code
stringlengths
22
1.05M
apis
listlengths
1
3.31k
extract_api
stringlengths
75
3.25M
# -*- encoding: utf-8 -*- # Importação das bibliotecas necessárias. import mysql.connector import datetime # Configuração da conexão. connection = mysql.connector.connect( host="localhost", user="root", password="", database="teste" ) # Variável que executará as operações. cursor = connection.cursor() # Comando e dados. sql = "INSERT INTO users (name, email, created) VALUES (%s, %s, %s)" data = ( "Primeiro usuário", "<EMAIL>", datetime.datetime.today() ) # Execução e efetivação do comando. cursor.execute(sql, data) connection.commit() # Obtenção do ID do usuário recém-cadastrado. userid = cursor.lastrowid # Fechamento da conexão. cursor.close() connection.close() # Exibição do último ID inserido no banco de dados. print("Foi cadastrado o nome usuário de ID: ", userid)
[ "datetime.datetime.today" ]
[((463, 488), 'datetime.datetime.today', 'datetime.datetime.today', ([], {}), '()\n', (486, 488), False, 'import datetime\n')]
# Unit Tests for the Enum Combo Box import pytest from logging import ERROR from qtpy.QtCore import Slot, Qt from ...widgets.enum_combo_box import PyDMEnumComboBox from ... import data_plugins # -------------------- # POSITIVE TEST CASES # -------------------- def test_construct(qtbot): """ Test the construction of the widget. Expectations: All the default values are properly set. Parameters ---------- qtbot : fixture pytest-qt window for widget test """ pydm_enumcombobox = PyDMEnumComboBox() qtbot.addWidget(pydm_enumcombobox) assert pydm_enumcombobox._has_enums is False assert pydm_enumcombobox.contextMenuPolicy() == Qt.DefaultContextMenu assert pydm_enumcombobox.contextMenuEvent == pydm_enumcombobox.open_context_menu @pytest.mark.parametrize("enums", [ ("spam", "eggs", "ham"), ("spam",), ("",), ]) def test_set_items(qtbot, enums): """ Test the populating of enum string (choices) to the widget. Expectations: All enum strings are populated to the widget, and the _has_enum flag is set to True if the enum string list is not empty. Parameters ---------- qtbot : fixture pytest-qt window for widget test enums : tuple A list of enum strings to be populated as choices to the widget. """ pydm_enumcombobox = PyDMEnumComboBox() qtbot.addWidget(pydm_enumcombobox) assert pydm_enumcombobox.count() == 0 pydm_enumcombobox.set_items(enums) assert pydm_enumcombobox.count() == len(enums) assert all([enums[i] == pydm_enumcombobox.itemText(i) for i in range(0, len(enums))]) assert pydm_enumcombobox._has_enums is True if len(enums) else pydm_enumcombobox._has_enums is False @pytest.mark.parametrize("connected, write_access, has_enum, is_app_read_only", [ (True, True, True, True), (True, True, True, False), (True, True, False, True), (True, True, False, False), (True, False, False, True), (True, False, False, False), (True, False, True, True), (True, False, True, False), (False, True, True, True), (False, True, True, False), (False, False, True, True), (False, False, True, False), (False, True, False, True), (False, True, False, False), (False, False, False, True), (False, False, False, False), ]) def test_check_enable_state(qtbot, signals, connected, write_access, has_enum, is_app_read_only): """ Test the tooltip generated depending on the channel connection, write access, whether the widget has enum strings, and whether the app is read-only. Expectations: 1. If the data channel is disconnected, the widget's tooltip will display "PV is disconnected" 2. If the data channel is connected, but it has no write access: a. If the app is read-only, the tooltip will read "Running PyDM on Read-Only mode." b. If the app is not read-only, the tooltip will read "Access denied by Channel Access Security." 3. If the widget does not have any enum strings, the tooltip will display "Enums not available". Parameters ---------- qtbot : fixture Window for widget testing signals : fixture The signals fixture, which provides access signals to be bound to the appropriate slots connected : bool True if the channel is connected; False otherwise write_access : bool True if the widget has write access to the channel; False otherwise has_enum: bool True if the widget has enum strings populated; False if the widget contains no enum strings (empty of choices) is_app_read_only : bool True if the PyDM app is read-only; False otherwise """ pydm_enumcombobox = PyDMEnumComboBox() qtbot.addWidget(pydm_enumcombobox) signals.write_access_signal[bool].connect(pydm_enumcombobox.writeAccessChanged) signals.write_access_signal[bool].emit(write_access) signals.connection_state_signal[bool].connect(pydm_enumcombobox.connectionStateChanged) signals.connection_state_signal[bool].emit(connected) if has_enum: signals.enum_strings_signal[tuple].connect(pydm_enumcombobox.enumStringsChanged) signals.enum_strings_signal[tuple].emit(("START", "STOP", "PAUSE")) assert pydm_enumcombobox._has_enums data_plugins.set_read_only(is_app_read_only) original_tooltip = "Original Tooltip" pydm_enumcombobox.setToolTip(original_tooltip) pydm_enumcombobox.check_enable_state() actual_tooltip = pydm_enumcombobox.toolTip() if not pydm_enumcombobox._connected: assert "PV is disconnected." in actual_tooltip elif not write_access: if data_plugins.is_read_only(): assert "Running PyDM on Read-Only mode." in actual_tooltip else: assert "Access denied by Channel Access Security." in actual_tooltip elif not pydm_enumcombobox._has_enums: assert "Enums not available" in actual_tooltip @pytest.mark.parametrize("values, selected_index, expected", [ (("RUN", "STOP"), 0, "RUN"), (("RUN", "STOP"), 1, "STOP"), (("RUN", "STOP"), "RUN", "RUN"), (("RUN", "STOP"), "STOP", "STOP"), ]) def test_enum_strings_changed(qtbot, signals, values, selected_index, expected): """ Test the widget's handling of enum strings, which are choices presented to the user, and the widget's ability to update the selected enum string when the user provides a choice index. This test will also cover value_changed() testing. Expectations: The widget displays the correct enum string whose index from the enum string tuple is selected by the user. Parameters ---------- qtbot : fixture pytest-qt window for widget testing signals : fixture The signals fixture, which provides access signals to be bound to the appropriate slots values : tuple A set of enum strings for the user to choose from selected_index : int The index from the enum string tuple chosen by the user expected : str The expected enum string displayed by the widget after receiving the user's choice index """ pydm_enumcombobox = PyDMEnumComboBox() qtbot.addWidget(pydm_enumcombobox) signals.enum_strings_signal.connect(pydm_enumcombobox.enumStringsChanged) signals.enum_strings_signal.emit(values) signals.new_value_signal[type(selected_index)].connect(pydm_enumcombobox.channelValueChanged) signals.new_value_signal[type(selected_index)].emit(selected_index) assert pydm_enumcombobox.value == selected_index assert pydm_enumcombobox.currentText() == expected @pytest.mark.parametrize("index", [ 0, 1, -1, ]) def test_internal_combo_box_activated_int(qtbot, signals, index): """ Test the the capability of the widget's activated slot in sending out a new enum string index value. Expectations: The value sent out from the "activated" slot reflects the correct new index value. Parameters ---------- qtbot : fixture pytest-qt window for widget test signals : fixture The signals fixture, which provides access signals to be bound to the appropriate slots index : int The new enum string index value """ pydm_enumcombobox = PyDMEnumComboBox() qtbot.addWidget(pydm_enumcombobox) # Connect the send_value_signal also to the conftest's receiveValue slot to intercept and verify that the correct # new index value is sent out pydm_enumcombobox.send_value_signal[int].connect(signals.receiveValue) pydm_enumcombobox.activated[int].emit(index) assert signals.value == index # -------------------- # NEGATIVE TEST CASES # -------------------- @pytest.mark.parametrize("enums, expected_error_message", [ (None, "Invalid enum value '{0}'. The value is expected to be a valid list of string values.".format(None)), ((None, "abc"), "Invalid enum type '{0}'. The expected type is 'string'.".format(type(None))), ((None, 123.456), "Invalid enum type '{0}'. The expected type is 'string'".format(type(None))), ((None, None, None), "Invalid enum type '{0}'. The expected type is 'string'".format(type(None))), ((123,), "Invalid enum type '{0}'. The expected type is 'string'".format(type(123))), ((123.45,), "Invalid enum type '{0}'. The expected type is 'string'".format(type(123.45))), ((123, 456), "Invalid enum type '{0}'. The expected type is 'string'".format(type(123))), ((123.456, None), "Invalid enum type '{0}'. The expected type is 'string'".format(type(123.456))), (("spam", 123, "eggs", "ham"), "Invalid enum type '{0}'. The expected type is 'string'".format(type(123))), ]) def test_set_items_neg(qtbot, caplog, enums, expected_error_message): """ Test sending setting the widget with an undefined list of enum strings. Expectations: The correct error message is logged. Parameters ---------- qtbot : fixture pytest-qt window for widget test caplog : fixture To capture the log messages enums : tuple A list of strings as enum strings (choices) to populate to the widget. """ pydm_enumcombobox = PyDMEnumComboBox() qtbot.addWidget(pydm_enumcombobox) pydm_enumcombobox.set_items(enums) for record in caplog.records: assert record.levelno == ERROR assert expected_error_message in caplog.text @pytest.mark.parametrize("values, selected_index, expected", [ (("ON", "OFF"), 3, ""), (("ON", "OFF"), -1, ""), ]) def test_enum_strings_changed_incorrect_index(qtbot, signals, values, selected_index, expected): """ Test the widget's handling of incorrectly provided enum string index. Expectations: The widget will display an empty string. Parameters ---------- qtbot : fixture pytest-qt window for widget testing signals : fixture The signals fixture, which provides access signals to be bound to the appropriate slots value : tuple A set of enum strings for the user to choose from selected_index : int The incorrect (out-of-bound) index from the enum string tuple chosen by the user expected : int The expected text displayed by the widget to notify the user of the incorrect choice index """ pydm_enumcombobox = PyDMEnumComboBox() qtbot.addWidget(pydm_enumcombobox) signals.enum_strings_signal.connect(pydm_enumcombobox.enumStringsChanged) signals.enum_strings_signal.emit(values) signals.new_value_signal[type(selected_index)].connect(pydm_enumcombobox.channelValueChanged) signals.new_value_signal[type(selected_index)].emit(selected_index) assert pydm_enumcombobox.value == selected_index assert pydm_enumcombobox.currentText() == expected
[ "pytest.mark.parametrize" ]
[((801, 878), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""enums"""', "[('spam', 'eggs', 'ham'), ('spam',), ('',)]"], {}), "('enums', [('spam', 'eggs', 'ham'), ('spam',), ('',)])\n", (824, 878), False, 'import pytest\n'), ((1754, 2315), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""connected, write_access, has_enum, is_app_read_only"""', '[(True, True, True, True), (True, True, True, False), (True, True, False, \n True), (True, True, False, False), (True, False, False, True), (True, \n False, False, False), (True, False, True, True), (True, False, True, \n False), (False, True, True, True), (False, True, True, False), (False, \n False, True, True), (False, False, True, False), (False, True, False, \n True), (False, True, False, False), (False, False, False, True), (False,\n False, False, False)]'], {}), "('connected, write_access, has_enum, is_app_read_only',\n [(True, True, True, True), (True, True, True, False), (True, True, \n False, True), (True, True, False, False), (True, False, False, True), (\n True, False, False, False), (True, False, True, True), (True, False, \n True, False), (False, True, True, True), (False, True, True, False), (\n False, False, True, True), (False, False, True, False), (False, True, \n False, True), (False, True, False, False), (False, False, False, True),\n (False, False, False, False)])\n", (1777, 2315), False, 'import pytest\n'), ((4991, 5187), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""values, selected_index, expected"""', "[(('RUN', 'STOP'), 0, 'RUN'), (('RUN', 'STOP'), 1, 'STOP'), (('RUN', 'STOP'\n ), 'RUN', 'RUN'), (('RUN', 'STOP'), 'STOP', 'STOP')]"], {}), "('values, selected_index, expected', [(('RUN',\n 'STOP'), 0, 'RUN'), (('RUN', 'STOP'), 1, 'STOP'), (('RUN', 'STOP'),\n 'RUN', 'RUN'), (('RUN', 'STOP'), 'STOP', 'STOP')])\n", (5014, 5187), False, 'import pytest\n'), ((6659, 6703), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""index"""', '[0, 1, -1]'], {}), "('index', [0, 1, -1])\n", (6682, 6703), False, 'import pytest\n'), ((9434, 9548), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""values, selected_index, expected"""', "[(('ON', 'OFF'), 3, ''), (('ON', 'OFF'), -1, '')]"], {}), "('values, selected_index, expected', [(('ON', 'OFF'),\n 3, ''), (('ON', 'OFF'), -1, '')])\n", (9457, 9548), False, 'import pytest\n')]
import os import random import argparse import multiprocessing import numpy as np import torch from torchvision import models, transforms from torch.utils.data import DataLoader, Dataset from pathlib import Path from PIL import Image from utils import Bar, config, mkdir_p, AverageMeter from datetime import datetime from tensorboardX import SummaryWriter from byol_pytorch import BYOL # arguments parser = argparse.ArgumentParser(description='byol-lightning-test') # Architecture & hyper-parameter parser.add_argument('--arch', '-a', metavar='ARCH', default='resnet', help='model architecture: | [resnet, ...] (default: resnet18)') parser.add_argument('--depth', type=int, default=18, help='Model depth.') parser.add_argument('-c', '--checkpoint', default='../checkpoints', type=str, metavar='PATH', help='path to save checkpoint (default: checkpoint)') parser.add_argument('--epoch', type=int, default=100, help='Epoch') parser.add_argument('--batch-size', type=int, default=32, help='Epoch') parser.add_argument('--lr', '--learning-rate', default=0.1, type=float, metavar='LR', help='initial learning rate') # Device options parser.add_argument('--manualSeed', type=int, help='manual seed') parser.add_argument('--gpu-id', default='0', type=str, help='id(s) for CUDA_VISIBLE_DEVICES') # Paths parser.add_argument('-d', '--dataset', default='neu', type=str) parser.add_argument('--image_folder', type=str, required=True, help='path to your folder of images for self-supervised learning') parser.add_argument('--board-path', '--bp', default='../board', type=str, help='tensorboardx path') parser.add_argument('--board-tag', '--tg', default='byol', type=str, help='tensorboardx writer tag') args = parser.parse_args() # Use CUDA os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id use_cuda = torch.cuda.is_available() # Torch Seed # Random seed if args.manualSeed is None: args.manualSeed = random.randint(1, 10000) # Random Lib Seed random.seed(args.manualSeed) # Numpy Seed np.random.seed(args.manualSeed) if use_cuda: torch.cuda.manual_seed_all(args.manualSeed) # constants args.image_size = 256 NUM_GPUS = 1 IMAGE_EXTS = ['.jpg', '.png', '.jpeg', '.bmp'] NUM_WORKERS = multiprocessing.cpu_count() # task_time = datetime.now().isoformat() # args.checkpoint = os.path.join(args.checkpoint, args.dataset, "{}-{}{:d}-bs{:d}-lr{:.5f}-{}".format(args.arch, # args.depth, # args.batch_size, # args.lr, # args.board_tag), # task_time) # if not os.path.isdir(args.checkpoint): # mkdir_p(args.checkpoint) # config.save_config(args, os.path.join(args.checkpoint, "config.txt")) # # writer_train = SummaryWriter( # log_dir=os.path.join(args.board_path, args.dataset, "{}-{}{:d}-bs{:d}-lr{:.5f}-{}".format(args.arch, # args.depth, # args.batch_size, # args.lr, # args.board_tag), # task_time, "train")) args.task_time = datetime.now().isoformat() output_name = "{}{:d}-bs{:d}-lr{:.5f}-{}".format(args.arch, args.depth, args.batch_size, args.lr, args.board_tag) args.checkpoint = os.path.join(args.checkpoint, args.dataset, output_name, args.task_time) if not os.path.isdir(args.checkpoint): mkdir_p(args.checkpoint) config.save_config(args, os.path.join(args.checkpoint, "config.txt")) writer_train = SummaryWriter( log_dir=os.path.join(args.board_path, args.dataset, output_name, args.task_time)) normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) def expand_greyscale(t): return t.expand(3, -1, -1) class ImagesDataset(Dataset): def __init__(self, folder, image_size): super().__init__() self.folder = folder self.paths = [] for path in Path(f'{folder}').glob('**/*'): _, ext = os.path.splitext(path) if ext.lower() in IMAGE_EXTS: self.paths.append(path) print(f'{len(self.paths)} images found') self.transform = transforms.Compose([ transforms.Resize(args.image_size), transforms.RandomSizedCrop((args.image_size, args.image_size)), transforms.ColorJitter(0.4, 0.4, 0.4), transforms.ToTensor(), # normalize ]) def __len__(self): return len(self.paths) def __getitem__(self, index): path = self.paths[index] img = Image.open(path) img = img.convert('RGB') return self.transform(img) if args.arch is "resnet": if args.depth == 18: model = models.resnet18(pretrained=False).cuda() elif args.depth == 34: model = models.resnet34(pretrained=False).cuda() elif args.depth == 50: model = models.resnet50(pretrained=False).cuda() elif args.depth == 101: model = models.resnet101(pretrained=False).cuda() else: assert ("Not supported Depth") learner = BYOL( model, image_size=args.image_size, hidden_layer='avgpool', projection_size=256, projection_hidden_size=4096, moving_average_decay=0.99, use_momentum=False # turn off momentum in the target encoder ) opt = torch.optim.Adam(learner.parameters(), lr=args.lr) ds = ImagesDataset(args.image_folder, args.image_size) trainloader = DataLoader(ds, batch_size=args.batch_size, num_workers=NUM_WORKERS, shuffle=True) losses = AverageMeter() for epoch in range(args.epoch): bar = Bar('Processing', max=len(trainloader)) for batch_idx, inputs in enumerate(trainloader): loss = learner(inputs.cuda()) losses.update(loss.data.item(), inputs.size(0)) opt.zero_grad() loss.backward() opt.step() # plot progress bar.suffix = 'Epoch {epoch} - ({batch}/{size}) | Total: {total:} | ETA: {eta:} | Loss: {loss:.4f} '.format( epoch=epoch, batch=batch_idx + 1, size=len(trainloader), total=bar.elapsed_td, eta=bar.eta_td, loss=loss.item(), ) n_iter = epoch * len(trainloader) + batch_idx + 1 writer_train.add_scalar('Train/loss', loss.data.item(), n_iter) bar.next() writer_train.add_scalar('Avg.loss', losses.avg, epoch) bar.finish() # save your improved network torch.save(model.state_dict(), os.path.join(args.checkpoint, 'byol.pt'))
[ "utils.mkdir_p", "torchvision.models.resnet18", "multiprocessing.cpu_count", "torchvision.transforms.ColorJitter", "torch.cuda.is_available", "argparse.ArgumentParser", "pathlib.Path", "os.path.isdir", "numpy.random.seed", "torchvision.transforms.ToTensor", "random.randint", "torchvision.model...
[((409, 467), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""byol-lightning-test"""'}), "(description='byol-lightning-test')\n", (432, 467), False, 'import argparse\n'), ((1935, 1960), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1958, 1960), False, 'import torch\n'), ((2082, 2110), 'random.seed', 'random.seed', (['args.manualSeed'], {}), '(args.manualSeed)\n', (2093, 2110), False, 'import random\n'), ((2125, 2156), 'numpy.random.seed', 'np.random.seed', (['args.manualSeed'], {}), '(args.manualSeed)\n', (2139, 2156), True, 'import numpy as np\n'), ((2327, 2354), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (2352, 2354), False, 'import multiprocessing\n'), ((4161, 4233), 'os.path.join', 'os.path.join', (['args.checkpoint', 'args.dataset', 'output_name', 'args.task_time'], {}), '(args.checkpoint, args.dataset, output_name, args.task_time)\n', (4173, 4233), False, 'import os\n'), ((4502, 4577), 'torchvision.transforms.Normalize', 'transforms.Normalize', ([], {'mean': '[0.485, 0.456, 0.406]', 'std': '[0.229, 0.224, 0.225]'}), '(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n', (4522, 4577), False, 'from torchvision import models, transforms\n'), ((5992, 6161), 'byol_pytorch.BYOL', 'BYOL', (['model'], {'image_size': 'args.image_size', 'hidden_layer': '"""avgpool"""', 'projection_size': '(256)', 'projection_hidden_size': '(4096)', 'moving_average_decay': '(0.99)', 'use_momentum': '(False)'}), "(model, image_size=args.image_size, hidden_layer='avgpool',\n projection_size=256, projection_hidden_size=4096, moving_average_decay=\n 0.99, use_momentum=False)\n", (5996, 6161), False, 'from byol_pytorch import BYOL\n'), ((6353, 6439), 'torch.utils.data.DataLoader', 'DataLoader', (['ds'], {'batch_size': 'args.batch_size', 'num_workers': 'NUM_WORKERS', 'shuffle': '(True)'}), '(ds, batch_size=args.batch_size, num_workers=NUM_WORKERS, shuffle\n =True)\n', (6363, 6439), False, 'from torch.utils.data import DataLoader, Dataset\n'), ((6445, 6459), 'utils.AverageMeter', 'AverageMeter', ([], {}), '()\n', (6457, 6459), False, 'from utils import Bar, config, mkdir_p, AverageMeter\n'), ((2038, 2062), 'random.randint', 'random.randint', (['(1)', '(10000)'], {}), '(1, 10000)\n', (2052, 2062), False, 'import random\n'), ((2174, 2217), 'torch.cuda.manual_seed_all', 'torch.cuda.manual_seed_all', (['args.manualSeed'], {}), '(args.manualSeed)\n', (2200, 2217), False, 'import torch\n'), ((4241, 4271), 'os.path.isdir', 'os.path.isdir', (['args.checkpoint'], {}), '(args.checkpoint)\n', (4254, 4271), False, 'import os\n'), ((4277, 4301), 'utils.mkdir_p', 'mkdir_p', (['args.checkpoint'], {}), '(args.checkpoint)\n', (4284, 4301), False, 'from utils import Bar, config, mkdir_p, AverageMeter\n'), ((4327, 4370), 'os.path.join', 'os.path.join', (['args.checkpoint', '"""config.txt"""'], {}), "(args.checkpoint, 'config.txt')\n", (4339, 4370), False, 'import os\n'), ((7379, 7419), 'os.path.join', 'os.path.join', (['args.checkpoint', '"""byol.pt"""'], {}), "(args.checkpoint, 'byol.pt')\n", (7391, 7419), False, 'import os\n'), ((3806, 3820), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (3818, 3820), False, 'from datetime import datetime\n'), ((4415, 4487), 'os.path.join', 'os.path.join', (['args.board_path', 'args.dataset', 'output_name', 'args.task_time'], {}), '(args.board_path, args.dataset, output_name, args.task_time)\n', (4427, 4487), False, 'import os\n'), ((5483, 5499), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (5493, 5499), False, 'from PIL import Image\n'), ((4899, 4921), 'os.path.splitext', 'os.path.splitext', (['path'], {}), '(path)\n', (4915, 4921), False, 'import os\n'), ((4846, 4863), 'pathlib.Path', 'Path', (['f"""{folder}"""'], {}), "(f'{folder}')\n", (4850, 4863), False, 'from pathlib import Path\n'), ((5113, 5147), 'torchvision.transforms.Resize', 'transforms.Resize', (['args.image_size'], {}), '(args.image_size)\n', (5130, 5147), False, 'from torchvision import models, transforms\n'), ((5161, 5223), 'torchvision.transforms.RandomSizedCrop', 'transforms.RandomSizedCrop', (['(args.image_size, args.image_size)'], {}), '((args.image_size, args.image_size))\n', (5187, 5223), False, 'from torchvision import models, transforms\n'), ((5237, 5274), 'torchvision.transforms.ColorJitter', 'transforms.ColorJitter', (['(0.4)', '(0.4)', '(0.4)'], {}), '(0.4, 0.4, 0.4)\n', (5259, 5274), False, 'from torchvision import models, transforms\n'), ((5288, 5309), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (5307, 5309), False, 'from torchvision import models, transforms\n'), ((5637, 5670), 'torchvision.models.resnet18', 'models.resnet18', ([], {'pretrained': '(False)'}), '(pretrained=False)\n', (5652, 5670), False, 'from torchvision import models, transforms\n'), ((5721, 5754), 'torchvision.models.resnet34', 'models.resnet34', ([], {'pretrained': '(False)'}), '(pretrained=False)\n', (5736, 5754), False, 'from torchvision import models, transforms\n'), ((5805, 5838), 'torchvision.models.resnet50', 'models.resnet50', ([], {'pretrained': '(False)'}), '(pretrained=False)\n', (5820, 5838), False, 'from torchvision import models, transforms\n'), ((5890, 5924), 'torchvision.models.resnet101', 'models.resnet101', ([], {'pretrained': '(False)'}), '(pretrained=False)\n', (5906, 5924), False, 'from torchvision import models, transforms\n')]
from sys import stdin a,b = [int(x) for x in stdin.readline().split(' ')] diff = abs(a-b) +1 a = min(a,b) +1 print(a) for x in range(1,diff): print(a+x)
[ "sys.stdin.readline" ]
[((46, 62), 'sys.stdin.readline', 'stdin.readline', ([], {}), '()\n', (60, 62), False, 'from sys import stdin\n')]
import os class Cajero: def __init__(self): self.continuar = True self.monto = 5000 self.menu() def contraseña(self): contador = 1 while contador <= 3: x = int(input("ingrese su contraseña:" )) if x == 5467: print("Contraseña Correcta") break else: print(f"Contraseña Incorrecta, le quedan {3 - contador} intentos") if contador == 3: print("No puede realizar operaciones.") self.continuar = False contador+=1 def menu(self): os.system("cls") #esto es solo para windows self.contraseña() opcion = 0 while opcion != "4": os.system("cls") print(""" Bienvenido al cajero automatico ***Menú*** 1- Depositar 2- Retirar 3- Ver saldo 4- Salir """) opcion = input("Su opción es: ") if self.continuar: if opcion == "1" : self.depositar() elif opcion == "2" : self.retiro() elif opcion == "3": self.ver() elif opcion == "4": print("Programa finalizado") else: print("NO existe esa opción") else: if opcion in "123": print("Imposible realizar esa operación") elif opcion == "4": print("Programa finalizado") else: print("No existe esa opción") def depositar(self): dep = int(input("Ingrese su monto a depositar:")) print("Usted a depositado:",dep) print(f"Su nuevo saldo es {self.monto + dep}") self.monto+=dep def retiro(self): retirar=int(input("¿Cuánto desea retirar? : ")) print("Su monto actual es", self.monto) if self.monto >= retirar : print(f"Usted a retirado: {retirar} , su nuevo monto es {self.monto - retirar}") self.monto-=retirar else: print("Imposible realizar el retiro, su monto es menor") def ver(self): print("Su saldo es: " , self.monto) app = Cajero()
[ "os.system" ]
[((651, 667), 'os.system', 'os.system', (['"""cls"""'], {}), "('cls')\n", (660, 667), False, 'import os\n'), ((783, 799), 'os.system', 'os.system', (['"""cls"""'], {}), "('cls')\n", (792, 799), False, 'import os\n')]
from threading import Thread, enumerate from random import choice from time import sleep as slp from time import time as tiime from os import mkdir, getcwd, path as pth from subprocess import run as run_ from math import ceil from traceback import format_exc from sys import exit import logging, json, ctypes from ppadb.client import Client from PIL import Image, UnidentifiedImageError, ImageFile from numpy import array from imagehash import average_hash from pytesseract import pytesseract from pytesseract import image_to_string from langdetect import detect, DetectorFactory from fuzzywuzzy.process import extractOne from difflib import SequenceMatcher from cv2 import bilateralFilter from requests import get if pth.exists('./.cache') == False: mkdir('./.cache') logging.basicConfig( handlers=[logging.FileHandler("./.cache/log.log", "a", "utf-8")], level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", datefmt="%m/%d/%Y %I:%M:%S %p", ) ImageFile.LOAD_TRUNCATED_IMAGES = True pytesseract.tesseract_cmd = ('./tesseract/tesseract.exe') update_notice_ = Image.open('./base/login/update_notice.png') introduction_ = Image.open('./base/login/introduction.png') tap_to_play_ = Image.open('./base/login/tap_to_play.png') tap_to_play_2_ = Image.open('./base/login/tap_to_play_2.png') community_ = Image.open('./base/login/community.png') sale_ = Image.open('./base/login/sale.png') attendance_ = Image.open('./base/login/attendance.png') event_ = Image.open('./base/login/event.png') guild_attendance_ = Image.open('./base/login/guild_attendance.png') accumualated_ = Image.open('./base/login/accumualated.png') sale_2_ = Image.open('./base/login/sale_2.png') special_shop_ = Image.open('./base/login/special_shop.png') home_screen_ = Image.open('./base/login/home_screen.png') mb_ = Image.open('./base/login/mission_button.png') loh_new_ = Image.open('./base/loh/loh_new.png') kr_discord_ = Image.open('./base/login/kr_discord.png') def crop(img, dimesions): # size of the image in pixels (size of original image) width, height = img.size # cropped image im = img.crop((dimesions[0], dimesions[1], width-dimesions[2], height-dimesions[3])) return im def check_similar(img1, img2, cutoff, bonus): # get data for comparing image image1 = average_hash(img1) image2 = average_hash(img2) # compare if image1 - image2 < cutoff+bonus: return "similar" else: return "not" def filter(pil_image): open_cv_image = array(pil_image.convert('RGB')) open_cv_image = open_cv_image[:, :, ::-1].copy() return bilateralFilter(open_cv_image, 9, 75, 75) class Missions: def __init__(self): self.dragon_ = False self.friendship_ = False self.inn_ = False self.lov_ = False self.shop_ = False self.stockage_ = False self.tower_ = False self.wb_ = False self.lil_ = False self.launched = None self.cache_2 = None self.game_count = 0 self.game_home_screen_count = 0 self.error_count = 0 self.gb_cf = None def update_cache(self, device, check_crash=True): count = 0 while True: try: device.shell('screencap -p /sdcard/screencap.png') device.pull('/sdcard/screencap.png', './.cache/screencap-'+str(device.serial)+'.png') im = Image.open('./.cache/screencap-'+str(device.serial)+'.png') if check_crash == True: if self.cache_2 is not None: try: if check_similar(self.cache_2, im, 5, self.gb_cf['bonus_cutoff']) == 'similar': self.game_count+=1 if self.game_count >= 50: # game freeze device.shell('am force-stop com.vespainteractive.KingsRaid') slp(3) device.shell('monkey -p com.vespainteractive.KingsRaid 1') slp(3) self.game_count = 0 self.run_execute(device, self.launched) exit() else: self.cache_2 = im self.game_count = 0 self.emulator_count = 0 except OSError: self.error_count += 1 if self.error_count >= 50: self.error_count = 0 break self.cache_2 = im slp(5) continue else: self.cache_2 = im break except RuntimeError: self.error_count += 1 if self.error_count >= 50: self.error_count = 0 break if count == 50: im = "device offline" break count += 1 slp(5) except PermissionError or UnidentifiedImageError or ConnectionResetError: self.error_count += 1 if self.error_count >= 50: self.error_count = 0 break slp(5) return im, device def make_sure_loaded(self, original_img, device, dimensions=None, shell_=None, loop=None, sleep_duration=None, \ shell_first=False, cutoff=6, second_img=None, third_img=None, oposite=False, second_shell=None, ck=True, ck_special_shop=True): count = 0 count_ = 0 while True: if ck == True: self.check_login(device, ck_special_shop) # do adb shell first if passed if shell_ is not None: if shell_first is True: device.shell(shell_) if second_shell is not None: if shell_first is True: slp(3) device.shell(second_shell) # update cache if count_ >= 100: im, device = self.update_cache(device) else: im, device = self.update_cache(device, False) if dimensions is not None: cache = crop(im, dimensions) else: cache = im # get data for comparing image original = average_hash(Image.open(original_img)) cache = average_hash(cache) # compare bonus = self.gb_cf['bonus_cutoff'] if original - cache < cutoff+bonus: if oposite == True: pass else: break else: if second_img is not None: second = average_hash(Image.open(second_img)) if second - cache < cutoff+bonus: break else: if third_img is not None: third = average_hash(Image.open(third_img)) if third - cache < cutoff+bonus: break if oposite == True: break pass # adb shell if passed if shell_ is not None: if shell_first is False: device.shell(shell_) if second_shell is not None: if shell_first is False: slp(3) device.shell(second_shell) # break loop if given arg if loop is not None: if count == loop: return 'loop' count+=1 if sleep_duration is not None: slp(sleep_duration) count_+=1 def check_login(self, device, ck_special_shop): # get device resolution im, device = self.update_cache(device, check_crash=False) size_ = f"{im.size[0]}x{im.size[1]}" with open('./sets.json', encoding='utf-8') as j: data = json.load(j)[size_] count = 0 community_count = 0 bonus = self.gb_cf['bonus_cutoff'] im, device = self.update_cache(device) # android home screen im1 = home_screen_ im2 = crop(im, data['login']['home_screen']['dms']) home_screen = check_similar(im1, im2, 15, bonus) if home_screen == 'similar': logging.info(device.serial+': android home screen detected') device.shell('monkey -p com.vespainteractive.KingsRaid 1') slp(3) # login # update notice im1 = update_notice_ im2 = crop(im, data['update_notice']['dms']) update_notice = check_similar(im1, im2, 10, bonus) if update_notice == 'similar': logging.info(device.serial+': update notice detected') device.shell(data['update_notice']['shell']) slp(3) # introduction im1 = introduction_ im2 = crop(im, data['introduction']['dms']) introduction = check_similar(im1, im2, 10, bonus) if introduction == 'similar': logging.info(device.serial+': introduction detected') device.shell(data['introduction']['shell']) slp(3) # tap to play im1 = tap_to_play_ im2 = crop(im, data['tap_to_play']['dms']) tap_to_play = check_similar(im1, im2, 10, bonus) if tap_to_play == 'similar': logging.info(device.serial+': tap to play detected') device.shell(data['tap_to_play']['shell']) slp(3) # tap to play 2 im1 = tap_to_play_2_ im2 = crop(im, data['tap_to_play']['dms']) tap_to_play_2 = check_similar(im1, im2, 10, bonus) if tap_to_play_2 == 'similar': logging.info(device.serial+': tap to play 2 detected') device.shell(data['tap_to_play']['shell']) slp(3) # pass community page im1 = community_ im2 = crop(im, data['login']['community']['dms']) community = check_similar(im1, im2, 10, bonus) if community == 'similar': logging.info(device.serial+': community page detected') device.shell(data['login']['community']['shell']) slp(3) # pass sale page im1 = sale_ im2 = crop(im, data['login']['sale']['dms']) sale = check_similar(im1, im2, 10, bonus) if sale == 'similar': logging.info(device.serial+': sale page detected') device.shell(data['login']['sale']['shell']) slp(3) # claim login attendance im1 = attendance_ im2 = crop(im, data['login']['attendance']['dms']) attendance = check_similar(im1, im2, 10, bonus) if attendance == 'similar': logging.info(device.serial+': login attendance detected') device.shell(data['login']['attendance']['shell']) slp(1) device.shell(data['login']['attendance']['second_shell']) slp(3) # pass event page im1 = event_ im2 = crop(im, data['login']['event']['dms']) event = check_similar(im1, im2, 10, bonus) if event == 'similar': logging.info(device.serial+': event page detected') device.shell(data['login']['event']['shell']) slp(3) # claim guild attendance im1 = guild_attendance_ im2 = crop(im, data['login']['guild_attendance']['dms']) guild_attendance = check_similar(im1, im2, 10, bonus) if guild_attendance == 'similar': logging.info(device.serial+': guild attendance detected') for day in data['login']['guild_attendance']['days']: device.shell(day) slp(1) device.shell(data['login']['guild_attendance']['row_reward']) slp(1) device.shell(data['login']['guild_attendance']['exit']) slp(3) # claim login accumualated im1 = accumualated_ im2 = crop(im, data['login']['accumualated']['dms']) accumualated = check_similar(im1, im2, 10, bonus) if accumualated == 'similar': logging.info(device.serial+': login accumualated detected') device.shell(data['login']['accumualated']['shell']) slp(1) device.shell(data['login']['accumualated']['second_shell']) slp(3) # check loh new season im1 = loh_new_ im2 = crop(im, data['loh']['0']['dms']) loh_new = check_similar(im1, im2, 10, bonus) if loh_new == 'similar': logging.info(device.serial+': new loh season detected') device.shell(data['loh']['0']['shell']) slp(3) # sale 2 im1 = sale_2_ im2 = crop(im, data['login']['sale_2']['dms']) sale_2 = check_similar(im1, im2, 10, bonus) if sale_2 == 'similar': logging.info(device.serial+': sale 2 page detected') device.shell(data['login']['sale_2']['shell']) slp(1) device.shell(data['login']['sale_2']['second_shell']) slp(3) # special shop if ck_special_shop != False: im1 = special_shop_ im2 = crop(im, data['login']['special_shop']['dms']) special_shop = check_similar(im1, im2, 10, bonus) if special_shop == 'similar': logging.info(device.serial+': special shop detected') device.shell(data['login']['special_shop']['shell']) slp(3) # return to main page im1 = mb_ im2 = crop(im, data['login']['mission_button']) mb = check_similar(im1, im2, 20, bonus) if mb == 'similar': self.game_home_screen_count += 1 if self.game_home_screen_count >= 100: logging.info(device.serial+': game home screen detected') device.shell(data['daily']['shell']) self.game_home_screen_count = 0 self.run_execute(device, launched=self.launched) exit() def run_execute(self, device, launched=None): with open('./config.json') as j: self.gb_cf = json.load(j) try: self.execute(device, launched) except SystemExit: pass except ConnectionResetError: if launched is not None: text = device.serial+': connection to remote host was forcibly closed, closing emulator' print(text) logging.warn(text) path = self.gb_cf['ldconsole'].replace('|', '"') run_(path+f' quit --index {str(launched)}') except: var = format_exc() logging.warn(device.serial+': Exception | '+var) return def execute(self, device, launched=None): if launched is not None: self.launched = launched # get device resolution im, device = self.update_cache(device, check_crash=False) if im == 'device offline': if str(device.serial).startswith('127'): return text = 'device '+device.serial+' is offline, script ended' logging.info(text) print(text) return size_ = f"{im.size[0]}x{im.size[1]}" logging.info(device.serial+': size '+size_+' detected') with open('./sets.json', encoding='utf-8') as j: data = json.load(j)[size_] device.shell('monkey -p com.vespainteractive.KingsRaid 1') path = self.gb_cf['ldconsole'].replace('|', '"') def claim(): # claim rewards count = 0 while True: if count == 9: break device.shell(data['claim'][0]) device.shell(data['claim'][1]) count+=1 # open daily mission board self.make_sure_loaded('./base/other/daily.png', device, data['daily']['dms'], data['daily']['shell'], cutoff=8) if self.gb_cf['buff'] == True: # claim exp and gold buff in etc self.make_sure_loaded('./base/other/etc.png', device, data['buff']['1']['dms'], data['buff']['1']['shell'], second_img='./base/other/etc_2.png', third_img='./base/other/etc_3.png', cutoff=8) # claim exp buff self.make_sure_loaded('./base/other/use_exp.png', device, data['buff']['2']['dms'], data['buff']['2']['shell'], cutoff=15, sleep_duration=1, loop=5) self.make_sure_loaded('./base/other/etc.png', device, data['buff']['1']['dms'], data['buff']['2']['second_shell'], second_img='./base/other/etc_2.png', third_img='./base/other/etc_3.png', cutoff=8) slp(5) # claim gold buff self.make_sure_loaded('./base/other/use_gold.png', device, data['buff']['3']['dms'], data['buff']['3']['shell'], cutoff=15, sleep_duration=1, loop=5) self.make_sure_loaded('./base/other/etc.png', device, data['buff']['1']['dms'], data['buff']['3']['second_shell'], second_img='./base/other/etc_2.png', third_img='./base/other/etc_3.png', cutoff=8) # click back to mission board # open daily mission board self.make_sure_loaded('./base/other/daily.png', device, data['daily']['dms'], data['daily']['second_shell'], cutoff=8, shell_first=True, sleep_duration=0.5) claim() text = device.serial+': opened and claimed rewards (and exp/gold buff) on daily mission board for the first time' logging.info(text) print(text) # get game language im, device = self.update_cache(device) first_misison = crop(im, data['first mission']) image = filter(first_misison) text_lang = image_to_string(image).splitlines()[0].lower().replace('♀', '') while True: try: lang = detect(text_lang) break except: device.shell(data['daily']['second_shell']) slp(1) claim() slp(5) continue if lang == 'en' or lang == 'da' or lang == 'fr': lang = 'eng' elif lang == 'ja': lang = 'jpn' elif lang == 'vi': lang = 'vie' else: with open('./languages.json', encoding='utf-8') as j: langs = json.load(j) lang = None missions_ = [] langs_ = [] _langs_ = {} for lang__ in langs: langs_.append(lang__) for _lang_ in langs[lang__]: missions_.append(_lang_) _langs_[_lang_] = lang__ for lang__ in langs_: text_lang = image_to_string(image, lang__).splitlines()[0].lower().replace('♀', '') if lang__ == 'jpn': text_lang = text_lang.replace(' ', '') lang_ = extractOne(text_lang, missions_) print(lang_[1]) if lang_[1] > 85: lang = _langs_[lang_[0]] if lang is None: text = device.serial+': language not supported or cannot recognized (supported languages: english, japanese, vietnamese)' logging.info(text) print(text) if self.launched is not None: text = device.serial+': because launched from config so closing after done' logging.info(text) print(text) run_(path+f' quit --index {str(self.launched)}') exit() # check for undone missions not_done = [] not_done_ = [] count = 0 while True: im, device = self.update_cache(device) # get 4 visible missions on mission board visible_missions = [crop(im, data['first mission']), crop(im, data['second mission']), \ crop(im, data['third mission']), crop(im, data['fourth mission'])] if not_done_ == not_done: if count >= 20: self.weekly(device, data) if self.gb_cf['mails'] == True: self.mails(device, data) if self.gb_cf['loh'] == True: re = self.loh(device, data, lang) if re != 'success': text = device.serial+': loh not enough currency or unavailable' logging.info(text) print(text) text = device.serial+': all avalible missions has been completed, script ended' logging.info(text) print(text) if self.launched is not None: text = device.serial+': because launched from config so closing after done' logging.info(text) print(text) run_(path+f' quit --index {str(self.launched)}') exit() count+=1 not_done_ = not_done count_ = 0 for mission in visible_missions: pil_image = mission text = image_to_string(pil_image, lang).splitlines()[0].lower().replace('♀', '') if text == ' ': img = filter(pil_image) text = image_to_string(img, lang).splitlines()[0].lower().replace('♀', '') re = self.do_mission(text, device, data['shortcut'][str(count_)], data, size_, lang) if re == 'not': if text not in not_done: not_done.append(text) else: self.make_sure_loaded('./base/other/daily.png', device, data['daily']['dms'], data['daily']['shell'], cutoff=8) claim() logging.info(device.serial+': opened and claimed rewards on daily mission board') break count_+=1 def do_mission(self, mission, device, pos, data, res, lang): with open('./languages.json', encoding='utf-8') as j: lang_data = json.load(j)[lang] lst = [] for name in lang_data: lst.append(name) ext = extractOne(mission, lst) re = lang_data[ext[0]] if re == 'dragon': if self.gb_cf['dragon'] == False: return 'not' if self.dragon_ == True: return 'not' return self.dragon(device, pos, data, lang) elif re == 'friendship': if self.gb_cf['friendship'] == False: return 'not' if self.friendship_ == True: return 'not' return self.friendship(device, pos, data) elif re == 'inn': if self.gb_cf['inn'] == False: return 'not' if self.inn_ == True: return 'not' return self.inn(device, pos, data) elif re == 'lov': if self.gb_cf['lov'] == False: return 'not' if self.lov_ == True: return 'not' return self.lov(device, pos, data) elif re == 'shop': if self.gb_cf['shop'] == False: return 'not' if self.shop_ == True: return 'not' return self.shop(device, pos, data) elif re == 'stockage': if self.gb_cf['stockage'] == False: return 'not' if self.stockage_ == True: return 'not' return self.stockage(device, pos, data) elif re == 'tower': if self.gb_cf['tower'] == False: return 'not' if self.tower_ == True: return 'not' return self.tower(device, pos, data, lang) elif re == 'wb': if self.gb_cf['wb'] == False: return 'not' if self.wb_ == True: return 'not' return self.wb(device, pos, data) elif re == 'lil': if self.gb_cf['lil'] == False: return 'not' if self.lil_ == True: return 'not' return self.lil(device, pos, data, res) elif re == 'dungeons': return 'not' elif re == 'stamina': return 'not' elif re == 'login': return 'not' def dragon(self, device, position, data, lang): print(device.serial+': hunting dragon...') logging.info(device.serial+': hunting dragon') # click mission shortcut shortcut = self.make_sure_loaded('./base/dragon/raid_list.png', device, data['dragon']['1']['dms'], data['dragon']['1']['shell']+position, cutoff=20, loop=20, sleep_duration=10) if shortcut == 'loop': self.dragon_ = True return 'not' logging.info(device.serial+': loaded from mission shortcut') # click create red dragon raid self.make_sure_loaded('./base/dragon/red_dra.png', device, data['dragon']['2']['dms'], data['dragon']['2']['shell']) logging.info(device.serial+': clicked create dragon raid') with open('./languages.json', encoding='utf-8') as j: dragon_text = json.load(j)[lang]['dragon'] # change hard level to t6 stage 1 while True: im, device = self.update_cache(device) pil_image = crop(im, data['dragon']['3']['dms']) img = filter(pil_image) text = image_to_string(img, lang).replace('♀', '') if lang == 'jpn': text = text.replace(' ', '') text_ = text.splitlines()[0].lower().replace(' ', '') if SequenceMatcher(None, dragon_text, text_).ratio() > 0.9: device.shell(data['dragon']['3']['shell']) break else: device.shell(data['dragon']['4']['shell']) logging.info(device.serial+': changed to dragon t6 stage 1') # click single raid self.make_sure_loaded('./base/dragon/single_raid.png', device, data['dragon']['5']['dms'], data['dragon']['5']['shell'], shell_first=True) logging.info(device.serial+': clicked single raid') # click enter raid self.make_sure_loaded('./base/dragon/party.png', device, data['dragon']['6']['dms'], data['dragon']['6']['shell'], sleep_duration=0.5, cutoff=20) logging.info(device.serial+': clicked enter raid') # check avalible party # slot 1 self.make_sure_loaded('./base/dragon/party_4.png', device, data['dragon']['7']['dms'], data['dragon']['7']['shell'], oposite=True, sleep_duration=1) # slot 2 self.make_sure_loaded('./base/dragon/party_3.png', device, data['dragon']['8']['dms'], data['dragon']['8']['shell'], oposite=True, sleep_duration=1) # slot 3 self.make_sure_loaded('./base/dragon/party_2.png', device, data['dragon']['9']['dms'], data['dragon']['9']['shell'], oposite=True, sleep_duration=1) # slot 4 self.make_sure_loaded('./base/dragon/party_1.png', device, data['dragon']['10']['dms'], data['dragon']['10']['shell'], oposite=True, sleep_duration=1) # slot 5 self.make_sure_loaded('./base/dragon/party_6.png', device, data['dragon']['11']['dms'], data['dragon']['11']['shell'], oposite=True, sleep_duration=1) # slot 6 self.make_sure_loaded('./base/dragon/party_5.png', device, data['dragon']['12']['dms'], data['dragon']['12']['shell'], oposite=True, sleep_duration=1) logging.info(device.serial+': checked all avalible slots') # click start battle self.make_sure_loaded('./base/dragon/battle.png', device, data['dragon']['13']['dms'], data['dragon']['13']['shell'], cutoff=30) logging.info(device.serial+': clicked start battle') # wait until finish self.make_sure_loaded('./base/dragon/end.png', device, data['dragon']['14']['dms'], sleep_duration=15, cutoff=10, ck=False, loop=4) logging.info(device.serial+': battle completed') # click exit battle self.make_sure_loaded('./base/dragon/party.png', device, data['dragon']['15']['dms'], data['dragon']['15']['shell'], sleep_duration=0.5) logging.info(device.serial+': exited battle') # click exit self.make_sure_loaded('./base/dragon/my_info.png', device, data['dragon']['16']['dms'], data['dragon']['16']['shell'], sleep_duration=0.5) device.shell(data['dragon']['17']['shell']) logging.info(device.serial+': successfully did dragon mission') self.dragon_ = True return 'success' def friendship(self, device, position, data): print(device.serial+': exchanging friendship points...') logging.info(device.serial+': exchanging friendship points') # click mission shortcut shortcut = self.make_sure_loaded('./base/friendship/friends.png', device, data['friendship']['1']['dms'], data['friendship']['1']['shell']+position, loop=20, cutoff=20, sleep_duration=10) if shortcut == 'loop': self.friendship_ = True return 'not' logging.info(device.serial+': loaded from mission shortcut') # click exchange friendship points self.make_sure_loaded('./base/friendship/exchange.png', device, data['friendship']['2']['dms'], data['friendship']['2']['shell'], cutoff=10, shell_first=True, loop=30) logging.info(device.serial+': clicked exchange friendship points') # click exit self.make_sure_loaded('./base/friendship/my_info.png', device, data['friendship']['3']['dms'], data['friendship']['3']['shell'], sleep_duration=0.5) device.shell(data['friendship']['4']['shell']) logging.info(device.serial+': successfully did friendship mission') self.friendship_ = True return 'success' def inn(self, device, position, data): print(device.serial+': doing stuffs in inn...') logging.info(device.serial+': doing stuffs in inn') # click mission shortcut shortcut = self.make_sure_loaded('./base/inn/visit_inn.png', device, data['inn']['1']['dms'], data['inn']['1']['shell']+position, cutoff=20, loop=20, sleep_duration=10) if shortcut == 'loop': self.inn_ = True return 'not' logging.info(device.serial+': loaded from mission shortcut') # open inn self.make_sure_loaded('./base/inn/inn.png', device, data['inn']['2']['dms'], data['inn']['2']['shell'], second_img='./base/inn/inn_.png', cutoff=15) logging.info(device.serial+': opened inn') # give gifts def gift(): slp(2) self.make_sure_loaded('./base/inn/greet.png', device, data['inn']['3']['dms'], data['inn']['3']['shell'], second_shell=data['inn']['2']['shell'], cutoff=10, \ second_img='./base/inn/greet_.png', third_img='./base/inn/greet__.png', loop=5, shell_first=True) self.make_sure_loaded('./base/inn/start_conversation.png', device, data['inn']['4']['dms'], data['inn']['4']['shell'], second_shell=data['inn']['2']['shell'], cutoff=10, \ second_img='./base/inn/start_conversation_.png', third_img='./base/inn/start_conversation__.png', loop=5, shell_first=True) self.make_sure_loaded('./base/inn/send_gift.png', device, data['inn']['5']['dms'], data['inn']['5']['shell'], second_shell=data['inn']['2']['shell'], cutoff=10, \ second_img='./base/inn/send_gift_.png', third_img='./base/inn/send_gift__.png', loop=5, shell_first=True) # choose hero in inn def choose_hero(tap1, tap2): self.make_sure_loaded('./base/inn/inn.png', device, data['inn']['6']['dms'], data['inn']['6']['shell']+str(tap1)+' '+str(tap2), shell_first=True, second_img='./base/inn/inn_.png', cutoff=25, second_shell=data['inn']['2']['shell']) # give gifts to first hero gift() logging.info(device.serial+': gave gifts to first hero') # give gifts to second hero choose_hero(data['inn']['7']['shell'][0], data['inn']['7']['shell'][1]) gift() logging.info(device.serial+': gave gifts to second hero') # give gifts to third hero choose_hero(data['inn']['8']['shell'][0], data['inn']['8']['shell'][1]) gift() logging.info(device.serial+': gave gifts to third hero') # give gifts to fourth hero choose_hero(data['inn']['9']['shell'][0], data['inn']['9']['shell'][1]) gift() logging.info(device.serial+': gave gifts to fourth hero') # give gifts to fifth hero choose_hero(data['inn']['10']['shell'][0], data['inn']['10']['shell'][1]) gift() logging.info(device.serial+': gave gifts to fifth hero') # give gifts to sixth hero choose_hero(data['inn']['11']['shell'][0], data['inn']['11']['shell'][1]) gift() logging.info(device.serial+': gave gifts to sixth hero') # click 'Mini Game' count = 0 while True: if count == 6: break self.make_sure_loaded('./base/inn/mini_game.png', device, data['inn']['12']['dms'], data['inn']['12']['shell']) slp(0.5) device.shell(data['inn']['13']['shell']) slp(0.5) self.make_sure_loaded('./base/inn/inn.png', device, data['inn']['14']['dms'], data['inn']['14']['shell'], cutoff=20, second_img='./base/inn/inn_.png') slp(1) count+=1 logging.info(device.serial+': played minigames') # click exit self.make_sure_loaded('./base/inn/visit_inn.png', device, data['inn']['15']['dms'], data['inn']['15']['shell'], cutoff=20, sleep_duration=3) self.make_sure_loaded('./base/inn/my_info.png', device, data['inn']['16']['dms'], data['inn']['16']['shell'], sleep_duration=0.5) device.shell(data['inn']['17']['shell']) logging.info(device.serial+': successfully did some stuffs in inn mission') self.inn_ = True return 'success' def lov(self, device, position, data): print(device.serial+': suiciding in lov...') logging.info(device.serial+': suiciding in lov') # click mission shortcut shortcut = self.make_sure_loaded('./base/lov/arena.png', device, data['lov']['1']['dms'], data['lov']['1']['shell']+position, loop=20, cutoff=20, sleep_duration=10) if shortcut == 'loop': self.lov_ = True return 'not' logging.info(device.serial+': loaded from mission shortcut') # click select arena self.make_sure_loaded('./base/lov/arenas.png', device, data['lov']['2']['dms'], data['lov']['2']['shell'], sleep_duration=0.5) logging.info(device.serial+': clicked select arena') # click enter lov self.make_sure_loaded('./base/lov/lov.png', device, data['lov']['3']['dms'], data['lov']['3']['shell'], sleep_duration=1) logging.info(device.serial+': clicked enter lov') # click ready to dual self.make_sure_loaded('./base/lov/party.png', device, data['lov']['4']['dms'], data['lov']['4']['shell'], sleep_duration=0.5, cutoff=20) logging.info(device.serial+': clicked ready to dual') # check avalible team self.make_sure_loaded('./base/lov/party_.png', device, data['lov']['5']['dms'], data['lov']['5']['shell'], sleep_duration=1, oposite=True, cutoff=20) logging.info(device.serial+': checked avalible team') # click register match self.make_sure_loaded('./base/lov/end.png', device, data['lov']['6']['dms'], data['lov']['6']['shell'], sleep_duration=0.5, cutoff=25, second_shell=data['lov']['6']['second_shell']) logging.info(device.serial+': clicked and exited battle') # click exit match self.make_sure_loaded('./base/lov/lov.png', device, data['lov']['7']['dms'], data['lov']['7']['shell'], sleep_duration=0.5) logging.info(device.serial+': exited match') # click exit self.make_sure_loaded('./base/lov/my_info.png', device, data['lov']['8']['dms'], data['lov']['8']['shell'], sleep_duration=0.5) device.shell(data['lov']['9']['shell']) logging.info(device.serial+': successfully did lov mission') self.lov_ = True return 'success' def shop(self, device, position, data): print(device.serial+': buying stuffs in shop...') logging.info(device.serial+': buying stuffs in shop') # click mission shortcut shortcut = self.make_sure_loaded('./base/shop/use_shop.png', device, data['shop']['1']['dms'], data['shop']['1']['shell']+position, loop=20, cutoff=20, sleep_duration=10) if shortcut == 'loop': self.shop_ = True return 'not' logging.info(device.serial+': loaded from mission shortcut') # open shop self.make_sure_loaded('./base/shop/shop.png', device, data['shop']['2']['dms'], data['shop']['2']['shell']) logging.info(device.serial+': opened shop') # click a random item in shop lst = data['shop']['3-0']['shell'] r = choice(lst) device.shell(data['shop']['3-1']['shell']+str(r[0])+' '+str(r[1])) logging.info(device.serial+': clicked a random stuff') self.make_sure_loaded('./base/shop/buy.png', device, data['shop']['3-2']['dms'], data['shop']['3-2']['shell']+str(r[0])+' '+str(r[1]), cutoff=1) logging.info(device.serial+': clicked a random stuff second time') # click buy item self.make_sure_loaded('./base/shop/bought.png', device, data['shop']['4']['dms'], data['shop']['4']['shell'], shell_first=True, cutoff=3) logging.info(device.serial+': bought stuff') # click exit self.make_sure_loaded('./base/shop/my_info.png', device, data['shop']['5']['dms'], data['shop']['5']['shell'], sleep_duration=0.5) device.shell(data['shop']['6']['shell']) logging.info(device.serial+': successfully bought stuffs in shop in inn mission') self.shop_ = True return 'success' def stockage(self, device, position, data): print(device.serial+': farming stuffs in stockage...') logging.info(device.serial+': farming stuffs in stockage') # click mission shortcut shortcut = self.make_sure_loaded('./base/stockage/enter_dungeons.png', device, data['stockage']['1']['dms'], data['stockage']['1']['shell']+position, loop=20, cutoff=20, sleep_duration=10) if shortcut == 'loop': self.stockage_ = True return 'not' logging.info(device.serial+': loaded from mission shortcut') # open stockage self.make_sure_loaded('./base/stockage/stockage.png', device, data['stockage']['2']['dms'], data['stockage']['2']['shell'], cutoff=9, sleep_duration=0.5) logging.info(device.serial+': opened stockage') def check_team(device, data): # slot 1 self.make_sure_loaded('./base/tower/party_4.png', device, data['tower']['7']['dms'], data['tower']['7']['shell'], sleep_duration=1, cutoff=20, oposite=True) # slot 2 self.make_sure_loaded('./base/tower/party_3.png', device, data['tower']['8']['dms'], data['tower']['8']['shell'], sleep_duration=1, cutoff=20, oposite=True) # slot 3 self.make_sure_loaded('./base/tower/party_2.png', device, data['tower']['9']['dms'], data['tower']['9']['shell'], sleep_duration=1, cutoff=20, oposite=True) # slot 4 self.make_sure_loaded('./base/tower/party_1.png', device, data['tower']['10']['dms'], data['tower']['10']['shell'], sleep_duration=1, cutoff=20, oposite=True) # fragment dungeons self.make_sure_loaded('./base/stockage/fragment_d.png', device, data['stockage']['3']['dms'], data['stockage']['3']['shell'], sleep_duration=0.5) logging.info(device.serial+': clicked fragment dungeons') # party self.make_sure_loaded('./base/stockage/party.png', device, data['stockage']['4']['dms'], data['stockage']['4']['shell'], sleep_duration=0.5) logging.info(device.serial+': clicked to party setup') # check avalible team check_team(device, data) # start battle self.make_sure_loaded('./base/stockage/select_battle.png', device, data['stockage']['5']['dms'], data['stockage']['5']['shell'], sleep_duration=0.5) logging.info(device.serial+': clicked start battle') # auto repeat self.make_sure_loaded('./base/stockage/notice.png', device, data['stockage']['6']['dms'], data['stockage']['6']['shell'], sleep_duration=0.5) logging.info(device.serial+': clicked auto repeat') # select reward self.make_sure_loaded('./base/stockage/fragment_select_reward.png', device, data['stockage']['7']['dms'], data['stockage']['7']['shell'], sleep_duration=0.5) logging.info(device.serial+': clicked to select reward') # click random reward lst = data['stockage']['8-0']['shell'] r = choice(lst) # self.make_sure_loaded('./base/stockage/ok.png', device, data['stockage']['8-1']['dms'], data['stockage']['8-1']['shell']+str(r[0])+' '+str(r[1]), shell_first=True, sleep_duration=0.5) # logging.info(device.serial+': selected random reward') # click ok self.make_sure_loaded('./base/stockage/loading_r.png', device, data['stockage']['9']['dms'], data['stockage']['9']['shell'], cutoff=10, loop=15, sleep_duration=0.5, second_shell=data['stockage']['8-1']['shell']+str(r[0])+' '+str(r[1])) logging.info(device.serial+': selected random reward and clicked ok to enter battle') slp(5) # wait until finish self.make_sure_loaded('./base/stockage/end.png', device, data['stockage']['10']['dms'], data['stockage']['10']['shell'], sleep_duration=15) logging.info(device.serial+': battle completed') # click exit self.make_sure_loaded('./base/stockage/loading.png', device, data['stockage']['11']['dms'], data['stockage']['11']['shell']) logging.info(device.serial+': exited from fragment dungeons') # skill book dungeon self.make_sure_loaded('./base/stockage/skill_book_d.png', device, data['stockage']['12']['dms'], data['stockage']['12']['shell'], sleep_duration=0.5) logging.info(device.serial+': clicked skill book dungeons') # party self.make_sure_loaded('./base/stockage/party.png', device, data['stockage']['13']['dms'], data['stockage']['13']['shell'], sleep_duration=0.5) logging.info(device.serial+': clicked to party setup') # check avalible team check_team(device, data) # start battle self.make_sure_loaded('./base/stockage/select_battle.png', device, data['stockage']['14']['dms'], data['stockage']['14']['shell'], sleep_duration=0.5) logging.info(device.serial+': clicked start battle') # auto repeat self.make_sure_loaded('./base/stockage/notice.png', device, data['stockage']['15']['dms'], data['stockage']['15']['shell'], sleep_duration=0.5) logging.info(device.serial+': clicked auto repeat') # select reward self.make_sure_loaded('./base/stockage/exp_select_reward.png', device, data['stockage']['16']['dms'], data['stockage']['16']['shell'], sleep_duration=0.5) logging.info(device.serial+': clicked to select reward') # click random type of book lst = data['stockage']['17-0']['shell'] r = choice(lst) device.shell(data['stockage']['17-1']['shell']+str(r[0])+' '+str(r[1])) logging.info(device.serial+': selected random book type') # click random book lst = data['stockage']['18-0']['shell'] r = choice(lst) # self.make_sure_loaded('./base/stockage/ok_.png', device, data['stockage']['18-1']['dms'], data['stockage']['18-1']['shell']+str(r[0])+' '+str(r[1]), shell_first=True, sleep_duration=0.5) # logging.info(device.serial+': selected random book reward') # click ok self.make_sure_loaded('./base/stockage/loading_r.png', device, data['stockage']['19']['dms'], data['stockage']['19']['shell'], cutoff=10, loop=15, sleep_duration=0.5, second_shell=data['stockage']['18-1']['shell']+str(r[0])+' '+str(r[1])) logging.info(device.serial+': selected random book reward and clicked ok to enter battle') slp(5) # wait until finish self.make_sure_loaded('./base/stockage/end.png', device, data['stockage']['20']['dms'], data['stockage']['20']['shell'], sleep_duration=15) logging.info(device.serial+': battle completed') # click exit self.make_sure_loaded('./base/stockage/loading.png', device, data['stockage']['21']['dms'], data['stockage']['21']['shell']) logging.info(device.serial+': exited from skill book dungeons') # exp dungeon self.make_sure_loaded('./base/stockage/exp_d.png', device, data['stockage']['22']['dms'], data['stockage']['22']['shell'], sleep_duration=0.5) logging.info(device.serial+': clicked exp dungeons') # party self.make_sure_loaded('./base/stockage/party.png', device, data['stockage']['23']['dms'], data['stockage']['23']['shell'], sleep_duration=0.5) logging.info(device.serial+': clicked to party setup') # check avalible team check_team(device, data) # start battle self.make_sure_loaded('./base/stockage/select_battle.png', device, data['stockage']['24']['dms'], data['stockage']['24']['shell'], sleep_duration=0.5) logging.info(device.serial+': clicked start battle') # auto repeat self.make_sure_loaded('./base/stockage/notice.png', device, data['stockage']['25']['dms'], data['stockage']['25']['shell'], sleep_duration=0.5) logging.info(device.serial+': clicked auto repeat') # click ok self.make_sure_loaded('./base/stockage/loading_r.png', device, data['stockage']['26']['dms'], data['stockage']['26']['shell'], loop=10, sleep_duration=0.5) logging.info(device.serial+': clicked ok to enter battle') slp(5) # wait until finish self.make_sure_loaded('./base/stockage/end.png', device, data['stockage']['27']['dms'], data['stockage']['27']['shell'], sleep_duration=15) logging.info(device.serial+': battle completed') # click exit self.make_sure_loaded('./base/stockage/loading.png', device, data['stockage']['28']['dms'], data['stockage']['28']['shell']) logging.info(device.serial+': exited from exp dungeons') # gold dungeon self.make_sure_loaded('./base/stockage/gold_d.png', device, data['stockage']['29']['dms'], data['stockage']['29']['shell'], sleep_duration=0.5) logging.info(device.serial+': clicked exp dungeons') # party self.make_sure_loaded('./base/stockage/party.png', device, data['stockage']['30']['dms'], data['stockage']['30']['shell'], sleep_duration=0.5) logging.info(device.serial+': clicked to party setup') # check avalible team check_team(device, data) # start battle self.make_sure_loaded('./base/stockage/select_battle.png', device, data['stockage']['31']['dms'], data['stockage']['31']['shell'], sleep_duration=0.5) logging.info(device.serial+': clicked start battle') # auto repeat self.make_sure_loaded('./base/stockage/notice.png', device, data['stockage']['32']['dms'], data['stockage']['32']['shell'], sleep_duration=0.5) logging.info(device.serial+': clicked auto repeat') # click ok self.make_sure_loaded('./base/stockage/loading_r.png', device, data['stockage']['33']['dms'], data['stockage']['33']['shell'], loop=10, sleep_duration=0.5) logging.info(device.serial+': clicked ok to enter battle') slp(5) # wait until finish self.make_sure_loaded('./base/stockage/end.png', device, data['stockage']['34']['dms'], data['stockage']['34']['shell'], sleep_duration=15) logging.info(device.serial+': battle completed') # click exit self.make_sure_loaded('./base/stockage/loading.png', device, data['stockage']['35']['dms'], data['stockage']['35']['shell']) logging.info(device.serial+': exited from gold dungeons') # click exit self.make_sure_loaded('./base/stockage/my_info.png', device, data['stockage']['36']['dms'], data['stockage']['36']['shell'], sleep_duration=0.5) device.shell(data['stockage']['37']['shell']) logging.info(device.serial+': successfully did stockage mission') self.stockage_ = True return 'success' def tower(self, device, position, data, lang): print(device.serial+': battling in tower...') logging.info(device.serial+': battling in tower') # click mission shortcut shortcut = self.make_sure_loaded('./base/tower/tower.png', device, data['tower']['1']['dms'], data['tower']['1']['shell']+position, loop=20, cutoff=20, sleep_duration=10) if shortcut == 'loop': self.tower_ = True return 'not' logging.info(device.serial+': loaded from mission shortcut') # click tower of challenge self.make_sure_loaded('./base/tower/toc.png', device, data['tower']['2']['dms'], data['tower']['2']['shell'], sleep_duration=1) logging.info(device.serial+': clicked toc') # change to floor 1 with open('./languages.json', encoding='utf-8') as j: floor = json.load(j)[lang]['tower'] while True: im, device = self.update_cache(device) pil_image = crop(im, data['tower']['3']['dms']) img = filter(pil_image) text = image_to_string(img, lang).replace('♀', '') if lang == 'jpn': text = text.replace(' ', '') text = text.splitlines()[0].lower().replace(' ','') if SequenceMatcher(None, text, floor).ratio() > 0.9: device.shell(data['tower']['5']['shell']) break else: device.shell(data['tower']['4']['shell']) slp(1) logging.info(device.serial+': changed floor level to 1') # click ready for battle self.make_sure_loaded('./base/tower/party.png', device, data['tower']['6']['dms'], data['tower']['6']['shell']) logging.info(device.serial+': clicked ready for battle') # check avalible team # slot 1 self.make_sure_loaded('./base/tower/party_4.png', device, data['tower']['7']['dms'], data['tower']['7']['shell'], sleep_duration=1, cutoff=20, oposite=True) # slot 2 self.make_sure_loaded('./base/tower/party_3.png', device, data['tower']['8']['dms'], data['tower']['8']['shell'], sleep_duration=1, cutoff=20, oposite=True) # slot 3 self.make_sure_loaded('./base/tower/party_2.png', device, data['tower']['9']['dms'], data['tower']['9']['shell'], sleep_duration=1, cutoff=20, oposite=True) # slot 4 self.make_sure_loaded('./base/tower/party_1.png', device, data['tower']['10']['dms'], data['tower']['10']['shell'], sleep_duration=1, cutoff=20, oposite=True) logging.info(device.serial+': checked all avalible slots') # click start battle to open select battle board self.make_sure_loaded('./base/tower/select_battle.png', device, data['tower']['11']['dms'], data['tower']['11']['shell'], sleep_duration=0.5) logging.info(device.serial+': clicked start battle and opened select battle board') # click start battle self.make_sure_loaded('./base/tower/end.png', device, data['tower']['12']['dms'], data['tower']['12']['shell'], sleep_duration=0.5, cutoff=10) logging.info(device.serial+': clicked start battle') # click exit battle self.make_sure_loaded('./base/tower/toc.png', device, data['tower']['2']['dms'], data['tower']['13']['shell']) logging.info(device.serial+': exited battle') # click exit self.make_sure_loaded('./base/tower/my_info.png', device, data['tower']['14']['dms'], data['tower']['14']['shell'], sleep_duration=0.5) device.shell(data['tower']['15']['shell']) logging.info(device.serial+': successfully did toc mission') self.tower_ = True return 'success' def wb(self, device, position, data): print(device.serial+': battling world boss...') logging.info(device.serial+': battling world boss') # click mission shortcut shortcut = self.make_sure_loaded('./base/wb/wb.png', device, data['wb']['1']['dms'], data['wb']['1']['shell']+position, loop=20, cutoff=20, sleep_duration=10) if shortcut == 'loop': self.wb_ = True return 'not' logging.info(device.serial+': loaded from mission shortcut') # click get ready for battle close = self.make_sure_loaded('./base/wb/party.png', device, data['wb']['2']['dms'], data['wb']['2']['shell'], sleep_duration=2, cutoff=20, loop=20) # wb close if close == 'loop': self.wb_ = True # click exit self.make_sure_loaded('./base/wb/my_info.png', device, data['wb']['8']['dms'], data['wb']['8']['shell'], sleep_duration=0.5) device.shell(data['wb']['9']['shell']) return 'success' logging.info(device.serial+': loaded from get ready for battle') # check avalible team self.make_sure_loaded('./base/wb/a_party.png', device, data['wb']['3']['dms'], data['wb']['3']['shell'], cutoff=20, oposite=True, sleep_duration=0.5) logging.info(device.serial+': checked avalible party') # click set sub team self.make_sure_loaded('./base/wb/sub_party.png', device, data['wb']['4']['dms'], data['wb']['4']['shell'], sleep_duration=0.5, cutoff=2) logging.info(device.serial+': clicked set up sub team') # click start battle self.make_sure_loaded('./base/wb/loading.png', device, data['wb']['5']['dms'], data['wb']['5']['shell'], cutoff=10, \ sleep_duration=0.5, second_shell=data['wb']['5']['second_shell'], loop=10) logging.info(device.serial+': clicked start battle') # wait until finish self.make_sure_loaded('./base/wb/end.png', device, data['wb']['6']['dms'], sleep_duration=15, cutoff=20) logging.info(device.serial+': battle completed') # click exit battle self.make_sure_loaded('./base/wb/wb.png', device, data['wb']['7']['dms'], data['wb']['7']['shell']) logging.info(device.serial+': exited battle') # click exit self.make_sure_loaded('./base/wb/my_info.png', device, data['wb']['8']['dms'], data['wb']['8']['shell'], sleep_duration=0.5) device.shell(data['wb']['9']['shell']) logging.info(device.serial+': successfully did world boss mission') self.wb_ = True return 'success' def lil(self, device, position, data, res): print(device.serial+': feeding lil raider...') logging.info(device.serial+': feeding lil raider') # click mission shortcut shortcut = self.make_sure_loaded('./base/lil/lil.png', device, data['lil']['1']['dms'], data['lil']['1']['shell']+position, cutoff=20, loop=20, sleep_duration=10) if shortcut == 'loop': self.lil_ = True return 'not' logging.info(device.serial+': loaded from mission shortcut') # click treats self.make_sure_loaded('./base/lil/treats.png', device, data['lil']['2']['dms'], data['lil']['2']['shell'], cutoff=10, sleep_duration=0.5) logging.info(device.serial+': clicked treats') # click feed first lil raider self.make_sure_loaded('./base/lil/feeded.png', device, data['lil']['3']['dms'], data['lil']['3']['shell'], second_shell=data['lil']['4']['shell'], shell_first=True, cutoff=20, sleep_duration=0.5) logging.info(device.serial+': clicked feed') # click exit feeding self.make_sure_loaded('./base/lil/lil.png', device, data['lil']['5']['dms'], data['lil']['5']['shell'], cutoff=10, sleep_duration=0.5) logging.info(device.serial+': exit treats') # click exit self.make_sure_loaded('./base/lil/my_info.png', device, data['lil']['6']['dms'], data['lil']['6']['shell'], sleep_duration=0.5) device.shell(data['lil']['7']['shell']) logging.info(device.serial+': successfully did lil raider mission') self.lil_ = True return 'success' def weekly(self, device, data): logging.info(device.serial+': claiming weekly rewards') def claim(): # claim rewards count = 0 while True: if count == 9: break device.shell(data['claim'][0]) device.shell(data['claim'][1]) count+=1 # change to weekly mission board self.make_sure_loaded('./base/other/daily.png', device, data['daily']['dms'], data['daily']['third_shell'], shell_first=True, sleep_duration=0.5, cutoff=8, loop=20) claim() def mails(self, device, data): print(device.serial+': mails is enabled, claiming all mails...') logging.info(device.serial+': claiming mails') # exit from mission board self.make_sure_loaded('./base/mails/my_info.png', device, data['mails']['1']['dms'], data['mails']['1']['shell'], sleep_duration=0.5) device.shell(data['mails']['2']['shell']) logging.info(device.serial+': exit to main screen (1)') # click mailbox self.make_sure_loaded('./base/mails/mailbox.png', device, data['mails']['3']['dms'], data['mails']['3']['shell'], sleep_duration=0.5) logging.info(device.serial+': clicked mailbox') # click claim all self.make_sure_loaded('./base/mails/claim_all.png', device, data['mails']['4']['dms'], data['mails']['4']['shell'], sleep_duration=0.5) logging.info(device.serial+': clicked claim all') # exit to main screen self.make_sure_loaded('./base/mails/my_info.png', device, data['mails']['1']['dms'], data['mails']['1']['shell'], sleep_duration=0.5) device.shell(data['mails']['2']['shell']) logging.info(device.serial+': exit to main screen (2)') def loh(self, device, data, lang): print(device.serial+': loh is enabled, suiciding in loh...') logging.info(device.serial+': suiciding in loh') # exit from mission board self.make_sure_loaded('./base/loh/my_info.png', device, data['loh']['1']['dms'], data['loh']['1']['shell'], sleep_duration=0.5) device.shell(data['loh']['2']['shell']) logging.info(device.serial+': exit to main screen') # click portal self.make_sure_loaded('./base/loh/portal.png', device, data['loh']['3']['dms'], data['loh']['3']['shell'], sleep_duration=1, ck_special_shop=False) logging.info(device.serial+': clicked portal') # click arena in portal self.make_sure_loaded('./base/loh/arena.png', device, data['loh']['4']['dms'], data['loh']['4']['shell'], cutoff=15, sleep_duration=0.5, ck_special_shop=False) logging.info(device.serial+': clicked arenas') # click loh in arena self.make_sure_loaded('./base/loh/notice.png', device, data['loh']['5']['dms'], data['loh']['5']['shell'], cutoff=20, sleep_duration=0.5, ck_special_shop=False) logging.info(device.serial+': clicked loh') # click ok in notice self.make_sure_loaded('./base/loh/loh.png', device, data['loh']['6']['dms'], data['loh']['6']['shell'], second_img='./base/loh/previous_result.png', third_img='./base/loh/rewards.png', sleep_duration=10, loop=10, ck_special_shop=False) logging.info(device.serial+': clicked ok in notice') # check def check_keys(device): while True: try: device.shell(data['loh']['7']['second_shell']) slp(3) device.shell(data['loh']['7']['shell']) slp(5) im, device = self.update_cache(device) im = crop(im, data['loh']['7']['dms']) text = image_to_string(im, lang).lower().replace('♀', '') detect(text) if lang == 'jpn': text = text.replace(' ', '') with open('./languages.json', encoding='utf-8') as j: re = json.load(j) if SequenceMatcher(None, re[lang]['loh'], text).ratio() > 0.9: return 'not enough currency' return 'continue' except: continue re = check_keys(device) if re == 'not enough currency': return 'not enough currency' # push script and continuosly execute device.shell('rm /sdcard/loh_script.sh') slp(5) device.push(data['loh']['scripts']['sh'], '/sdcard/loh_script.sh') start_time = tiime() seconds = 4000 count = 0 slp(5) device.shell(data['loh']['scripts']['confirm']) while True: current_time = tiime() elapsed_time = current_time - start_time if elapsed_time > seconds: break if count == 50: re = check_keys(device) if re == 'not enough currency': return 'not enough currency' count = 0 device.shell(data['loh']['scripts']['get_ready']) device.shell(data['loh']['scripts']['confirm']) device.shell('sh /sdcard/loh_script.sh') count+=1 logging.info(device.serial+': successfully suiciding in loh') return 'success' def extra_dailies(self, device): pass def load_devices(): working_dir = getcwd() adb_dir = '"'+working_dir+'\\adb" ' run_(adb_dir+'kill-server') adb = Client(host="127.0.0.1", port=5037) try: devices = adb.devices() except: run_(adb_dir+'devices') slp(5) run_(adb_dir+'devices') devices = adb.devices() return devices, adb_dir, adb def run(): with open('./config.json') as j: re = json.load(j) path = re['ldconsole'].replace('|', '"') quit_all = False if re['quit_all'] == True: quit_all = True try: run_(path+' quitall') except FileNotFoundError: text = "path to LDPlayer is wrong, please config and try again" logging.info(text) print(text) input('press any key to exit...') return latest = get("https://api.github.com/repos/faber6/kings-raid-daily/releases/latest") with open('./sets.json') as t: this = json.load(t) if latest.json()["tag_name"] != this['version']: text = (f'\nThere is a new version ({latest.json()["tag_name"]}) of script on https://github.com/faber6/kings-raid-daily/releases'+ '\nIf this version not working as expected, please update to a newer version\n') logging.info(text) print(text) def msg_box(this): answ = ctypes.windll.user32.MessageBoxW(0, text[1:].replace('\n','\n\n')+'do you want to remind this later?', f"kings-raid-daily new version ({latest.json()['tag_name']})", 4) if answ == 6: # yes this['remind'] = True elif answ == 7: # no this['remind'] = False with open('./sets.json', 'w') as w: json.dump(this, w, indent=4) return msg_box_thread = Thread(target=msg_box, name='msg_box', args=(this,)) if this['remind'] == True: msg_box_thread.start() else: if latest.json()["tag_name"] != this['latest']: this['latest'] = latest.json()["tag_name"] with open('./sets.json', 'w') as w: json.dump(this, w, indent=4) msg_box_thread.start() devices, adb_dir, adb = load_devices() count = 0 while True: if count == 49: text = 'no device was found after 50 retries, script ended' logging.info(text) print(text) break if devices == []: if re['devices'] != []: if count == 4 or quit_all == True: if quit_all == True: text = 'quit all emulators, launching from config...' logging.info(text) print(text) else: text = 'no device was found after 5 retries, launching from config and retrying...' logging.info(text) print(text) break_ = False devices_dexist = 0 if re['max_devices'] == 1: for device_ in re['devices']: try: re_ = run_(path+' launch --index '+str(device_), capture_output=True).stdout if str(re_)+'/' == """b"player don't exist!"/""": devices_dexist += 1 text = 'device with index '+str(device_)+" doesn't exist" logging.info(text) print(text) else: text = 'launched device with index '+str(device_) logging.info(text) print(text) print('waiting 30 secs for fully boot up') slp(30) while True: devices, adb_dir, adb = load_devices() if devices != []: if len(devices) == 1: for device in devices: if str(device.serial).startswith('127'): continue thread = Thread(target=Missions().run_execute, args=(device, device_,)) text = 'executing on device '+device.serial logging.info(text) print(text) thread.start() start_time = tiime() seconds = 10800 while True: current_time = tiime() elapsed_time = current_time - start_time if elapsed_time > seconds: break if thread.is_alive() == False: break else: text = "'max_devices' set to 1 but 'adb devices' returns "+str(len(devices))+' devices, retrying...' logging.info(text) print(text) continue break slp(5) break_ = True except FileNotFoundError: break_ = True text = "path to LDPlayer is wrong, please config and try again" logging.info(text) print(text) input('press any key to exit...') break if devices_dexist == len(re['devices']): text = "all configured devices don't exit" logging.info(text) print(text) input('press any key to exit...') break_ = True break else: running = 0 _devices_ = {} for device_ in re['devices']: _devices_[device_] = False if len(_devices_) % 2 == 0: last_run = 0 else: run_times = ceil(len(_devices_) / 2) last_run = len(_devices_) - run_times threads = [] launched = [] launched_ = [] done = [] devices_ = [] _break_ = False i = 0 while True: if len(done) == len(re['devices']): break_ = True _break_ = True break if running != 0: if running == re['max_devices'] or running == last_run: slp(10) for thread_ in threads: if int(thread_.name) not in done: start_time = tiime() seconds = 10800 while True: current_time = tiime() elapsed_time = current_time - start_time if elapsed_time > seconds: break if thread_.is_alive() == False: break done.append(int(thread_.name)) # for thread_ in threads: # if int(thread_.name) not in done: # thread_.join(9000) # done.append(int(thread_.name)) running = running - len(done) else: for device_ in _devices_: if running == re['max_devices']: break elif _devices_[device_] == False: try: path = re['ldconsole'].replace('|', '"') re_ = run_(path+' launch --index '+str(device_), capture_output=True).stdout if str(re_)+'/' == """b"player don't exist!"/""": devices_dexist += 1 text = 'device with index '+str(device_)+" doesn't exist" logging.info(text) print(text) else: text = 'launched device with index '+str(device_) logging.info(text) print(text) launched.append(int(device_)) running += 1 _devices_[device_] = True except FileNotFoundError: break_ = True _break_ = True text = "path to LDPlayer is wrong, please config and try again" logging.info(text) print(text) input('press any key to exit...') break if devices_dexist == len(re['devices']): text = "all configured device(s) don't exit" logging.info(text) print(text) input('press any key to exit...') break_ = True _break_ = True break print('waiting 30 secs for fully boot up') slp(30) while True: devices, adb_dir, adb = load_devices() if devices != []: if len(devices) == running: pass else: text = "'max_devices' set to "+str(re['max_devices'])+" but 'adb devices' returns "+str(len(devices))+' devices, retrying...' logging.info(text) print(text) continue for device in devices: if str(device.serial).startswith('127'): continue if device not in devices_: devices_.append(device) while True: try: device = devices_[i] device_ = launched[i] except: break if str(device.serial).startswith('127'): continue if int(device_) not in launched_: thread = Thread(target=Missions().run_execute, name=str(device_), args=(device,device_,)) threads.append(thread) launched_.append(int(device_)) text = 'executing on device '+device.serial logging.info(text) print(text) thread.start() i+=1 break slp(5) if _break_ == True: break if break_ == True: break print('no device was found, retrying...') run_(adb_dir+'devices') devices = adb.devices() elif str(devices[0].serial).startswith('127'): print('no device was found, retrying...') devices, adb_dir, adb = load_devices() else: slp(10) run_(adb_dir+'devices') devices = adb.devices() print('device(s) detected') for device in devices: thread = Thread(target=Missions().run_execute, args=(device,)) text = 'executing on device '+device.serial logging.info(text) print(text) thread.start() break slp(5) count+=1
[ "time.sleep", "langdetect.detect", "fuzzywuzzy.process.extractOne", "sys.exit", "logging.info", "os.path.exists", "logging.warn", "subprocess.run", "logging.FileHandler", "os.mkdir", "ppadb.client.Client", "random.choice", "requests.get", "time.time", "traceback.format_exc", "PIL.Image...
[((1112, 1156), 'PIL.Image.open', 'Image.open', (['"""./base/login/update_notice.png"""'], {}), "('./base/login/update_notice.png')\n", (1122, 1156), False, 'from PIL import Image, UnidentifiedImageError, ImageFile\n'), ((1173, 1216), 'PIL.Image.open', 'Image.open', (['"""./base/login/introduction.png"""'], {}), "('./base/login/introduction.png')\n", (1183, 1216), False, 'from PIL import Image, UnidentifiedImageError, ImageFile\n'), ((1232, 1274), 'PIL.Image.open', 'Image.open', (['"""./base/login/tap_to_play.png"""'], {}), "('./base/login/tap_to_play.png')\n", (1242, 1274), False, 'from PIL import Image, UnidentifiedImageError, ImageFile\n'), ((1292, 1336), 'PIL.Image.open', 'Image.open', (['"""./base/login/tap_to_play_2.png"""'], {}), "('./base/login/tap_to_play_2.png')\n", (1302, 1336), False, 'from PIL import Image, UnidentifiedImageError, ImageFile\n'), ((1350, 1390), 'PIL.Image.open', 'Image.open', (['"""./base/login/community.png"""'], {}), "('./base/login/community.png')\n", (1360, 1390), False, 'from PIL import Image, UnidentifiedImageError, ImageFile\n'), ((1399, 1434), 'PIL.Image.open', 'Image.open', (['"""./base/login/sale.png"""'], {}), "('./base/login/sale.png')\n", (1409, 1434), False, 'from PIL import Image, UnidentifiedImageError, ImageFile\n'), ((1449, 1490), 'PIL.Image.open', 'Image.open', (['"""./base/login/attendance.png"""'], {}), "('./base/login/attendance.png')\n", (1459, 1490), False, 'from PIL import Image, UnidentifiedImageError, ImageFile\n'), ((1500, 1536), 'PIL.Image.open', 'Image.open', (['"""./base/login/event.png"""'], {}), "('./base/login/event.png')\n", (1510, 1536), False, 'from PIL import Image, UnidentifiedImageError, ImageFile\n'), ((1557, 1604), 'PIL.Image.open', 'Image.open', (['"""./base/login/guild_attendance.png"""'], {}), "('./base/login/guild_attendance.png')\n", (1567, 1604), False, 'from PIL import Image, UnidentifiedImageError, ImageFile\n'), ((1621, 1664), 'PIL.Image.open', 'Image.open', (['"""./base/login/accumualated.png"""'], {}), "('./base/login/accumualated.png')\n", (1631, 1664), False, 'from PIL import Image, UnidentifiedImageError, ImageFile\n'), ((1675, 1712), 'PIL.Image.open', 'Image.open', (['"""./base/login/sale_2.png"""'], {}), "('./base/login/sale_2.png')\n", (1685, 1712), False, 'from PIL import Image, UnidentifiedImageError, ImageFile\n'), ((1729, 1772), 'PIL.Image.open', 'Image.open', (['"""./base/login/special_shop.png"""'], {}), "('./base/login/special_shop.png')\n", (1739, 1772), False, 'from PIL import Image, UnidentifiedImageError, ImageFile\n'), ((1788, 1830), 'PIL.Image.open', 'Image.open', (['"""./base/login/home_screen.png"""'], {}), "('./base/login/home_screen.png')\n", (1798, 1830), False, 'from PIL import Image, UnidentifiedImageError, ImageFile\n'), ((1837, 1882), 'PIL.Image.open', 'Image.open', (['"""./base/login/mission_button.png"""'], {}), "('./base/login/mission_button.png')\n", (1847, 1882), False, 'from PIL import Image, UnidentifiedImageError, ImageFile\n'), ((1894, 1930), 'PIL.Image.open', 'Image.open', (['"""./base/loh/loh_new.png"""'], {}), "('./base/loh/loh_new.png')\n", (1904, 1930), False, 'from PIL import Image, UnidentifiedImageError, ImageFile\n'), ((1945, 1986), 'PIL.Image.open', 'Image.open', (['"""./base/login/kr_discord.png"""'], {}), "('./base/login/kr_discord.png')\n", (1955, 1986), False, 'from PIL import Image, UnidentifiedImageError, ImageFile\n'), ((721, 743), 'os.path.exists', 'pth.exists', (['"""./.cache"""'], {}), "('./.cache')\n", (731, 743), True, 'from os import mkdir, getcwd, path as pth\n'), ((758, 775), 'os.mkdir', 'mkdir', (['"""./.cache"""'], {}), "('./.cache')\n", (763, 775), False, 'from os import mkdir, getcwd, path as pth\n'), ((2322, 2340), 'imagehash.average_hash', 'average_hash', (['img1'], {}), '(img1)\n', (2334, 2340), False, 'from imagehash import average_hash\n'), ((2354, 2372), 'imagehash.average_hash', 'average_hash', (['img2'], {}), '(img2)\n', (2366, 2372), False, 'from imagehash import average_hash\n'), ((2632, 2673), 'cv2.bilateralFilter', 'bilateralFilter', (['open_cv_image', '(9)', '(75)', '(75)'], {}), '(open_cv_image, 9, 75, 75)\n', (2647, 2673), False, 'from cv2 import bilateralFilter\n'), ((62739, 62747), 'os.getcwd', 'getcwd', ([], {}), '()\n', (62745, 62747), False, 'from os import mkdir, getcwd, path as pth\n'), ((62792, 62821), 'subprocess.run', 'run_', (["(adb_dir + 'kill-server')"], {}), "(adb_dir + 'kill-server')\n", (62796, 62821), True, 'from subprocess import run as run_\n'), ((62830, 62865), 'ppadb.client.Client', 'Client', ([], {'host': '"""127.0.0.1"""', 'port': '(5037)'}), "(host='127.0.0.1', port=5037)\n", (62836, 62865), False, 'from ppadb.client import Client\n'), ((63552, 63627), 'requests.get', 'get', (['"""https://api.github.com/repos/faber6/kings-raid-daily/releases/latest"""'], {}), "('https://api.github.com/repos/faber6/kings-raid-daily/releases/latest')\n", (63555, 63627), False, 'from requests import get\n'), ((15738, 15799), 'logging.info', 'logging.info', (["(device.serial + ': size ' + size_ + ' detected')"], {}), "(device.serial + ': size ' + size_ + ' detected')\n", (15750, 15799), False, 'import logging, json, ctypes\n'), ((17950, 17968), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (17962, 17968), False, 'import logging, json, ctypes\n'), ((22770, 22794), 'fuzzywuzzy.process.extractOne', 'extractOne', (['mission', 'lst'], {}), '(mission, lst)\n', (22780, 22794), False, 'from fuzzywuzzy.process import extractOne\n'), ((25058, 25106), 'logging.info', 'logging.info', (["(device.serial + ': hunting dragon')"], {}), "(device.serial + ': hunting dragon')\n", (25070, 25106), False, 'import logging, json, ctypes\n'), ((25421, 25483), 'logging.info', 'logging.info', (["(device.serial + ': loaded from mission shortcut')"], {}), "(device.serial + ': loaded from mission shortcut')\n", (25433, 25483), False, 'import logging, json, ctypes\n'), ((25655, 25715), 'logging.info', 'logging.info', (["(device.serial + ': clicked create dragon raid')"], {}), "(device.serial + ': clicked create dragon raid')\n", (25667, 25715), False, 'import logging, json, ctypes\n'), ((26484, 26546), 'logging.info', 'logging.info', (["(device.serial + ': changed to dragon t6 stage 1')"], {}), "(device.serial + ': changed to dragon t6 stage 1')\n", (26496, 26546), False, 'import logging, json, ctypes\n'), ((26729, 26782), 'logging.info', 'logging.info', (["(device.serial + ': clicked single raid')"], {}), "(device.serial + ': clicked single raid')\n", (26741, 26782), False, 'import logging, json, ctypes\n'), ((26971, 27023), 'logging.info', 'logging.info', (["(device.serial + ': clicked enter raid')"], {}), "(device.serial + ': clicked enter raid')\n", (26983, 27023), False, 'import logging, json, ctypes\n'), ((28112, 28172), 'logging.info', 'logging.info', (["(device.serial + ': checked all avalible slots')"], {}), "(device.serial + ': checked all avalible slots')\n", (28124, 28172), False, 'import logging, json, ctypes\n'), ((28346, 28400), 'logging.info', 'logging.info', (["(device.serial + ': clicked start battle')"], {}), "(device.serial + ': clicked start battle')\n", (28358, 28400), False, 'import logging, json, ctypes\n'), ((28576, 28626), 'logging.info', 'logging.info', (["(device.serial + ': battle completed')"], {}), "(device.serial + ': battle completed')\n", (28588, 28626), False, 'import logging, json, ctypes\n'), ((28807, 28854), 'logging.info', 'logging.info', (["(device.serial + ': exited battle')"], {}), "(device.serial + ': exited battle')\n", (28819, 28854), False, 'import logging, json, ctypes\n'), ((29082, 29147), 'logging.info', 'logging.info', (["(device.serial + ': successfully did dragon mission')"], {}), "(device.serial + ': successfully did dragon mission')\n", (29094, 29147), False, 'import logging, json, ctypes\n'), ((29324, 29386), 'logging.info', 'logging.info', (["(device.serial + ': exchanging friendship points')"], {}), "(device.serial + ': exchanging friendship points')\n", (29336, 29386), False, 'import logging, json, ctypes\n'), ((29715, 29777), 'logging.info', 'logging.info', (["(device.serial + ': loaded from mission shortcut')"], {}), "(device.serial + ': loaded from mission shortcut')\n", (29727, 29777), False, 'import logging, json, ctypes\n'), ((30004, 30072), 'logging.info', 'logging.info', (["(device.serial + ': clicked exchange friendship points')"], {}), "(device.serial + ': clicked exchange friendship points')\n", (30016, 30072), False, 'import logging, json, ctypes\n'), ((30313, 30382), 'logging.info', 'logging.info', (["(device.serial + ': successfully did friendship mission')"], {}), "(device.serial + ': successfully did friendship mission')\n", (30325, 30382), False, 'import logging, json, ctypes\n'), ((30547, 30600), 'logging.info', 'logging.info', (["(device.serial + ': doing stuffs in inn')"], {}), "(device.serial + ': doing stuffs in inn')\n", (30559, 30600), False, 'import logging, json, ctypes\n'), ((30903, 30965), 'logging.info', 'logging.info', (["(device.serial + ': loaded from mission shortcut')"], {}), "(device.serial + ': loaded from mission shortcut')\n", (30915, 30965), False, 'import logging, json, ctypes\n'), ((31149, 31193), 'logging.info', 'logging.info', (["(device.serial + ': opened inn')"], {}), "(device.serial + ': opened inn')\n", (31161, 31193), False, 'import logging, json, ctypes\n'), ((32552, 32610), 'logging.info', 'logging.info', (["(device.serial + ': gave gifts to first hero')"], {}), "(device.serial + ': gave gifts to first hero')\n", (32564, 32610), False, 'import logging, json, ctypes\n'), ((32748, 32807), 'logging.info', 'logging.info', (["(device.serial + ': gave gifts to second hero')"], {}), "(device.serial + ': gave gifts to second hero')\n", (32760, 32807), False, 'import logging, json, ctypes\n'), ((32944, 33002), 'logging.info', 'logging.info', (["(device.serial + ': gave gifts to third hero')"], {}), "(device.serial + ': gave gifts to third hero')\n", (32956, 33002), False, 'import logging, json, ctypes\n'), ((33140, 33199), 'logging.info', 'logging.info', (["(device.serial + ': gave gifts to fourth hero')"], {}), "(device.serial + ': gave gifts to fourth hero')\n", (33152, 33199), False, 'import logging, json, ctypes\n'), ((33338, 33396), 'logging.info', 'logging.info', (["(device.serial + ': gave gifts to fifth hero')"], {}), "(device.serial + ': gave gifts to fifth hero')\n", (33350, 33396), False, 'import logging, json, ctypes\n'), ((33535, 33593), 'logging.info', 'logging.info', (["(device.serial + ': gave gifts to sixth hero')"], {}), "(device.serial + ': gave gifts to sixth hero')\n", (33547, 33593), False, 'import logging, json, ctypes\n'), ((34138, 34188), 'logging.info', 'logging.info', (["(device.serial + ': played minigames')"], {}), "(device.serial + ': played minigames')\n", (34150, 34188), False, 'import logging, json, ctypes\n'), ((34553, 34630), 'logging.info', 'logging.info', (["(device.serial + ': successfully did some stuffs in inn mission')"], {}), "(device.serial + ': successfully did some stuffs in inn mission')\n", (34565, 34630), False, 'import logging, json, ctypes\n'), ((34785, 34835), 'logging.info', 'logging.info', (["(device.serial + ': suiciding in lov')"], {}), "(device.serial + ': suiciding in lov')\n", (34797, 34835), False, 'import logging, json, ctypes\n'), ((35142, 35204), 'logging.info', 'logging.info', (["(device.serial + ': loaded from mission shortcut')"], {}), "(device.serial + ': loaded from mission shortcut')\n", (35154, 35204), False, 'import logging, json, ctypes\n'), ((35376, 35430), 'logging.info', 'logging.info', (["(device.serial + ': clicked select arena')"], {}), "(device.serial + ': clicked select arena')\n", (35388, 35430), False, 'import logging, json, ctypes\n'), ((35594, 35645), 'logging.info', 'logging.info', (["(device.serial + ': clicked enter lov')"], {}), "(device.serial + ': clicked enter lov')\n", (35606, 35645), False, 'import logging, json, ctypes\n'), ((35828, 35883), 'logging.info', 'logging.info', (["(device.serial + ': clicked ready to dual')"], {}), "(device.serial + ': clicked ready to dual')\n", (35840, 35883), False, 'import logging, json, ctypes\n'), ((36079, 36134), 'logging.info', 'logging.info', (["(device.serial + ': checked avalible team')"], {}), "(device.serial + ': checked avalible team')\n", (36091, 36134), False, 'import logging, json, ctypes\n'), ((36363, 36422), 'logging.info', 'logging.info', (["(device.serial + ': clicked and exited battle')"], {}), "(device.serial + ': clicked and exited battle')\n", (36375, 36422), False, 'import logging, json, ctypes\n'), ((36589, 36635), 'logging.info', 'logging.info', (["(device.serial + ': exited match')"], {}), "(device.serial + ': exited match')\n", (36601, 36635), False, 'import logging, json, ctypes\n'), ((36848, 36910), 'logging.info', 'logging.info', (["(device.serial + ': successfully did lov mission')"], {}), "(device.serial + ': successfully did lov mission')\n", (36860, 36910), False, 'import logging, json, ctypes\n'), ((37071, 37126), 'logging.info', 'logging.info', (["(device.serial + ': buying stuffs in shop')"], {}), "(device.serial + ': buying stuffs in shop')\n", (37083, 37126), False, 'import logging, json, ctypes\n'), ((37432, 37494), 'logging.info', 'logging.info', (["(device.serial + ': loaded from mission shortcut')"], {}), "(device.serial + ': loaded from mission shortcut')\n", (37444, 37494), False, 'import logging, json, ctypes\n'), ((37638, 37683), 'logging.info', 'logging.info', (["(device.serial + ': opened shop')"], {}), "(device.serial + ': opened shop')\n", (37650, 37683), False, 'import logging, json, ctypes\n'), ((37776, 37787), 'random.choice', 'choice', (['lst'], {}), '(lst)\n', (37782, 37787), False, 'from random import choice\n'), ((37871, 37927), 'logging.info', 'logging.info', (["(device.serial + ': clicked a random stuff')"], {}), "(device.serial + ': clicked a random stuff')\n", (37883, 37927), False, 'import logging, json, ctypes\n'), ((38087, 38155), 'logging.info', 'logging.info', (["(device.serial + ': clicked a random stuff second time')"], {}), "(device.serial + ': clicked a random stuff second time')\n", (38099, 38155), False, 'import logging, json, ctypes\n'), ((38334, 38380), 'logging.info', 'logging.info', (["(device.serial + ': bought stuff')"], {}), "(device.serial + ': bought stuff')\n", (38346, 38380), False, 'import logging, json, ctypes\n'), ((38597, 38684), 'logging.info', 'logging.info', (["(device.serial + ': successfully bought stuffs in shop in inn mission')"], {}), "(device.serial +\n ': successfully bought stuffs in shop in inn mission')\n", (38609, 38684), False, 'import logging, json, ctypes\n'), ((38851, 38911), 'logging.info', 'logging.info', (["(device.serial + ': farming stuffs in stockage')"], {}), "(device.serial + ': farming stuffs in stockage')\n", (38863, 38911), False, 'import logging, json, ctypes\n'), ((39239, 39301), 'logging.info', 'logging.info', (["(device.serial + ': loaded from mission shortcut')"], {}), "(device.serial + ': loaded from mission shortcut')\n", (39251, 39301), False, 'import logging, json, ctypes\n'), ((39495, 39544), 'logging.info', 'logging.info', (["(device.serial + ': opened stockage')"], {}), "(device.serial + ': opened stockage')\n", (39507, 39544), False, 'import logging, json, ctypes\n'), ((40535, 40594), 'logging.info', 'logging.info', (["(device.serial + ': clicked fragment dungeons')"], {}), "(device.serial + ': clicked fragment dungeons')\n", (40547, 40594), False, 'import logging, json, ctypes\n'), ((40766, 40822), 'logging.info', 'logging.info', (["(device.serial + ': clicked to party setup')"], {}), "(device.serial + ': clicked to party setup')\n", (40778, 40822), False, 'import logging, json, ctypes\n'), ((41072, 41126), 'logging.info', 'logging.info', (["(device.serial + ': clicked start battle')"], {}), "(device.serial + ': clicked start battle')\n", (41084, 41126), False, 'import logging, json, ctypes\n'), ((41305, 41358), 'logging.info', 'logging.info', (["(device.serial + ': clicked auto repeat')"], {}), "(device.serial + ': clicked auto repeat')\n", (41317, 41358), False, 'import logging, json, ctypes\n'), ((41555, 41613), 'logging.info', 'logging.info', (["(device.serial + ': clicked to select reward')"], {}), "(device.serial + ': clicked to select reward')\n", (41567, 41613), False, 'import logging, json, ctypes\n'), ((41701, 41712), 'random.choice', 'choice', (['lst'], {}), '(lst)\n', (41707, 41712), False, 'from random import choice\n'), ((42243, 42334), 'logging.info', 'logging.info', (["(device.serial + ': selected random reward and clicked ok to enter battle')"], {}), "(device.serial +\n ': selected random reward and clicked ok to enter battle')\n", (42255, 42334), False, 'import logging, json, ctypes\n'), ((42337, 42343), 'time.sleep', 'slp', (['(5)'], {}), '(5)\n', (42340, 42343), True, 'from time import sleep as slp\n'), ((42528, 42578), 'logging.info', 'logging.info', (["(device.serial + ': battle completed')"], {}), "(device.serial + ': battle completed')\n", (42540, 42578), False, 'import logging, json, ctypes\n'), ((42739, 42802), 'logging.info', 'logging.info', (["(device.serial + ': exited from fragment dungeons')"], {}), "(device.serial + ': exited from fragment dungeons')\n", (42751, 42802), False, 'import logging, json, ctypes\n'), ((42998, 43059), 'logging.info', 'logging.info', (["(device.serial + ': clicked skill book dungeons')"], {}), "(device.serial + ': clicked skill book dungeons')\n", (43010, 43059), False, 'import logging, json, ctypes\n'), ((43233, 43289), 'logging.info', 'logging.info', (["(device.serial + ': clicked to party setup')"], {}), "(device.serial + ': clicked to party setup')\n", (43245, 43289), False, 'import logging, json, ctypes\n'), ((43541, 43595), 'logging.info', 'logging.info', (["(device.serial + ': clicked start battle')"], {}), "(device.serial + ': clicked start battle')\n", (43553, 43595), False, 'import logging, json, ctypes\n'), ((43776, 43829), 'logging.info', 'logging.info', (["(device.serial + ': clicked auto repeat')"], {}), "(device.serial + ': clicked auto repeat')\n", (43788, 43829), False, 'import logging, json, ctypes\n'), ((44023, 44081), 'logging.info', 'logging.info', (["(device.serial + ': clicked to select reward')"], {}), "(device.serial + ': clicked to select reward')\n", (44035, 44081), False, 'import logging, json, ctypes\n'), ((44176, 44187), 'random.choice', 'choice', (['lst'], {}), '(lst)\n', (44182, 44187), False, 'from random import choice\n'), ((44276, 44335), 'logging.info', 'logging.info', (["(device.serial + ': selected random book type')"], {}), "(device.serial + ': selected random book type')\n", (44288, 44335), False, 'import logging, json, ctypes\n'), ((44422, 44433), 'random.choice', 'choice', (['lst'], {}), '(lst)\n', (44428, 44433), False, 'from random import choice\n'), ((44975, 45071), 'logging.info', 'logging.info', (["(device.serial + ': selected random book reward and clicked ok to enter battle'\n )"], {}), "(device.serial +\n ': selected random book reward and clicked ok to enter battle')\n", (44987, 45071), False, 'import logging, json, ctypes\n'), ((45074, 45080), 'time.sleep', 'slp', (['(5)'], {}), '(5)\n', (45077, 45080), True, 'from time import sleep as slp\n'), ((45265, 45315), 'logging.info', 'logging.info', (["(device.serial + ': battle completed')"], {}), "(device.serial + ': battle completed')\n", (45277, 45315), False, 'import logging, json, ctypes\n'), ((45476, 45541), 'logging.info', 'logging.info', (["(device.serial + ': exited from skill book dungeons')"], {}), "(device.serial + ': exited from skill book dungeons')\n", (45488, 45541), False, 'import logging, json, ctypes\n'), ((45723, 45777), 'logging.info', 'logging.info', (["(device.serial + ': clicked exp dungeons')"], {}), "(device.serial + ': clicked exp dungeons')\n", (45735, 45777), False, 'import logging, json, ctypes\n'), ((45951, 46007), 'logging.info', 'logging.info', (["(device.serial + ': clicked to party setup')"], {}), "(device.serial + ': clicked to party setup')\n", (45963, 46007), False, 'import logging, json, ctypes\n'), ((46259, 46313), 'logging.info', 'logging.info', (["(device.serial + ': clicked start battle')"], {}), "(device.serial + ': clicked start battle')\n", (46271, 46313), False, 'import logging, json, ctypes\n'), ((46494, 46547), 'logging.info', 'logging.info', (["(device.serial + ': clicked auto repeat')"], {}), "(device.serial + ': clicked auto repeat')\n", (46506, 46547), False, 'import logging, json, ctypes\n'), ((46737, 46797), 'logging.info', 'logging.info', (["(device.serial + ': clicked ok to enter battle')"], {}), "(device.serial + ': clicked ok to enter battle')\n", (46749, 46797), False, 'import logging, json, ctypes\n'), ((46804, 46810), 'time.sleep', 'slp', (['(5)'], {}), '(5)\n', (46807, 46810), True, 'from time import sleep as slp\n'), ((46995, 47045), 'logging.info', 'logging.info', (["(device.serial + ': battle completed')"], {}), "(device.serial + ': battle completed')\n", (47007, 47045), False, 'import logging, json, ctypes\n'), ((47206, 47264), 'logging.info', 'logging.info', (["(device.serial + ': exited from exp dungeons')"], {}), "(device.serial + ': exited from exp dungeons')\n", (47218, 47264), False, 'import logging, json, ctypes\n'), ((47448, 47502), 'logging.info', 'logging.info', (["(device.serial + ': clicked exp dungeons')"], {}), "(device.serial + ': clicked exp dungeons')\n", (47460, 47502), False, 'import logging, json, ctypes\n'), ((47676, 47732), 'logging.info', 'logging.info', (["(device.serial + ': clicked to party setup')"], {}), "(device.serial + ': clicked to party setup')\n", (47688, 47732), False, 'import logging, json, ctypes\n'), ((47984, 48038), 'logging.info', 'logging.info', (["(device.serial + ': clicked start battle')"], {}), "(device.serial + ': clicked start battle')\n", (47996, 48038), False, 'import logging, json, ctypes\n'), ((48219, 48272), 'logging.info', 'logging.info', (["(device.serial + ': clicked auto repeat')"], {}), "(device.serial + ': clicked auto repeat')\n", (48231, 48272), False, 'import logging, json, ctypes\n'), ((48462, 48522), 'logging.info', 'logging.info', (["(device.serial + ': clicked ok to enter battle')"], {}), "(device.serial + ': clicked ok to enter battle')\n", (48474, 48522), False, 'import logging, json, ctypes\n'), ((48529, 48535), 'time.sleep', 'slp', (['(5)'], {}), '(5)\n', (48532, 48535), True, 'from time import sleep as slp\n'), ((48720, 48770), 'logging.info', 'logging.info', (["(device.serial + ': battle completed')"], {}), "(device.serial + ': battle completed')\n", (48732, 48770), False, 'import logging, json, ctypes\n'), ((48931, 48990), 'logging.info', 'logging.info', (["(device.serial + ': exited from gold dungeons')"], {}), "(device.serial + ': exited from gold dungeons')\n", (48943, 48990), False, 'import logging, json, ctypes\n'), ((49227, 49294), 'logging.info', 'logging.info', (["(device.serial + ': successfully did stockage mission')"], {}), "(device.serial + ': successfully did stockage mission')\n", (49239, 49294), False, 'import logging, json, ctypes\n'), ((49463, 49514), 'logging.info', 'logging.info', (["(device.serial + ': battling in tower')"], {}), "(device.serial + ': battling in tower')\n", (49475, 49514), False, 'import logging, json, ctypes\n'), ((49821, 49883), 'logging.info', 'logging.info', (["(device.serial + ': loaded from mission shortcut')"], {}), "(device.serial + ': loaded from mission shortcut')\n", (49833, 49883), False, 'import logging, json, ctypes\n'), ((50062, 50107), 'logging.info', 'logging.info', (["(device.serial + ': clicked toc')"], {}), "(device.serial + ': clicked toc')\n", (50074, 50107), False, 'import logging, json, ctypes\n'), ((50862, 50920), 'logging.info', 'logging.info', (["(device.serial + ': changed floor level to 1')"], {}), "(device.serial + ': changed floor level to 1')\n", (50874, 50920), False, 'import logging, json, ctypes\n'), ((51081, 51139), 'logging.info', 'logging.info', (["(device.serial + ': clicked ready for battle')"], {}), "(device.serial + ': clicked ready for battle')\n", (51093, 51139), False, 'import logging, json, ctypes\n'), ((51907, 51967), 'logging.info', 'logging.info', (["(device.serial + ': checked all avalible slots')"], {}), "(device.serial + ': checked all avalible slots')\n", (51919, 51967), False, 'import logging, json, ctypes\n'), ((52182, 52271), 'logging.info', 'logging.info', (["(device.serial + ': clicked start battle and opened select battle board')"], {}), "(device.serial +\n ': clicked start battle and opened select battle board')\n", (52194, 52271), False, 'import logging, json, ctypes\n'), ((52455, 52509), 'logging.info', 'logging.info', (["(device.serial + ': clicked start battle')"], {}), "(device.serial + ': clicked start battle')\n", (52467, 52509), False, 'import logging, json, ctypes\n'), ((52664, 52711), 'logging.info', 'logging.info', (["(device.serial + ': exited battle')"], {}), "(device.serial + ': exited battle')\n", (52676, 52711), False, 'import logging, json, ctypes\n'), ((52935, 52997), 'logging.info', 'logging.info', (["(device.serial + ': successfully did toc mission')"], {}), "(device.serial + ': successfully did toc mission')\n", (52947, 52997), False, 'import logging, json, ctypes\n'), ((53156, 53209), 'logging.info', 'logging.info', (["(device.serial + ': battling world boss')"], {}), "(device.serial + ': battling world boss')\n", (53168, 53209), False, 'import logging, json, ctypes\n'), ((53501, 53563), 'logging.info', 'logging.info', (["(device.serial + ': loaded from mission shortcut')"], {}), "(device.serial + ': loaded from mission shortcut')\n", (53513, 53563), False, 'import logging, json, ctypes\n'), ((54082, 54148), 'logging.info', 'logging.info', (["(device.serial + ': loaded from get ready for battle')"], {}), "(device.serial + ': loaded from get ready for battle')\n", (54094, 54148), False, 'import logging, json, ctypes\n'), ((54344, 54400), 'logging.info', 'logging.info', (["(device.serial + ': checked avalible party')"], {}), "(device.serial + ': checked avalible party')\n", (54356, 54400), False, 'import logging, json, ctypes\n'), ((54582, 54639), 'logging.info', 'logging.info', (["(device.serial + ': clicked set up sub team')"], {}), "(device.serial + ': clicked set up sub team')\n", (54594, 54639), False, 'import logging, json, ctypes\n'), ((54889, 54943), 'logging.info', 'logging.info', (["(device.serial + ': clicked start battle')"], {}), "(device.serial + ': clicked start battle')\n", (54901, 54943), False, 'import logging, json, ctypes\n'), ((55092, 55142), 'logging.info', 'logging.info', (["(device.serial + ': battle completed')"], {}), "(device.serial + ': battle completed')\n", (55104, 55142), False, 'import logging, json, ctypes\n'), ((55286, 55333), 'logging.info', 'logging.info', (["(device.serial + ': exited battle')"], {}), "(device.serial + ': exited battle')\n", (55298, 55333), False, 'import logging, json, ctypes\n'), ((55550, 55619), 'logging.info', 'logging.info', (["(device.serial + ': successfully did world boss mission')"], {}), "(device.serial + ': successfully did world boss mission')\n", (55562, 55619), False, 'import logging, json, ctypes\n'), ((55780, 55832), 'logging.info', 'logging.info', (["(device.serial + ': feeding lil raider')"], {}), "(device.serial + ': feeding lil raider')\n", (55792, 55832), False, 'import logging, json, ctypes\n'), ((56129, 56191), 'logging.info', 'logging.info', (["(device.serial + ': loaded from mission shortcut')"], {}), "(device.serial + ': loaded from mission shortcut')\n", (56141, 56191), False, 'import logging, json, ctypes\n'), ((56368, 56416), 'logging.info', 'logging.info', (["(device.serial + ': clicked treats')"], {}), "(device.serial + ': clicked treats')\n", (56380, 56416), False, 'import logging, json, ctypes\n'), ((56665, 56711), 'logging.info', 'logging.info', (["(device.serial + ': clicked feed')"], {}), "(device.serial + ': clicked feed')\n", (56677, 56711), False, 'import logging, json, ctypes\n'), ((56890, 56935), 'logging.info', 'logging.info', (["(device.serial + ': exit treats')"], {}), "(device.serial + ': exit treats')\n", (56902, 56935), False, 'import logging, json, ctypes\n'), ((57148, 57217), 'logging.info', 'logging.info', (["(device.serial + ': successfully did lil raider mission')"], {}), "(device.serial + ': successfully did lil raider mission')\n", (57160, 57217), False, 'import logging, json, ctypes\n'), ((57311, 57368), 'logging.info', 'logging.info', (["(device.serial + ': claiming weekly rewards')"], {}), "(device.serial + ': claiming weekly rewards')\n", (57323, 57368), False, 'import logging, json, ctypes\n'), ((57991, 58039), 'logging.info', 'logging.info', (["(device.serial + ': claiming mails')"], {}), "(device.serial + ': claiming mails')\n", (58003, 58039), False, 'import logging, json, ctypes\n'), ((58273, 58330), 'logging.info', 'logging.info', (["(device.serial + ': exit to main screen (1)')"], {}), "(device.serial + ': exit to main screen (1)')\n", (58285, 58330), False, 'import logging, json, ctypes\n'), ((58504, 58553), 'logging.info', 'logging.info', (["(device.serial + ': clicked mailbox')"], {}), "(device.serial + ': clicked mailbox')\n", (58516, 58553), False, 'import logging, json, ctypes\n'), ((58731, 58782), 'logging.info', 'logging.info', (["(device.serial + ': clicked claim all')"], {}), "(device.serial + ': clicked claim all')\n", (58743, 58782), False, 'import logging, json, ctypes\n'), ((59012, 59069), 'logging.info', 'logging.info', (["(device.serial + ': exit to main screen (2)')"], {}), "(device.serial + ': exit to main screen (2)')\n", (59024, 59069), False, 'import logging, json, ctypes\n'), ((59190, 59240), 'logging.info', 'logging.info', (["(device.serial + ': suiciding in loh')"], {}), "(device.serial + ': suiciding in loh')\n", (59202, 59240), False, 'import logging, json, ctypes\n'), ((59474, 59527), 'logging.info', 'logging.info', (["(device.serial + ': exit to main screen')"], {}), "(device.serial + ': exit to main screen')\n", (59486, 59527), False, 'import logging, json, ctypes\n'), ((59714, 59762), 'logging.info', 'logging.info', (["(device.serial + ': clicked portal')"], {}), "(device.serial + ': clicked portal')\n", (59726, 59762), False, 'import logging, json, ctypes\n'), ((59970, 60018), 'logging.info', 'logging.info', (["(device.serial + ': clicked arenas')"], {}), "(device.serial + ': clicked arenas')\n", (59982, 60018), False, 'import logging, json, ctypes\n'), ((60224, 60269), 'logging.info', 'logging.info', (["(device.serial + ': clicked loh')"], {}), "(device.serial + ': clicked loh')\n", (60236, 60269), False, 'import logging, json, ctypes\n'), ((60562, 60616), 'logging.info', 'logging.info', (["(device.serial + ': clicked ok in notice')"], {}), "(device.serial + ': clicked ok in notice')\n", (60574, 60616), False, 'import logging, json, ctypes\n'), ((61770, 61776), 'time.sleep', 'slp', (['(5)'], {}), '(5)\n', (61773, 61776), True, 'from time import sleep as slp\n'), ((61873, 61880), 'time.time', 'tiime', ([], {}), '()\n', (61878, 61880), True, 'from time import time as tiime\n'), ((61930, 61936), 'time.sleep', 'slp', (['(5)'], {}), '(5)\n', (61933, 61936), True, 'from time import sleep as slp\n'), ((62560, 62623), 'logging.info', 'logging.info', (["(device.serial + ': successfully suiciding in loh')"], {}), "(device.serial + ': successfully suiciding in loh')\n", (62572, 62623), False, 'import logging, json, ctypes\n'), ((63127, 63139), 'json.load', 'json.load', (['j'], {}), '(j)\n', (63136, 63139), False, 'import logging, json, ctypes\n'), ((63678, 63690), 'json.load', 'json.load', (['t'], {}), '(t)\n', (63687, 63690), False, 'import logging, json, ctypes\n'), ((63985, 64003), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (63997, 64003), False, 'import logging, json, ctypes\n'), ((64566, 64618), 'threading.Thread', 'Thread', ([], {'target': 'msg_box', 'name': '"""msg_box"""', 'args': '(this,)'}), "(target=msg_box, name='msg_box', args=(this,))\n", (64572, 64618), False, 'from threading import Thread, enumerate\n'), ((77709, 77715), 'time.sleep', 'slp', (['(5)'], {}), '(5)\n', (77712, 77715), True, 'from time import sleep as slp\n'), ((811, 864), 'logging.FileHandler', 'logging.FileHandler', (['"""./.cache/log.log"""', '"""a"""', '"""utf-8"""'], {}), "('./.cache/log.log', 'a', 'utf-8')\n", (830, 864), False, 'import logging, json, ctypes\n'), ((6721, 6740), 'imagehash.average_hash', 'average_hash', (['cache'], {}), '(cache)\n', (6733, 6740), False, 'from imagehash import average_hash\n'), ((8733, 8795), 'logging.info', 'logging.info', (["(device.serial + ': android home screen detected')"], {}), "(device.serial + ': android home screen detected')\n", (8745, 8795), False, 'import logging, json, ctypes\n'), ((8877, 8883), 'time.sleep', 'slp', (['(3)'], {}), '(3)\n', (8880, 8883), True, 'from time import sleep as slp\n'), ((9117, 9173), 'logging.info', 'logging.info', (["(device.serial + ': update notice detected')"], {}), "(device.serial + ': update notice detected')\n", (9129, 9173), False, 'import logging, json, ctypes\n'), ((9241, 9247), 'time.sleep', 'slp', (['(3)'], {}), '(3)\n', (9244, 9247), True, 'from time import sleep as slp\n'), ((9460, 9515), 'logging.info', 'logging.info', (["(device.serial + ': introduction detected')"], {}), "(device.serial + ': introduction detected')\n", (9472, 9515), False, 'import logging, json, ctypes\n'), ((9582, 9588), 'time.sleep', 'slp', (['(3)'], {}), '(3)\n', (9585, 9588), True, 'from time import sleep as slp\n'), ((9796, 9850), 'logging.info', 'logging.info', (["(device.serial + ': tap to play detected')"], {}), "(device.serial + ': tap to play detected')\n", (9808, 9850), False, 'import logging, json, ctypes\n'), ((9916, 9922), 'time.sleep', 'slp', (['(3)'], {}), '(3)\n', (9919, 9922), True, 'from time import sleep as slp\n'), ((10138, 10194), 'logging.info', 'logging.info', (["(device.serial + ': tap to play 2 detected')"], {}), "(device.serial + ': tap to play 2 detected')\n", (10150, 10194), False, 'import logging, json, ctypes\n'), ((10260, 10266), 'time.sleep', 'slp', (['(3)'], {}), '(3)\n', (10263, 10266), True, 'from time import sleep as slp\n'), ((10483, 10540), 'logging.info', 'logging.info', (["(device.serial + ': community page detected')"], {}), "(device.serial + ': community page detected')\n", (10495, 10540), False, 'import logging, json, ctypes\n'), ((10613, 10619), 'time.sleep', 'slp', (['(3)'], {}), '(3)\n', (10616, 10619), True, 'from time import sleep as slp\n'), ((10811, 10863), 'logging.info', 'logging.info', (["(device.serial + ': sale page detected')"], {}), "(device.serial + ': sale page detected')\n", (10823, 10863), False, 'import logging, json, ctypes\n'), ((10931, 10937), 'time.sleep', 'slp', (['(3)'], {}), '(3)\n', (10934, 10937), True, 'from time import sleep as slp\n'), ((11161, 11220), 'logging.info', 'logging.info', (["(device.serial + ': login attendance detected')"], {}), "(device.serial + ': login attendance detected')\n", (11173, 11220), False, 'import logging, json, ctypes\n'), ((11294, 11300), 'time.sleep', 'slp', (['(1)'], {}), '(1)\n', (11297, 11300), True, 'from time import sleep as slp\n'), ((11383, 11389), 'time.sleep', 'slp', (['(3)'], {}), '(3)\n', (11386, 11389), True, 'from time import sleep as slp\n'), ((11586, 11639), 'logging.info', 'logging.info', (["(device.serial + ': event page detected')"], {}), "(device.serial + ': event page detected')\n", (11598, 11639), False, 'import logging, json, ctypes\n'), ((11708, 11714), 'time.sleep', 'slp', (['(3)'], {}), '(3)\n', (11711, 11714), True, 'from time import sleep as slp\n'), ((11962, 12021), 'logging.info', 'logging.info', (["(device.serial + ': guild attendance detected')"], {}), "(device.serial + ': guild attendance detected')\n", (11974, 12021), False, 'import logging, json, ctypes\n'), ((12132, 12138), 'time.sleep', 'slp', (['(1)'], {}), '(1)\n', (12135, 12138), True, 'from time import sleep as slp\n'), ((12225, 12231), 'time.sleep', 'slp', (['(1)'], {}), '(1)\n', (12228, 12231), True, 'from time import sleep as slp\n'), ((12312, 12318), 'time.sleep', 'slp', (['(3)'], {}), '(3)\n', (12315, 12318), True, 'from time import sleep as slp\n'), ((12560, 12621), 'logging.info', 'logging.info', (["(device.serial + ': login accumualated detected')"], {}), "(device.serial + ': login accumualated detected')\n", (12572, 12621), False, 'import logging, json, ctypes\n'), ((12697, 12703), 'time.sleep', 'slp', (['(1)'], {}), '(1)\n', (12700, 12703), True, 'from time import sleep as slp\n'), ((12788, 12794), 'time.sleep', 'slp', (['(3)'], {}), '(3)\n', (12791, 12794), True, 'from time import sleep as slp\n'), ((12996, 13053), 'logging.info', 'logging.info', (["(device.serial + ': new loh season detected')"], {}), "(device.serial + ': new loh season detected')\n", (13008, 13053), False, 'import logging, json, ctypes\n'), ((13116, 13122), 'time.sleep', 'slp', (['(3)'], {}), '(3)\n', (13119, 13122), True, 'from time import sleep as slp\n'), ((13314, 13368), 'logging.info', 'logging.info', (["(device.serial + ': sale 2 page detected')"], {}), "(device.serial + ': sale 2 page detected')\n", (13326, 13368), False, 'import logging, json, ctypes\n'), ((13438, 13444), 'time.sleep', 'slp', (['(1)'], {}), '(1)\n', (13441, 13444), True, 'from time import sleep as slp\n'), ((13523, 13529), 'time.sleep', 'slp', (['(3)'], {}), '(3)\n', (13526, 13529), True, 'from time import sleep as slp\n'), ((14611, 14623), 'json.load', 'json.load', (['j'], {}), '(j)\n', (14620, 14623), False, 'import logging, json, ctypes\n'), ((15623, 15641), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (15635, 15641), False, 'import logging, json, ctypes\n'), ((17142, 17148), 'time.sleep', 'slp', (['(5)'], {}), '(5)\n', (17145, 17148), True, 'from time import sleep as slp\n'), ((31246, 31252), 'time.sleep', 'slp', (['(2)'], {}), '(2)\n', (31249, 31252), True, 'from time import sleep as slp\n'), ((33844, 33852), 'time.sleep', 'slp', (['(0.5)'], {}), '(0.5)\n', (33847, 33852), True, 'from time import sleep as slp\n'), ((33918, 33926), 'time.sleep', 'slp', (['(0.5)'], {}), '(0.5)\n', (33921, 33926), True, 'from time import sleep as slp\n'), ((34102, 34108), 'time.sleep', 'slp', (['(1)'], {}), '(1)\n', (34105, 34108), True, 'from time import sleep as slp\n'), ((50847, 50853), 'time.sleep', 'slp', (['(1)'], {}), '(1)\n', (50850, 50853), True, 'from time import sleep as slp\n'), ((62040, 62047), 'time.time', 'tiime', ([], {}), '()\n', (62045, 62047), True, 'from time import time as tiime\n'), ((62927, 62952), 'subprocess.run', 'run_', (["(adb_dir + 'devices')"], {}), "(adb_dir + 'devices')\n", (62931, 62952), True, 'from subprocess import run as run_\n'), ((62959, 62965), 'time.sleep', 'slp', (['(5)'], {}), '(5)\n', (62962, 62965), True, 'from time import sleep as slp\n'), ((62974, 62999), 'subprocess.run', 'run_', (["(adb_dir + 'devices')"], {}), "(adb_dir + 'devices')\n", (62978, 62999), True, 'from subprocess import run as run_\n'), ((63286, 63309), 'subprocess.run', 'run_', (["(path + ' quitall')"], {}), "(path + ' quitall')\n", (63290, 63309), True, 'from subprocess import run as run_\n'), ((65144, 65162), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (65156, 65162), False, 'import logging, json, ctypes\n'), ((77049, 77074), 'subprocess.run', 'run_', (["(adb_dir + 'devices')"], {}), "(adb_dir + 'devices')\n", (77053, 77074), True, 'from subprocess import run as run_\n'), ((6675, 6699), 'PIL.Image.open', 'Image.open', (['original_img'], {}), '(original_img)\n', (6685, 6699), False, 'from PIL import Image, UnidentifiedImageError, ImageFile\n'), ((8038, 8057), 'time.sleep', 'slp', (['sleep_duration'], {}), '(sleep_duration)\n', (8041, 8057), True, 'from time import sleep as slp\n'), ((8352, 8364), 'json.load', 'json.load', (['j'], {}), '(j)\n', (8361, 8364), False, 'import logging, json, ctypes\n'), ((13808, 13863), 'logging.info', 'logging.info', (["(device.serial + ': special shop detected')"], {}), "(device.serial + ': special shop detected')\n", (13820, 13863), False, 'import logging, json, ctypes\n'), ((13947, 13953), 'time.sleep', 'slp', (['(3)'], {}), '(3)\n', (13950, 13953), True, 'from time import sleep as slp\n'), ((14247, 14306), 'logging.info', 'logging.info', (["(device.serial + ': game home screen detected')"], {}), "(device.serial + ': game home screen detected')\n", (14259, 14306), False, 'import logging, json, ctypes\n'), ((14487, 14493), 'sys.exit', 'exit', ([], {}), '()\n', (14491, 14493), False, 'from sys import exit\n'), ((15125, 15137), 'traceback.format_exc', 'format_exc', ([], {}), '()\n', (15135, 15137), False, 'from traceback import format_exc\n'), ((15150, 15202), 'logging.warn', 'logging.warn', (["(device.serial + ': Exception | ' + var)"], {}), "(device.serial + ': Exception | ' + var)\n", (15162, 15202), False, 'import logging, json, ctypes\n'), ((15870, 15882), 'json.load', 'json.load', (['j'], {}), '(j)\n', (15879, 15882), False, 'import logging, json, ctypes\n'), ((18303, 18320), 'langdetect.detect', 'detect', (['text_lang'], {}), '(text_lang)\n', (18309, 18320), False, 'from langdetect import detect, DetectorFactory\n'), ((22660, 22672), 'json.load', 'json.load', (['j'], {}), '(j)\n', (22669, 22672), False, 'import logging, json, ctypes\n'), ((63430, 63448), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (63442, 63448), False, 'import logging, json, ctypes\n'), ((64493, 64521), 'json.dump', 'json.dump', (['this', 'w'], {'indent': '(4)'}), '(this, w, indent=4)\n', (64502, 64521), False, 'import logging, json, ctypes\n'), ((77295, 77302), 'time.sleep', 'slp', (['(10)'], {}), '(10)\n', (77298, 77302), True, 'from time import sleep as slp\n'), ((77315, 77340), 'subprocess.run', 'run_', (["(adb_dir + 'devices')"], {}), "(adb_dir + 'devices')\n", (77319, 77340), True, 'from subprocess import run as run_\n'), ((5271, 5277), 'time.sleep', 'slp', (['(5)'], {}), '(5)\n', (5274, 5277), True, 'from time import sleep as slp\n'), ((5528, 5534), 'time.sleep', 'slp', (['(5)'], {}), '(5)\n', (5531, 5534), True, 'from time import sleep as slp\n'), ((6221, 6227), 'time.sleep', 'slp', (['(3)'], {}), '(3)\n', (6224, 6227), True, 'from time import sleep as slp\n'), ((7761, 7767), 'time.sleep', 'slp', (['(3)'], {}), '(3)\n', (7764, 7767), True, 'from time import sleep as slp\n'), ((14947, 14965), 'logging.warn', 'logging.warn', (['text'], {}), '(text)\n', (14959, 14965), False, 'import logging, json, ctypes\n'), ((18439, 18445), 'time.sleep', 'slp', (['(1)'], {}), '(1)\n', (18442, 18445), True, 'from time import sleep as slp\n'), ((18486, 18492), 'time.sleep', 'slp', (['(5)'], {}), '(5)\n', (18489, 18492), True, 'from time import sleep as slp\n'), ((21137, 21155), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (21149, 21155), False, 'import logging, json, ctypes\n'), ((21510, 21516), 'sys.exit', 'exit', ([], {}), '()\n', (21514, 21516), False, 'from sys import exit\n'), ((22373, 22460), 'logging.info', 'logging.info', (["(device.serial + ': opened and claimed rewards on daily mission board')"], {}), "(device.serial +\n ': opened and claimed rewards on daily mission board')\n", (22385, 22460), False, 'import logging, json, ctypes\n'), ((25803, 25815), 'json.load', 'json.load', (['j'], {}), '(j)\n', (25812, 25815), False, 'import logging, json, ctypes\n'), ((26061, 26087), 'pytesseract.image_to_string', 'image_to_string', (['img', 'lang'], {}), '(img, lang)\n', (26076, 26087), False, 'from pytesseract import image_to_string\n'), ((50217, 50229), 'json.load', 'json.load', (['j'], {}), '(j)\n', (50226, 50229), False, 'import logging, json, ctypes\n'), ((50431, 50457), 'pytesseract.image_to_string', 'image_to_string', (['img', 'lang'], {}), '(img, lang)\n', (50446, 50457), False, 'from pytesseract import image_to_string\n'), ((60796, 60802), 'time.sleep', 'slp', (['(3)'], {}), '(3)\n', (60799, 60802), True, 'from time import sleep as slp\n'), ((60883, 60889), 'time.sleep', 'slp', (['(5)'], {}), '(5)\n', (60886, 60889), True, 'from time import sleep as slp\n'), ((61106, 61118), 'langdetect.detect', 'detect', (['text'], {}), '(text)\n', (61112, 61118), False, 'from langdetect import detect, DetectorFactory\n'), ((64894, 64922), 'json.dump', 'json.dump', (['this', 'w'], {'indent': '(4)'}), '(this, w, indent=4)\n', (64903, 64922), False, 'import logging, json, ctypes\n'), ((77605, 77623), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (77617, 77623), False, 'import logging, json, ctypes\n'), ((7070, 7092), 'PIL.Image.open', 'Image.open', (['second_img'], {}), '(second_img)\n', (7080, 7092), False, 'from PIL import Image, UnidentifiedImageError, ImageFile\n'), ((18808, 18820), 'json.load', 'json.load', (['j'], {}), '(j)\n', (18817, 18820), False, 'import logging, json, ctypes\n'), ((19380, 19412), 'fuzzywuzzy.process.extractOne', 'extractOne', (['text_lang', 'missions_'], {}), '(text_lang, missions_)\n', (19390, 19412), False, 'from fuzzywuzzy.process import extractOne\n'), ((19708, 19726), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (19720, 19726), False, 'import logging, json, ctypes\n'), ((20053, 20059), 'sys.exit', 'exit', ([], {}), '()\n', (20057, 20059), False, 'from sys import exit\n'), ((21362, 21380), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (21374, 21380), False, 'import logging, json, ctypes\n'), ((26261, 26302), 'difflib.SequenceMatcher', 'SequenceMatcher', (['None', 'dragon_text', 'text_'], {}), '(None, dragon_text, text_)\n', (26276, 26302), False, 'from difflib import SequenceMatcher\n'), ((50629, 50663), 'difflib.SequenceMatcher', 'SequenceMatcher', (['None', 'text', 'floor'], {}), '(None, text, floor)\n', (50644, 50663), False, 'from difflib import SequenceMatcher\n'), ((61313, 61325), 'json.load', 'json.load', (['j'], {}), '(j)\n', (61322, 61325), False, 'import logging, json, ctypes\n'), ((65461, 65479), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (65473, 65479), False, 'import logging, json, ctypes\n'), ((65674, 65692), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (65686, 65692), False, 'import logging, json, ctypes\n'), ((19917, 19935), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (19929, 19935), False, 'import logging, json, ctypes\n'), ((20958, 20976), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (20970, 20976), False, 'import logging, json, ctypes\n'), ((4813, 4819), 'time.sleep', 'slp', (['(5)'], {}), '(5)\n', (4816, 4819), True, 'from time import sleep as slp\n'), ((7303, 7324), 'PIL.Image.open', 'Image.open', (['third_img'], {}), '(third_img)\n', (7313, 7324), False, 'from PIL import Image, UnidentifiedImageError, ImageFile\n'), ((61349, 61393), 'difflib.SequenceMatcher', 'SequenceMatcher', (['None', "re[lang]['loh']", 'text'], {}), "(None, re[lang]['loh'], text)\n", (61364, 61393), False, 'from difflib import SequenceMatcher\n'), ((69417, 69435), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (69429, 69435), False, 'import logging, json, ctypes\n'), ((74516, 74523), 'time.sleep', 'slp', (['(30)'], {}), '(30)\n', (74519, 74523), True, 'from time import sleep as slp\n'), ((3991, 3997), 'time.sleep', 'slp', (['(3)'], {}), '(3)\n', (3994, 3997), True, 'from time import sleep as slp\n'), ((4129, 4135), 'time.sleep', 'slp', (['(3)'], {}), '(3)\n', (4132, 4135), True, 'from time import sleep as slp\n'), ((4304, 4310), 'sys.exit', 'exit', ([], {}), '()\n', (4308, 4310), False, 'from sys import exit\n'), ((18179, 18201), 'pytesseract.image_to_string', 'image_to_string', (['image'], {}), '(image)\n', (18194, 18201), False, 'from pytesseract import image_to_string\n'), ((61035, 61060), 'pytesseract.image_to_string', 'image_to_string', (['im', 'lang'], {}), '(im, lang)\n', (61050, 61060), False, 'from pytesseract import image_to_string\n'), ((66314, 66332), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (66326, 66332), False, 'import logging, json, ctypes\n'), ((66541, 66559), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (66553, 66559), False, 'import logging, json, ctypes\n'), ((66723, 66730), 'time.sleep', 'slp', (['(30)'], {}), '(30)\n', (66726, 66730), True, 'from time import sleep as slp\n'), ((69074, 69092), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (69086, 69092), False, 'import logging, json, ctypes\n'), ((70750, 70757), 'time.sleep', 'slp', (['(10)'], {}), '(10)\n', (70753, 70757), True, 'from time import sleep as slp\n'), ((76821, 76827), 'time.sleep', 'slp', (['(5)'], {}), '(5)\n', (76824, 76827), True, 'from time import sleep as slp\n'), ((68789, 68795), 'time.sleep', 'slp', (['(5)'], {}), '(5)\n', (68792, 68795), True, 'from time import sleep as slp\n'), ((21702, 21734), 'pytesseract.image_to_string', 'image_to_string', (['pil_image', 'lang'], {}), '(pil_image, lang)\n', (21717, 21734), False, 'from pytesseract import image_to_string\n'), ((70949, 70956), 'time.time', 'tiime', ([], {}), '()\n', (70954, 70956), True, 'from time import time as tiime\n'), ((75074, 75092), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (75086, 75092), False, 'import logging, json, ctypes\n'), ((21879, 21905), 'pytesseract.image_to_string', 'image_to_string', (['img', 'lang'], {}), '(img, lang)\n', (21894, 21905), False, 'from pytesseract import image_to_string\n'), ((68563, 68581), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (68575, 68581), False, 'import logging, json, ctypes\n'), ((71136, 71143), 'time.time', 'tiime', ([], {}), '()\n', (71141, 71143), True, 'from time import time as tiime\n'), ((74089, 74107), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (74101, 74107), False, 'import logging, json, ctypes\n'), ((76544, 76562), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (76556, 76562), False, 'import logging, json, ctypes\n'), ((19189, 19219), 'pytesseract.image_to_string', 'image_to_string', (['image', 'lang__'], {}), '(image, lang__)\n', (19204, 19219), False, 'from pytesseract import image_to_string\n'), ((67483, 67501), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (67495, 67501), False, 'import logging, json, ctypes\n'), ((67698, 67705), 'time.time', 'tiime', ([], {}), '()\n', (67703, 67705), True, 'from time import time as tiime\n'), ((72769, 72787), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (72781, 72787), False, 'import logging, json, ctypes\n'), ((73044, 73062), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (73056, 73062), False, 'import logging, json, ctypes\n'), ((73672, 73690), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (73684, 73690), False, 'import logging, json, ctypes\n'), ((67909, 67916), 'time.time', 'tiime', ([], {}), '()\n', (67914, 67916), True, 'from time import time as tiime\n')]
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # 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 heat.engine.components import Component from heat.engine.components import Components from heat.tests.common import HeatTestCase class ComponentTest(HeatTestCase): def test_init(self): comp = Component() self.assertEqual(comp.type, 'OS::Heat::SoftwareConfig') self.assertEqual(comp.properties, {}) self.assertEqual(comp.scripts, {}) self.assertEqual(comp.relations, []) self.assertEqual(comp.hosted_on(), None) self.assertEqual(comp.depends(), []) def test_hosted_on(self): schema = { 'relationships': [ {'hosted_on': 'wordpress'} ] } comp = Component(schema) self.assertEqual(comp.hosted_on(), 'wordpress') def test_depends(self): schema = { 'relationships': [ {'depends_on': 'config_mysql'} ] } comp = Component(schema) self.assertEqual(comp.depends(), ['config_mysql']) comp['relationships'].append({'depends_on': 'config_wordpress'}) self.assertEqual(comp.depends(), ['config_mysql', 'config_wordpress']) class ComponentsTest(HeatTestCase): def test_init(self): schema = {} comps = Components(schema) self.assertEqual(0, len(comps)) schema['config_mysql'] = {} comps = Components(schema) self.assertEqual(1, len(comps)) comp = comps['config_mysql'] self.assertIsInstance(comp, Component) def test_depends(self): schema = { 'install_mysql': { }, 'config_mysql': { 'relationships': [ {'depends_on': 'install_mysql'} ] }, 'start_mysql': { 'relationships': [ {'depends_on': 'config_mysql'} ] } } comps = Components(schema) self.assertEqual(3, len(comps)) deps = comps.depends() self.assertEqual(2, len(deps)) self.assertIn('install_mysql', deps) self.assertIn('config_mysql', deps) def test_multi_depends(self): schema = { 'install_mysql': { }, 'config_mysql': { 'relationships': [ {'depends_on': 'install_mysql'} ] }, 'start_mysql': { 'relationships': [ {'depends_on': 'config_mysql'} ] }, 'install_wordpress': {}, 'config_wordpress': { 'relationships': [ {'depends_on': 'install_wordpress'} ] }, 'start_wordpress': { 'relationships': [ {'depends_on': 'config_wordpress'}, {'depends_on': 'start_mysql'} ] } } comps = Components(schema) deps = comps.depends() self.assertEqual(5, len(deps)) self.assertNotIn('start_wordpress', deps) self.assertIn('install_wordpress', deps) self.assertIn('config_wordpress', deps) self.assertIn('start_mysql', deps) self.assertIn('config_mysql', deps) self.assertIn('install_mysql', deps) def test_filter(self): schema = { 'install_mysql': { 'relationships': [ {'hosted_on': 'mysql'} ] }, 'config_mysql': { 'relationships': [ {'hosted_on': 'mysql'}, {'depends_on': 'install_mysql'} ] }, 'start_mysql': { 'relationships': [ {'hosted_on': 'mysql'}, {'depends_on': 'config_mysql'} ] }, 'install_wordpress': { 'relationships': [ {'hosted_on': 'wordpress'} ] }, 'config_wordpress': { 'relationships': [ {'hosted_on': 'wordpress'}, {'depends_on': 'install_wordpress'} ] }, 'start_wordpress': { 'relationships': [ {'hosted_on': 'wordpress'}, {'depends_on': 'config_wordpress'}, {'depends_on': 'start_mysql'} ] } } comps = Components(schema) names = comps.filter('mysql') self.assertEqual(3, len(names)) self.assertIn('config_mysql', names) self.assertIn('install_mysql', names) self.assertIn('start_mysql', names) names = comps.filter('wordpress') self.assertEqual(3, len(names)) self.assertIn('config_wordpress', names) self.assertIn('install_wordpress', names) self.assertIn('start_wordpress', names) def test_validate(self): schema = {'install_mysql': {}} comps = Components(schema) self.assertTrue(comps.validate()) schema = { 'config_mysql': { 'relationships': [ {'depends_on': 'config_mysql'} ] } } comps = Components(schema) err = self.assertRaises(ValueError, comps.validate) self.assertIn('component config_mysql depends on itself.', str(err)) schema = { 'config_mysql': { 'relationships': [ {'depends_on': 'install_mysql'} ] } } comps = Components(schema) err = self.assertRaises(ValueError, comps.validate) self.assertIn('component install_mysql is not defined.', str(err)) schema = { 'install_mysql': { }, 'config_mysql': { 'relationships': [ {'depends_on': 'install_mysql'}, {'depends_on': 'install_mysql'} ] } } comps = Components(schema) err = self.assertRaises(ValueError, comps.validate) self.assertIn('duplicated install_mysql in config_mysql depends on.', str(err))
[ "heat.engine.components.Components", "heat.engine.components.Component" ]
[((830, 841), 'heat.engine.components.Component', 'Component', ([], {}), '()\n', (839, 841), False, 'from heat.engine.components import Component\n'), ((1297, 1314), 'heat.engine.components.Component', 'Component', (['schema'], {}), '(schema)\n', (1306, 1314), False, 'from heat.engine.components import Component\n'), ((1536, 1553), 'heat.engine.components.Component', 'Component', (['schema'], {}), '(schema)\n', (1545, 1553), False, 'from heat.engine.components import Component\n'), ((1891, 1909), 'heat.engine.components.Components', 'Components', (['schema'], {}), '(schema)\n', (1901, 1909), False, 'from heat.engine.components import Components\n'), ((2003, 2021), 'heat.engine.components.Components', 'Components', (['schema'], {}), '(schema)\n', (2013, 2021), False, 'from heat.engine.components import Components\n'), ((2563, 2581), 'heat.engine.components.Components', 'Components', (['schema'], {}), '(schema)\n', (2573, 2581), False, 'from heat.engine.components import Components\n'), ((3606, 3624), 'heat.engine.components.Components', 'Components', (['schema'], {}), '(schema)\n', (3616, 3624), False, 'from heat.engine.components import Components\n'), ((5186, 5204), 'heat.engine.components.Components', 'Components', (['schema'], {}), '(schema)\n', (5196, 5204), False, 'from heat.engine.components import Components\n'), ((5733, 5751), 'heat.engine.components.Components', 'Components', (['schema'], {}), '(schema)\n', (5743, 5751), False, 'from heat.engine.components import Components\n'), ((5988, 6006), 'heat.engine.components.Components', 'Components', (['schema'], {}), '(schema)\n', (5998, 6006), False, 'from heat.engine.components import Components\n'), ((6339, 6357), 'heat.engine.components.Components', 'Components', (['schema'], {}), '(schema)\n', (6349, 6357), False, 'from heat.engine.components import Components\n'), ((6787, 6805), 'heat.engine.components.Components', 'Components', (['schema'], {}), '(schema)\n', (6797, 6805), False, 'from heat.engine.components import Components\n')]
"""pycstruct definitions Copyright 2021 by <NAME>. All rights reserved. This file is part of the pycstruct python library and is released under the "MIT License Agreement". Please see the LICENSE file that should have been included as part of this package. """ # pylint: disable=too-many-lines, protected-access import collections import math import struct import sys ############################################################################### # Global constants # Basic Types _TYPE = { "int8": {"format": "b", "bytes": 1, "dtype": "i1"}, "uint8": {"format": "B", "bytes": 1, "dtype": "u1"}, "bool8": {"format": "B", "bytes": 1, "dtype": "b1"}, "int16": {"format": "h", "bytes": 2, "dtype": "i2"}, "uint16": {"format": "H", "bytes": 2, "dtype": "u2"}, "bool16": {"format": "H", "bytes": 2}, "float16": {"format": "e", "bytes": 2, "dtype": "f2"}, "int32": {"format": "i", "bytes": 4, "dtype": "i4"}, "uint32": {"format": "I", "bytes": 4, "dtype": "u4"}, "bool32": {"format": "I", "bytes": 4}, "float32": {"format": "f", "bytes": 4, "dtype": "f4"}, "int64": {"format": "q", "bytes": 8, "dtype": "i8"}, "uint64": {"format": "Q", "bytes": 8, "dtype": "u8"}, "bool64": {"format": "Q", "bytes": 8}, "float64": {"format": "d", "bytes": 8, "dtype": "f8"}, } _BYTEORDER = { "native": {"format": "="}, "little": {"format": "<"}, "big": {"format": ">"}, } ############################################################################### # Internal functions def _get_padding(alignment, current_size, next_element_size): """Calculate number of padding bytes required to get next element in the correct alignment """ if alignment == 1: return 0 # Always aligned elem_size = min(alignment, next_element_size) remainder = current_size % elem_size if remainder == 0: return 0 return elem_size - remainder def _round_pow_2(value): """Round value to next power of 2 value - max 16""" if value > 8: return 16 if value > 4: return 8 if value > 2: return 4 return value ############################################################################### # _BaseDef Class class _BaseDef: """This is an abstract base class for definitions""" def size(self): """Returns size in bytes""" raise NotImplementedError def serialize(self, data, buffer=None, offset=0): """Serialize a python object into a binary buffer. If a `buffer` is specified, it will be updated using an optional `offset` instead of creating and returning a new `bytearray`. :param buffer: If not None, the serialization will feed this buffer instead of creating and returning a new `bytearray`. :param offset: If a `buffer` is specified the offset can be set to specify the location of the serialization inside the buffer. :returns: A new bytearray if `buffer` is None, else returns `buffer` """ raise NotImplementedError def deserialize(self, buffer, offset=0): """Deserialize a `buffer` at an optional `offset` into a python object :param buffer: buffer containing the data to deserialize. :param offset: Specify the place of the buffer to deserialize. :returns: A python object """ raise NotImplementedError def _largest_member(self): raise NotImplementedError def _type_name(self): raise NotImplementedError def __getitem__(self, length): """Create an array type from this base type. This make array type easy to create: .. code-block:: python basetype = pycstruct.pycstruct.BaseTypeDef("uint16") arraytype = basetype[10] Be careful that multi dimentional arrays will be defined in the revert from a C declaration: .. code-block:: python basetype = pycstruct.pycstruct.BaseTypeDef("uint16") arraytype = basetype[10][5][2] # The fast axis is the first one (of size 10) """ if not isinstance(length, int): raise TypeError("An integer is expected for a length of array") return ArrayDef(self, length) def dtype(self): """Returns the numpy dtype of this definition""" raise Exception("dtype not implemented for %s" % type(self)) ############################################################################### # BasicTypeDef Class class BasicTypeDef(_BaseDef): """This class represents the basic types (int, float and bool)""" def __init__(self, datatype, byteorder): self.type = datatype self.byteorder = byteorder self.size_bytes = _TYPE[datatype]["bytes"] self.format = _TYPE[datatype]["format"] def serialize(self, data, buffer=None, offset=0): """ Data needs to be an integer, floating point or boolean value """ if buffer is None: assert offset == 0, "When buffer is None, offset have to be unset" buffer = bytearray(self.size()) else: assert len(buffer) >= offset + self.size(), "Specified buffer too small" dataformat = _BYTEORDER[self.byteorder]["format"] + self.format struct.pack_into(dataformat, buffer, offset, data) return buffer def deserialize(self, buffer, offset=0): """ Result is an integer, floating point or boolean value """ dataformat = _BYTEORDER[self.byteorder]["format"] + self.format value = struct.unpack_from(dataformat, buffer, offset)[0] if self.type.startswith("bool"): if value == 0: value = False else: value = True return value def size(self): return self.size_bytes def _largest_member(self): return self.size_bytes def _type_name(self): return self.type def dtype(self): dtype = _TYPE[self.type].get("dtype") if dtype is None: raise NotImplementedError( 'Basic type "%s" is not implemented as dtype' % self.type ) byteorder = _BYTEORDER[self.byteorder]["format"] return byteorder + dtype ############################################################################### # StringDef Class class StringDef(_BaseDef): """This class represents UTF-8 strings""" def __init__(self, length): self.length = length def serialize(self, data, buffer=None, offset=0): """ Data needs to be a string """ if buffer is None: assert offset == 0, "When buffer is None, offset have to be unset" buffer = bytearray(self.size()) else: assert len(buffer) >= offset + self.size(), "Specified buffer too small" if not isinstance(data, str): raise Exception("Not a valid string: {0}".format(data)) utf8_bytes = data.encode("utf-8") if len(utf8_bytes) > self.length: raise Exception( "String overflow. Produced size {0} but max is {1}".format( len(utf8_bytes), self.length ) ) for i, value in enumerate(utf8_bytes): buffer[offset + i] = value return buffer def deserialize(self, buffer, offset=0): """ Result is a string """ size = self.size() # Find null termination index = buffer.find(0, offset, offset + size) if index >= 0: buffer = buffer[offset:index] else: buffer = buffer[offset : offset + size] return buffer.decode("utf-8") def size(self): return self.length # Each element 1 byte def _largest_member(self): return 1 # 1 byte def _type_name(self): return "utf-8" def dtype(self): return ("S", self.length) ############################################################################### # ArrayDef Class class ArrayDef(_BaseDef): """This class represents a fixed size array of a type""" def __init__(self, element_type, length): self.type = element_type self.length = length def serialize(self, data, buffer=None, offset=0): """Serialize a python type into a binary type following this array type""" if not isinstance(data, collections.abc.Iterable): raise Exception("Data shall be a list") if len(data) > self.length: raise Exception("List is larger than {1}".format(self.length)) if buffer is None: assert offset == 0, "When buffer is None, offset have to be unset" buffer = bytearray(self.size()) else: assert len(buffer) >= offset + self.size(), "Specified buffer too small" size = self.type.size() for item in data: self.type.serialize(item, buffer=buffer, offset=offset) offset += size return buffer def _serialize_element(self, index, value, buffer, buffer_offset=0): """Serialize one element into the buffer :param index: Index of the element :type data: int :param value: Value of element :type data: varies :param buffer: Buffer that contains the data to serialize data into. This is an output. :type buffer: bytearray :param buffer_offset: Start address in buffer :type buffer: int :param index: If this is a list (array) which index to deserialize? :type buffer: int """ size = self.type.size() offset = buffer_offset + size * index self.type.serialize(value, buffer=buffer, offset=offset) def deserialize(self, buffer, offset=0): """Deserialize a binary buffer into a python list following this array type""" size = self.type.size() if len(buffer) < offset + size * self.length: raise ValueError( "A buffer size of at least {} is expected".format(size * self.length) ) result = [] for _ in range(self.length): item = self.type.deserialize(buffer=buffer, offset=offset) result.append(item) offset += size return result def _deserialize_element(self, index, buffer, buffer_offset=0): """Deserialize one element from buffer :param index: Index of element :type data: int :param buffer: Buffer that contains the data to deserialize data from. :type buffer: bytearray :param buffer_offset: Start address in buffer :type buffer: int :param index: If this is a list (array) which index to deserialize? :type buffer: int :return: The value of the element :rtype: varies """ size = self.type.size() offset = buffer_offset + size * index value = self.type.deserialize(buffer=buffer, offset=offset) return value def instance(self, buffer=None, buffer_offset=0): """Create an instance of this array. This is an alternative of using dictionaries and the :meth:`ArrayDef.serialize`/ :meth:`ArrayDef.deserialize` methods for representing the data. :param buffer: Byte buffer where data is stored. If no buffer is provided a new byte buffer will be created and the instance will be 'empty'. :type buffer: bytearray, optional :param buffer_offset: Start offset in the buffer. This means that you can have multiple Instances (or other data) that shares the same buffer. :type buffer_offset: int, optional :return: A new Instance object :rtype: :meth:`Instance` """ # I know. This is cyclic import of _InstanceList, since instance depends # on classes within this file. However, it should not be any problem # since this file will be full imported once this method is called. # pylint: disable=cyclic-import, import-outside-toplevel from pycstruct.instance import _InstanceList return _InstanceList(self, buffer, buffer_offset) def size(self): return self.length * self.type.size() def _largest_member(self): return self.type._largest_member() def _type_name(self): return "{}[{}]".format(self.type._type_name(), self.length) def dtype(self): return (self.type.dtype(), self.length) ############################################################################### # StructDef Class class StructDef(_BaseDef): """This class represents a struct or a union definition :param default_byteorder: Byte order of each element unless explicitly set for the element. Valid values are 'native', 'little' and 'big'. :type default_byteorder: str, optional :param alignment: Alignment of elements in bytes. If set to a value > 1 padding will be added between elements when necessary. Use 4 for 32 bit architectures, 8 for 64 bit architectures unless packing is performed. :type alignment: str, optional :param union: If this is set the True, the instance will behave like a union instead of a struct, i.e. all elements share the same data (same start address). Default is False. :type union: boolean, optional """ # pylint: disable=too-many-instance-attributes, too-many-arguments def __init__(self, default_byteorder="native", alignment=1, union=False): """Constructor method""" if default_byteorder not in _BYTEORDER: raise Exception("Invalid byteorder: {0}.".format(default_byteorder)) self.__default_byteorder = default_byteorder self.__alignment = alignment self.__union = union self.__pad_count = 0 self.__fields = collections.OrderedDict() self.__fields_same_level = collections.OrderedDict() self.__dtype = None # Add end padding of 0 size self.__pad_byte = BasicTypeDef("uint8", default_byteorder) self.__pad_end = ArrayDef(self.__pad_byte, 0) @staticmethod def _normalize_shape(length, shape): """Sanity check and normalization for length and shape. The `length` is used to define a string size, and `shape` is used to define an array shape. Both can be used at the same time. Returns the final size of the array, as a tuple of int. """ if shape is None: shape = tuple() elif isinstance(shape, int): shape = (shape,) elif isinstance(shape, collections.abc.Iterable): shape = tuple(shape) for dim in shape: if not isinstance(dim, int) or dim < 1: raise ValueError( "Strict positive dimensions are expected: {0}.".format(shape) ) if length == 1: # It's just the type without array pass elif isinstance(length, int): if length < 1: raise ValueError( "Strict positive dimension is expected: {0}.".format(length) ) shape = shape + (length,) return shape def add(self, datatype, name, length=1, byteorder="", same_level=False, shape=None): """Add a new element in the struct/union definition. The element will be added directly after the previous element if a struct or in parallel with the previous element if union. Padding might be added depending on the alignment setting. - Supported data types: +------------+---------------+--------------------------------------+ | Name | Size in bytes | Comment | +============+===============+======================================+ | int8 | 1 | Integer | +------------+---------------+--------------------------------------+ | uint8 | 1 | Unsigned integer | +------------+---------------+--------------------------------------+ | bool8 | 1 | True (<>0) or False (0) | +------------+---------------+--------------------------------------+ | int16 | 2 | Integer | +------------+---------------+--------------------------------------+ | uint16 | 2 | Unsigned integer | +------------+---------------+--------------------------------------+ | bool16 | 2 | True (<>0) or False (0) | +------------+---------------+--------------------------------------+ | float16 | 2 | Floating point number | +------------+---------------+--------------------------------------+ | int32 | 4 | Integer | +------------+---------------+--------------------------------------+ | uint32 | 4 | Unsigned integer | +------------+---------------+--------------------------------------+ | bool32 | 4 | True (<>0) or False (0) | +------------+---------------+--------------------------------------+ | float32 | 4 | Floating point number | +------------+---------------+--------------------------------------+ | int64 | 8 | Integer | +------------+---------------+--------------------------------------+ | uint64 | 8 | Unsigned integer | +------------+---------------+--------------------------------------+ | bool64 | 8 | True (<>0) or False (0) | +------------+---------------+--------------------------------------+ | float64 | 8 | Floating point number | +------------+---------------+--------------------------------------+ | utf-8 | 1 | UTF-8/ASCII string. Use length | | | | parameter to set the length of the | | | | string including null termination | +------------+---------------+--------------------------------------+ | struct | struct size | Embedded struct. The actual | | | | StructDef object shall be set as | | | | type and not 'struct' string. | +------------+---------------+--------------------------------------+ | bitfield | bitfield size | Bitfield. The actual | | | | :meth:`BitfieldDef` object shall be | | | | set as type and not 'bitfield' | | | | string. | +------------+---------------+--------------------------------------+ | enum | enum size | Enum. The actual :meth:`EnumDef` | | | | object shall be set as type and not | | | | 'enum' string. | +------------+---------------+--------------------------------------+ :param datatype: Element data type. See above. :type datatype: str :param name: Name of element. Needs to be unique. :type name: str :param length: Number of elements. If > 1 this is an array/list of elements with equal size. Default is 1. This should only be specified for string size. Use `shape` for arrays. :type length: int, optional :param shape: If specified an array of this shape is defined. It supported, int, and tuple of int for multi-dimentional arrays (the last is the fast axis) :type shape: int, tuple, optional :param byteorder: Byteorder of this element. Valid values are 'native', 'little' and 'big'. If not specified the default byteorder is used. :type byteorder: str, optional :param same_level: Relevant if adding embedded bitfield. If True, the serialized or deserialized dictionary keys will be on the same level as the parent. Default is False. :type same_level: bool, optional """ # pylint: disable=too-many-branches # Sanity checks shape = self._normalize_shape(length, shape) if name in self.__fields: raise Exception("Field name already exist: {0}.".format(name)) if byteorder == "": byteorder = self.__default_byteorder elif byteorder not in _BYTEORDER: raise Exception("Invalid byteorder: {0}.".format(byteorder)) if same_level and len(shape) != 0: raise Exception("same_level not allowed in combination with arrays") if same_level and not isinstance(datatype, BitfieldDef): raise Exception("same_level only allowed in combination with BitfieldDef") # Invalidate the dtype cache self.__dtype = None # Create objects when necessary if datatype == "utf-8": if shape == tuple(): shape = (1,) datatype = StringDef(shape[-1]) # Remaining dimensions for arrays of string shape = shape[0:-1] elif datatype in _TYPE: datatype = BasicTypeDef(datatype, byteorder) elif not isinstance(datatype, _BaseDef): raise Exception("Invalid datatype: {0}.".format(datatype)) if len(shape) > 0: for dim in reversed(shape): datatype = ArrayDef(datatype, dim) # Remove end padding if it exists self.__fields.pop("__pad_end", "") # Offset in buffer (for unions always 0) offset = 0 # Check if padding between elements is required (only struct not union) if not self.__union: offset = self.size() padding = _get_padding( self.__alignment, self.size(), datatype._largest_member() ) if padding > 0: padtype = ArrayDef(self.__pad_byte, padding) self.__fields["__pad_{0}".format(self.__pad_count)] = { "type": padtype, "same_level": False, "offset": offset, } offset += padding self.__pad_count += 1 # Add the element self.__fields[name] = { "type": datatype, "same_level": same_level, "offset": offset, } # Check if end padding is required padding = _get_padding(self.__alignment, self.size(), self._largest_member()) if padding > 0: offset += datatype.size() self.__pad_end.length = padding self.__fields["__pad_end"] = { "type": self.__pad_end, "offset": offset, "same_level": False, } # If same_level, store the bitfield elements if same_level: for subname in datatype._element_names(): self.__fields_same_level[subname] = name def size(self): """Get size of structure or union. :return: Number of bytes this structure represents alternatively largest of the elements (including end padding) if this is a union. :rtype: int """ all_elem_size = 0 largest_size = 0 for name, field in self.__fields.items(): fieldtype = field["type"] elem_size = fieldtype.size() if not name.startswith("__pad") and elem_size > largest_size: largest_size = elem_size all_elem_size += elem_size if self.__union: return largest_size + self.__pad_end.length # Union return all_elem_size # Struct def _largest_member(self): """Used for struct/union padding :return: Largest member :rtype: int """ largest = 0 for field in self.__fields.values(): current_largest = field["type"]._largest_member() if current_largest > largest: largest = current_largest return largest def deserialize(self, buffer, offset=0): """Deserialize buffer into dictionary""" result = {} if len(buffer) < self.size() + offset: raise Exception( "Invalid buffer size: {0}. Expected: {1}".format( len(buffer), self.size() ) ) # for name, field in self.__fields.items(): for name in self._element_names(): if name.startswith("__pad"): continue data = self._deserialize_element(name, buffer, buffer_offset=offset) result[name] = data return result def _deserialize_element(self, name, buffer, buffer_offset=0): """Deserialize one element from buffer :param name: Name of element :type data: str :param buffer: Buffer that contains the data to deserialize data from. :type buffer: bytearray :param buffer_offset: Start address in buffer :type buffer: int :param index: If this is a list (array) which index to deserialize? :type buffer: int :return: The value of the element :rtype: varies """ if name in self.__fields_same_level: # This is a bitfield on same level field = self.__fields[self.__fields_same_level[name]] bitfield = field["type"] return bitfield._deserialize_element( name, buffer, buffer_offset + field["offset"] ) field = self.__fields[name] datatype = field["type"] offset = field["offset"] try: value = datatype.deserialize(buffer, buffer_offset + offset) except Exception as exception: raise Exception( "Unable to deserialize {} {}. Reason:\n{}".format( datatype._type_name(), name, exception.args[0] ) ) from exception return value def serialize(self, data, buffer=None, offset=0): """Serialize dictionary into buffer NOTE! If this is a union the method will try to serialize all the elements into the buffer (at the same position in the buffer). It is quite possible that the elements in the dictionary have contradicting data and the buffer of the last serialized element will be ok while the others might be wrong. Thus you should only define the element that you want to serialize in the dictionary. :param data: A dictionary keyed with element names. Elements can be omitted from the dictionary (defaults to value 0). :type data: dict :return: A buffer that contains data :rtype: bytearray """ if buffer is None: assert offset == 0, "When buffer is None, offset have to be unset" buffer = bytearray(self.size()) else: assert len(buffer) >= offset + self.size(), "Specified buffer too small" for name in self._element_names(): if name in data and not name.startswith("__pad"): self._serialize_element(name, data[name], buffer, buffer_offset=offset) return buffer def _serialize_element(self, name, value, buffer, buffer_offset=0): """Serialize one element into the buffer :param name: Name of element :type data: str :param value: Value of element :type data: varies :param buffer: Buffer that contains the data to serialize data into. This is an output. :type buffer: bytearray :param buffer_offset: Start address in buffer :type buffer: int :param index: If this is a list (array) which index to deserialize? :type buffer: int """ if name in self.__fields_same_level: # This is a bitfield on same level field = self.__fields[self.__fields_same_level[name]] bitfield = field["type"] bitfield._serialize_element( name, value, buffer, buffer_offset + field["offset"] ) return # We are done field = self.__fields[name] datatype = field["type"] offset = field["offset"] next_offset = buffer_offset + offset try: datatype.serialize(value, buffer, next_offset) except Exception as exception: raise Exception( "Unable to serialize {} {}. Reason:\n{}".format( datatype._type_name(), name, exception.args[0] ) ) from exception def instance(self, buffer=None, buffer_offset=0): """Create an instance of this struct / union. This is an alternative of using dictionaries and the :meth:`StructDef.serialize`/ :meth:`StructDef.deserialize` methods for representing the data. :param buffer: Byte buffer where data is stored. If no buffer is provided a new byte buffer will be created and the instance will be 'empty'. :type buffer: bytearray, optional :param buffer_offset: Start offset in the buffer. This means that you can have multiple Instances (or other data) that shares the same buffer. :type buffer_offset: int, optional :return: A new Instance object :rtype: :meth:`Instance` """ # I know. This is cyclic import of Instance, since instance depends # on classes within this file. However, it should not be any problem # since this file will be full imported once this method is called. # pylint: disable=cyclic-import, import-outside-toplevel from pycstruct.instance import Instance return Instance(self, buffer, buffer_offset) def create_empty_data(self): """Create an empty dictionary with all keys :return: A dictionary keyed with the element names. Values are "empty" or 0. :rtype: dict """ buffer = bytearray(self.size()) return self.deserialize(buffer) def __str__(self): """Create string representation :return: A string illustrating all members (not Bitfield fields with same_level = True) :rtype: string """ result = [] result.append( "{:<30}{:<15}{:<10}{:<10}{:<10}{:<10}".format( "Name", "Type", "Size", "Length", "Offset", "Largest type" ) ) for name, field in self.__fields.items(): datatype = field["type"] if isinstance(datatype, ArrayDef): length = [] while isinstance(datatype, ArrayDef): length.append(datatype.length) datatype = datatype.type length = ",".join([str(l) for l in length]) else: length = "" result.append( "{:<30}{:<15}{:<10}{:<10}{:<10}{:<10}".format( name, datatype._type_name(), datatype.size(), length, field["offset"], datatype._largest_member(), ) ) return "\n".join(result) def _type_name(self): if self.__union: return "union" return "struct" def remove_from(self, name): """Remove all elements from a specific element This function is useful to create a sub-set of a struct. :param name: Name of element to remove and all after this element :type name: str """ self._remove_from_or_to(name, to_criteria=False) def remove_to(self, name): """Remove all elements from beginning to a specific element This function is useful to create a sub-set of a struct. :param name: Name of element to remove and all before element :type name: str """ self._remove_from_or_to(name, to_criteria=True) def _remove_from_or_to(self, name, to_criteria=True): if name not in self.__fields: raise Exception("Element {} does not exist".format(name)) # Invalidate the dtype cache self.__dtype = None keys = list(self.__fields) if not to_criteria: keys.reverse() for key in keys: del self.__fields[key] if key == name: break # Done if len(self.__fields) > 0: # Update offset of all elements keys = list(self.__fields) adjust_offset = self.__fields[keys[0]]["offset"] for _, field in self.__fields.items(): field["offset"] -= adjust_offset def _element_names(self): """Get a list of all element names (in correct order) Note that this method also include elements of bitfields with same_level = True :return: A list of all elements :rtype: list """ result = [] for name, field in self.__fields.items(): if field["same_level"]: for subname, parent_name in self.__fields_same_level.items(): if name == parent_name: result.append(subname) else: result.append(name) return result def _element_type(self, name): """Returns the type of element. Note that elements of bitfields with same_level = True will be returned as None. :return: Type of element or None :rtype: pycstruct class """ if name in self.__fields: return self.__fields[name]["type"] return None def _element_offset(self, name): """Returns the offset of the element. :return: Offset of element :rtype: int """ if name in self.__fields: return self.__fields[name]["offset"] raise Exception("Invalid element {}".format(name)) def get_field_type(self, name): """Returns the type of a field of this struct. :return: Type if the field :rtype: _BaseDef """ return self._element_type(name) def dtype(self): """Returns the dtype of this structure as defined by numpy. This allows to use the pycstruct modelization together with numpy to read C structures from buffers. .. code-block:: python color_t = StructDef() color_t.add("uint8", "r") color_t.add("uint8", "g") color_t.add("uint8", "b") color_t.add("uint8", "a") raw = b"\x01\x02\x03\x00" color = numpy.frombuffer(raw, dtype=color_t.dtype()) :return: a python dict representing a numpy dtype :rtype: dict """ if self.__dtype is not None: return self.__dtype names = [] formats = [] offsets = [] for name in self._element_names(): if name.startswith("__pad"): continue if name not in self.__fields: continue datatype = self.__fields[name]["type"] offset = self.__fields[name]["offset"] dtype = datatype.dtype() names.append(name) formats.append(dtype) offsets.append(offset) dtype_def = { "names": names, "formats": formats, "offsets": offsets, "itemsize": self.size(), } self.__dtype = dtype_def return dtype_def ############################################################################### # BitfieldDef Class class BitfieldDef(_BaseDef): """This class represents a bit field definition The size of the bit field is 1, 2, 3, .., 8 bytes depending on the number of elements added to the bit field. You can also force the bitfield size by setting the size argument. When forcing the size larger bitfields than 8 bytes are allowed. :param byteorder: Byte order of the bitfield. Valid values are 'native', 'little' and 'big'. :type byteorder: str, optional :param size: Force bitfield to be a certain size. By default it will expand when new elements are added. :type size: int, optional """ def __init__(self, byteorder="native", size=-1): if byteorder not in _BYTEORDER: raise Exception("Invalid byteorder: {0}.".format(byteorder)) if byteorder == "native": byteorder = sys.byteorder self.__byteorder = byteorder self.__size = size self.__fields = collections.OrderedDict() def add(self, name, nbr_of_bits=1, signed=False): """Add a new element in the bitfield definition. The element will be added directly after the previous element. The size of the bitfield will expand when required, but adding more than in total 64 bits (8 bytes) will generate an exception. :param name: Name of element. Needs to be unique. :type name: str :param nbr_of_bits: Number of bits this element represents. Default is 1. :type nbr_of_bits: int, optional :param signed: Should the bit field be signed or not. Default is False. :type signed: bool, optional""" # Check for same bitfield name if name in self.__fields: raise Exception("Field with name {0} already exists.".format(name)) # Check that new size is not too large assigned_bits = self.assigned_bits() total_nbr_of_bits = assigned_bits + nbr_of_bits if total_nbr_of_bits > self._max_bits(): raise Exception( "Maximum number of bits ({}) exceeded: {}.".format( self._max_bits(), total_nbr_of_bits ) ) self.__fields[name] = { "nbr_of_bits": nbr_of_bits, "signed": signed, "offset": assigned_bits, } def deserialize(self, buffer, offset=0): """Deserialize buffer into dictionary :param buffer: Buffer that contains the data to deserialize (1 - 8 bytes) :type buffer: bytearray :param buffer_offset: Start address in buffer :type buffer: int :return: A dictionary keyed with the element names :rtype: dict """ result = {} if len(buffer) < self.size() + offset: raise Exception( "Invalid buffer size: {0}. Expected at least: {1}".format( len(buffer), self.size() ) ) for name in self._element_names(): result[name] = self._deserialize_element(name, buffer, buffer_offset=offset) return result def _deserialize_element(self, name, buffer, buffer_offset=0): """Deserialize one element from buffer :param name: Name of element :type data: str :param buffer: Buffer that contains the data to deserialize data from (1 - 8 bytes). :type buffer: bytearray :param buffer_offset: Start address in buffer :type buffer: int :return: The value of the element :rtype: int """ buffer = buffer[buffer_offset : buffer_offset + self.size()] full_value = int.from_bytes(buffer, self.__byteorder, signed=False) field = self.__fields[name] return self._get_subvalue( full_value, field["nbr_of_bits"], field["offset"], field["signed"] ) def serialize(self, data, buffer=None, offset=0): """Serialize dictionary into buffer :param data: A dictionary keyed with element names. Elements can be omitted from the dictionary (defaults to value 0). :type data: dict :return: A buffer that contains data :rtype: bytearray """ if buffer is None: assert offset == 0, "When buffer is None, offset have to be unset" buffer = bytearray(self.size()) else: assert len(buffer) >= offset + self.size(), "Specified buffer too small" for name in self._element_names(): if name in data: self._serialize_element(name, data[name], buffer, buffer_offset=offset) return buffer def _serialize_element(self, name, value, buffer, buffer_offset=0): """Serialize one element into the buffer :param name: Name of element :type data: str :param value: Value of element :type data: int :param buffer: Buffer that contains the data to serialize data into (1 - 8 bytes). This is an output. :type buffer: bytearray :param buffer_offset: Start address in buffer :type buffer: int """ full_value = int.from_bytes( buffer[buffer_offset : buffer_offset + self.size()], self.__byteorder, signed=False, ) field = self.__fields[name] value = self._set_subvalue( full_value, value, field["nbr_of_bits"], field["offset"], field["signed"] ) buffer[buffer_offset : buffer_offset + self.size()] = value.to_bytes( self.size(), self.__byteorder, signed=False ) def instance(self, buffer=None, buffer_offset=0): """Create an instance of this bitfield. This is an alternative of using dictionaries and the :meth:`BitfieldDef.serialize`/ :meth:`BitfieldDef.deserialize` methods for representing the data. :param buffer: Byte buffer where data is stored. If no buffer is provided a new byte buffer will be created and the instance will be 'empty'. :type buffer: bytearray, optional :param buffer_offset: Start offset in the buffer. This means that you can have multiple Instances (or other data) that shares the same buffer. :type buffer_offset: int, optional :return: A new Instance object :rtype: :meth:`Instance` """ # I know. This is cyclic import of Instance, since instance depends # on classes within this file. However, it should not be any problem # since this file will be full imported once this method is called. # pylint: disable=cyclic-import, import-outside-toplevel from pycstruct.instance import Instance return Instance(self, buffer, buffer_offset) def assigned_bits(self): """Get size of bitfield in bits excluding padding bits :return: Number of bits this bitfield represents excluding padding bits :rtype: int """ total_nbr_of_bits = 0 for _, field in self.__fields.items(): total_nbr_of_bits += field["nbr_of_bits"] return total_nbr_of_bits def size(self): """Get size of bitfield in bytes :return: Number of bytes this bitfield represents :rtype: int """ if self.__size >= 0: return self.__size # Force size return int(math.ceil(self.assigned_bits() / 8.0)) def _max_bits(self): if self.__size >= 0: return self.__size * 8 # Force size return 64 def _largest_member(self): """Used for struct padding :return: Closest power of 2 value of size :rtype: int """ return _round_pow_2(self.size()) def _get_subvalue(self, value, nbr_of_bits, start_bit, signed): """Get subvalue of value :return: The subvalue :rtype: int """ # pylint: disable=no-self-use shifted_value = value >> start_bit mask = 0xFFFFFFFFFFFFFFFF >> (64 - nbr_of_bits) non_signed_value = shifted_value & mask if not signed: return non_signed_value sign_bit = 0x1 << (nbr_of_bits - 1) if non_signed_value & sign_bit == 0: # Value is positive return non_signed_value # Convert to negative value using Two's complement signed_value = -1 * ((~non_signed_value & mask) + 1) return signed_value def _set_subvalue(self, value, subvalue, nbr_of_bits, start_bit, signed): """Set subvalue of value :return: New value where subvalue is included :rtype: int """ # pylint: disable=too-many-arguments,no-self-use # Validate size according to nbr_of_bits max_value = 2 ** nbr_of_bits - 1 min_value = 0 if signed: max_value = 2 ** (nbr_of_bits - 1) - 1 min_value = -1 * (2 ** (nbr_of_bits - 1)) signed_str = "Unsigned" if signed: signed_str = "Signed" if subvalue > max_value: raise Exception( "{0} value {1} is too large to fit in {2} bits. Max value is {3}.".format( signed_str, subvalue, nbr_of_bits, max_value ) ) if subvalue < min_value: raise Exception( "{0} value {1} is too small to fit in {2} bits. Min value is {3}.".format( signed_str, subvalue, nbr_of_bits, min_value ) ) if signed and subvalue < 0: # Convert from negative value using Two's complement sign_bit = 0x1 << (nbr_of_bits - 1) subvalue = sign_bit | ~(-1 * subvalue - 1) mask = 0xFFFFFFFFFFFFFFFF >> (64 - nbr_of_bits) shifted_subvalue = (subvalue & mask) << start_bit return value | shifted_subvalue def create_empty_data(self): """Create an empty dictionary with all keys :return: A dictionary keyed with the element names. Values are "empty" or 0. :rtype: dict """ buffer = bytearray(self.size()) return self.deserialize(buffer) def _type_name(self): return "bitfield" def __str__(self): """Create string representation :return: A string illustrating all members :rtype: string """ result = [] result.append( "{:<30}{:<10}{:<10}{:<10}".format("Name", "Bits", "Offset", "Signed") ) for name, field in self.__fields.items(): signed = "-" if field["signed"]: signed = "x" result.append( "{:<30}{:<10}{:<10}{:<10}".format( name, field["nbr_of_bits"], field["offset"], signed ) ) return "\n".join(result) def _element_names(self): """Get a list of all element names (in correct order) :return: A list of all elements :rtype: list """ result = [] for name in self.__fields.keys(): result.append(name) return result ############################################################################### # EnumDef Class class EnumDef(_BaseDef): """This class represents an enum definition The size of the enum is 1, 2, 3, .., 8 bytes depending on the value of the largest enum constant. You can also force the enum size by setting the size argument. :param byteorder: Byte order of the enum. Valid values are 'native', 'little' and 'big'. :type byteorder: str, optional :param size: Force enum to be a certain size. By default it will expand when new elements are added. :type size: int, optional :param signed: True if enum is signed (may contain negative values) :type signed: bool, optional """ def __init__(self, byteorder="native", size=-1, signed=False): if byteorder not in _BYTEORDER: raise Exception("Invalid byteorder: {0}.".format(byteorder)) if byteorder == "native": byteorder = sys.byteorder self.__byteorder = byteorder self.__size = size self.__signed = signed self.__constants = collections.OrderedDict() def add(self, name, value=None): """Add a new constant in the enum definition. Multiple constant might be assigned to the same value. The size of the enum will expand when required, but adding a value requiring a size larger than 64 bits will generate an exception. :param name: Name of constant. Needs to be unique. :type name: str :param value: Value of the constant. Automatically assigned to next available value (0, 1, 2, ...) if not provided. :type value: int, optional""" # pylint: disable=bare-except # Check for same bitfield name if name in self.__constants: raise Exception("Constant with name {0} already exists.".format(name)) # Automatically assigned to next available value index = 0 while value is None: try: self.get_name(index) index += 1 except: value = index # Secure that no negative number are added to signed enum if not self.__signed and value < 0: raise Exception( "Negative value, {0}, not supported in unsigned enums.".format(value) ) # Check that new size is not too large if self._bit_length(value) > self._max_bits(): raise Exception( "Maximum number of bits ({}) exceeded: {}.".format( self._max_bits(), self._bit_length(value) ) ) self.__constants[name] = value def deserialize(self, buffer, offset=0): """Deserialize buffer into a string (constant name) If no constant name is defined for the value following name will be returned:: __VALUE__<value> Where <value> is the integer stored in the buffer. :param buffer: Buffer that contains the data to deserialize (1 - 8 bytes) :type buffer: bytearray :return: The constant name (string) :rtype: str """ # pylint: disable=bare-except if len(buffer) < self.size() + offset: raise Exception( "Invalid buffer size: {0}. Expected: {1}".format( len(buffer), self.size() ) ) value = int.from_bytes( buffer[offset : offset + self.size()], self.__byteorder, signed=self.__signed, ) name = "" try: name = self.get_name(value) except: # No constant name exist, generate a new name = "__VALUE__{}".format(value) return name def serialize(self, data, buffer=None, offset=0): """Serialize string (constant name) into buffer :param data: A string representing the constant name. :type data: str :return: A buffer that contains data :rtype: bytearray """ if buffer is None: assert offset == 0, "When buffer is None, offset have to be unset" value = self.get_value(data) result = value.to_bytes(self.size(), self.__byteorder, signed=self.__signed) if buffer is not None: buffer[offset : offset + len(result)] = result return buffer return result def size(self): """Get size of enum in bytes :return: Number of bytes this enum represents :rtype: int """ if self.__size >= 0: return self.__size # Force size max_length = 1 # To avoid 0 size for _, value in self.__constants.items(): bit_length = self._bit_length(value) if bit_length > max_length: max_length = bit_length return int(math.ceil(max_length / 8.0)) def _max_bits(self): if self.__size >= 0: return self.__size * 8 # Force size return 64 def _largest_member(self): """Used for struct padding :return: Closest power of 2 value of size :rtype: int """ return _round_pow_2(self.size()) def get_name(self, value): """Get the name representation of the value :return: The constant name :rtype: str """ for constant, item_value in self.__constants.items(): if value == item_value: return constant raise Exception("Value {0} is not a valid value for this enum.".format(value)) def get_value(self, name): """Get the value representation of the name :return: The value :rtype: int """ if name not in self.__constants: raise Exception("{0} is not a valid name in this enum".format(name)) return self.__constants[name] def _type_name(self): return "enum" def _bit_length(self, value): """Get number of bits a value represents. Works for negative values based on two's complement, which is not considered in the python built in bit_length method. If enum is signed the extra sign bit is included in the returned result. """ if value < 0: value += 1 # Two's complement reverse bit_length = value.bit_length() if self.__signed: bit_length += 1 return bit_length def __str__(self): """Create string representation :return: A string illustrating all constants :rtype: string """ result = [] result.append("{:<30}{:<10}".format("Name", "Value")) for name, value in self.__constants.items(): result.append("{:<30}{:<10}".format(name, value)) return "\n".join(result)
[ "collections.OrderedDict", "math.ceil", "struct.pack_into", "pycstruct.instance._InstanceList", "pycstruct.instance.Instance", "struct.unpack_from" ]
[((5305, 5355), 'struct.pack_into', 'struct.pack_into', (['dataformat', 'buffer', 'offset', 'data'], {}), '(dataformat, buffer, offset, data)\n', (5321, 5355), False, 'import struct\n'), ((12221, 12263), 'pycstruct.instance._InstanceList', '_InstanceList', (['self', 'buffer', 'buffer_offset'], {}), '(self, buffer, buffer_offset)\n', (12234, 12263), False, 'from pycstruct.instance import _InstanceList\n'), ((14071, 14096), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (14094, 14096), False, 'import collections\n'), ((14132, 14157), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (14155, 14157), False, 'import collections\n'), ((30925, 30962), 'pycstruct.instance.Instance', 'Instance', (['self', 'buffer', 'buffer_offset'], {}), '(self, buffer, buffer_offset)\n', (30933, 30962), False, 'from pycstruct.instance import Instance\n'), ((37858, 37883), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (37881, 37883), False, 'import collections\n'), ((43724, 43761), 'pycstruct.instance.Instance', 'Instance', (['self', 'buffer', 'buffer_offset'], {}), '(self, buffer, buffer_offset)\n', (43732, 43761), False, 'from pycstruct.instance import Instance\n'), ((49281, 49306), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (49304, 49306), False, 'import collections\n'), ((5583, 5629), 'struct.unpack_from', 'struct.unpack_from', (['dataformat', 'buffer', 'offset'], {}), '(dataformat, buffer, offset)\n', (5601, 5629), False, 'import struct\n'), ((53095, 53122), 'math.ceil', 'math.ceil', (['(max_length / 8.0)'], {}), '(max_length / 8.0)\n', (53104, 53122), False, 'import math\n')]
import huckelpy from huckelpy import file_io class ExtendedHuckel: def __init__(self, geometry, charge=0): self._EH = huckelpy.ExtendedHuckel(geometry.get_positions(), geometry.get_symbols(), charge=charge) self._alpha_electrons = None self._beta_electrons = None self._total_electrons = self._EH.get_number_of_electrons() def get_mo_coefficients(self): return self._EH.get_eigenvectors() def get_basis(self): return self._EH.get_molecular_basis() def get_mo_energies(self): return self._EH.get_mo_energies() def get_multiplicity(self): return self._EH.get_multiplicity() def get_alpha_electrons(self): if self._alpha_electrons is None: self._alpha_electrons = self._total_electrons // 2 + self.get_multiplicity() - 1 return self._alpha_electrons def get_beta_electrons(self): return self._total_electrons - self._alpha_electrons def build_fchk_file(self, name): txt_fchk = file_io.build_fchk(self._EH) open(name + '.fchk', 'w').write(txt_fchk)
[ "huckelpy.file_io.build_fchk" ]
[((1024, 1052), 'huckelpy.file_io.build_fchk', 'file_io.build_fchk', (['self._EH'], {}), '(self._EH)\n', (1042, 1052), False, 'from huckelpy import file_io\n')]
# SPDX-License-Identifier: BSD-2-Clause-Patent # SPDX-FileCopyrightText: 2020 the prplMesh contributors (see AUTHORS.md) # This code is subject to the terms of the BSD+Patent license. # See LICENSE file for more details. from .prplmesh_base_test import PrplMeshBaseTest from boardfarm.exceptions import SkipTest from capi import tlv class ApConfigBSSTeardown(PrplMeshBaseTest): """Check SSID is still available after being torn down Devices used in test setup: AP1 - Agent1 [DUT] GW - Controller """ def runTest(self): # Locate test participants try: agent = self.dev.DUT.agent_entity controller = self.dev.lan.controller_entity except AttributeError as ae: raise SkipTest(ae) self.dev.DUT.wired_sniffer.start(self.__class__.__name__ + "-" + self.dev.DUT.name) # Configure the controller and send renew self.device_reset_default() controller.cmd_reply( "DEV_SET_CONFIG,bss_info1," "{} 8x Boardfarm-Tests-24G-3 0x0020 0x0008 maprocks1 0 1".format(agent.mac)) controller.dev_send_1905(agent.mac, self.ieee1905['eMessageType'] ['AP_AUTOCONFIGURATION_RENEW_MESSAGE'], tlv(self.ieee1905['eTlvType']['TLV_AL_MAC_ADDRESS'], "{" + controller.mac + "}"), tlv(self.ieee1905['eTlvType']['TLV_SUPPORTED_ROLE'], "{" + f"""0x{self.ieee1905['tlvSupportedRole'] ['eValue']['REGISTRAR']:02x}""" + "}"), tlv(self.ieee1905['eTlvType']['TLV_SUPPORTED_FREQ_BAND'], "{" + f"""0x{self.ieee1905['tlvSupportedFreqBand'] ['eValue']['BAND_2_4G']:02x}""" + "}")) # Wait until the connection map is updated: self.check_log(controller, rf"Setting node '{agent.radios[0].mac}' as active", timeout=10) self.check_log(controller, rf"Setting node '{agent.radios[1].mac}' as active", timeout=10) self.check_log(agent.radios[0], r"Autoconfiguration for ssid: Boardfarm-Tests-24G-3 .*" r"fronthaul: true backhaul: false") self.check_log(agent.radios[1], r".* tear down radio") conn_map = controller.get_conn_map() repeater1 = conn_map[agent.mac] repeater1_wlan0 = repeater1.radios[agent.radios[0].mac] for vap in repeater1_wlan0.vaps.values(): if vap.ssid not in ('Boardfarm-Tests-24G-3', 'N/A'): self.fail('Wrong SSID: {vap.ssid} instead of Boardfarm-Tests-24G-3'.format(vap=vap)) repeater1_wlan2 = repeater1.radios[agent.radios[1].mac] for vap in repeater1_wlan2.vaps.values(): if vap.ssid != 'N/A': self.fail('Wrong SSID: {vap.ssid} instead torn down'.format(vap=vap)) self.checkpoint() # SSIDs have been removed for the CTT Agent1's front radio controller.cmd_reply( "DEV_SET_CONFIG,bss_info1,{} 8x".format(agent.mac)) # Send renew message controller.dev_send_1905(agent.mac, self.ieee1905['eMessageType'] ['AP_AUTOCONFIGURATION_RENEW_MESSAGE'], tlv(self.ieee1905['eTlvType']['TLV_AL_MAC_ADDRESS'], "{" + controller.mac + "}"), tlv(self.ieee1905['eTlvType']['TLV_SUPPORTED_ROLE'], "{" + f"""0x{self.ieee1905['tlvSupportedRole'] ['eValue']['REGISTRAR']:02x}""" + "}"), tlv(self.ieee1905['eTlvType']['TLV_SUPPORTED_FREQ_BAND'], "{" + f"""0x{self.ieee1905['tlvSupportedFreqBand'] ['eValue']['BAND_2_4G']:02x}""" + "}")) self.check_log(controller, rf"Setting node '{agent.radios[0].mac}' as active", timeout=10) self.check_log(controller, rf"Setting node '{agent.radios[1].mac}' as active", timeout=10) self.check_log(agent.radios[0], r".* tear down radio") conn_map = controller.get_conn_map() repeater1 = conn_map[agent.mac] repeater1_wlan0 = repeater1.radios[agent.radios[0].mac] for vap in repeater1_wlan0.vaps.values(): if vap.ssid != 'N/A': self.fail('Wrong SSID: {vap.ssid} instead torn down'.format(vap=vap)) repeater1_wlan2 = repeater1.radios[agent.radios[1].mac] for vap in repeater1_wlan2.vaps.values(): if vap.ssid != 'N/A': self.fail('Wrong SSID: {vap.ssid} instead torn down'.format(vap=vap))
[ "capi.tlv", "boardfarm.exceptions.SkipTest" ]
[((1342, 1427), 'capi.tlv', 'tlv', (["self.ieee1905['eTlvType']['TLV_AL_MAC_ADDRESS']", "('{' + controller.mac + '}')"], {}), "(self.ieee1905['eTlvType']['TLV_AL_MAC_ADDRESS'], '{' + controller.mac + '}'\n )\n", (1345, 1427), False, 'from capi import tlv\n'), ((1494, 1631), 'capi.tlv', 'tlv', (["self.ieee1905['eTlvType']['TLV_SUPPORTED_ROLE']", '(\'{\' + f"0x{self.ieee1905[\'tlvSupportedRole\'][\'eValue\'][\'REGISTRAR\']:02x}" +\n \'}\')'], {}), '(self.ieee1905[\'eTlvType\'][\'TLV_SUPPORTED_ROLE\'], \'{\' +\n f"0x{self.ieee1905[\'tlvSupportedRole\'][\'eValue\'][\'REGISTRAR\']:02x}" + \'}\')\n', (1497, 1631), False, 'from capi import tlv\n'), ((1741, 1891), 'capi.tlv', 'tlv', (["self.ieee1905['eTlvType']['TLV_SUPPORTED_FREQ_BAND']", '(\'{\' +\n f"0x{self.ieee1905[\'tlvSupportedFreqBand\'][\'eValue\'][\'BAND_2_4G\']:02x}" +\n \'}\')'], {}), '(self.ieee1905[\'eTlvType\'][\'TLV_SUPPORTED_FREQ_BAND\'], \'{\' +\n f"0x{self.ieee1905[\'tlvSupportedFreqBand\'][\'eValue\'][\'BAND_2_4G\']:02x}" +\n \'}\')\n', (1744, 1891), False, 'from capi import tlv\n'), ((3532, 3617), 'capi.tlv', 'tlv', (["self.ieee1905['eTlvType']['TLV_AL_MAC_ADDRESS']", "('{' + controller.mac + '}')"], {}), "(self.ieee1905['eTlvType']['TLV_AL_MAC_ADDRESS'], '{' + controller.mac + '}'\n )\n", (3535, 3617), False, 'from capi import tlv\n'), ((3684, 3821), 'capi.tlv', 'tlv', (["self.ieee1905['eTlvType']['TLV_SUPPORTED_ROLE']", '(\'{\' + f"0x{self.ieee1905[\'tlvSupportedRole\'][\'eValue\'][\'REGISTRAR\']:02x}" +\n \'}\')'], {}), '(self.ieee1905[\'eTlvType\'][\'TLV_SUPPORTED_ROLE\'], \'{\' +\n f"0x{self.ieee1905[\'tlvSupportedRole\'][\'eValue\'][\'REGISTRAR\']:02x}" + \'}\')\n', (3687, 3821), False, 'from capi import tlv\n'), ((3931, 4081), 'capi.tlv', 'tlv', (["self.ieee1905['eTlvType']['TLV_SUPPORTED_FREQ_BAND']", '(\'{\' +\n f"0x{self.ieee1905[\'tlvSupportedFreqBand\'][\'eValue\'][\'BAND_2_4G\']:02x}" +\n \'}\')'], {}), '(self.ieee1905[\'eTlvType\'][\'TLV_SUPPORTED_FREQ_BAND\'], \'{\' +\n f"0x{self.ieee1905[\'tlvSupportedFreqBand\'][\'eValue\'][\'BAND_2_4G\']:02x}" +\n \'}\')\n', (3934, 4081), False, 'from capi import tlv\n'), ((778, 790), 'boardfarm.exceptions.SkipTest', 'SkipTest', (['ae'], {}), '(ae)\n', (786, 790), False, 'from boardfarm.exceptions import SkipTest\n')]
import cv2 import pickle import numpy as np from flag import Flag flag = Flag() with open('assets/colors.h5', 'rb') as f: colors = pickle.loads(f.read()) with open('label.txt', 'r') as f: classes = f.readlines() def detector(image, label): image = np.asarray(image * 255., np.uint8) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) indices = np.squeeze(np.max(np.max(label, axis=0, keepdims=True), axis=1, keepdims=True)) indices = np.where(indices > 0.5)[0] for i in indices: output = np.asarray(label[:, :, i], dtype=np.float) output[output > flag.threshold] = 255. output[output <= flag.threshold] = 0. output = np.asarray(output, dtype=np.uint8) kernel = np.ones((2, 2), np.float32) / 4 output = cv2.filter2D(output, -1, kernel) # cv2.imshow('out', cv2.resize(output, (256, 256))) # cv2.waitKey(0) _, contours, _ = cv2.findContours(output, cv2.RETR_LIST, cv2.CHAIN_APPROX_TC89_L1) for contour in contours: # print(contour) col_wise = contour[:, :, 0] row_wise = contour[:, :, 1] x1 = min(col_wise)[0] / flag.y_size * flag.x_size y1 = min(row_wise)[0] / flag.y_size * flag.x_size x2 = max(col_wise)[0] / flag.y_size * flag.x_size y2 = max(row_wise)[0] / flag.y_size * flag.x_size # print(x1, y1, x2, y2) c = colors[i] image = cv2.rectangle(image, (int(x1), int(y1)), (int(x2), int(y2)), (int(c[0]), int(c[1]), int(c[2])), 2) # print('class =', classes[i-1]) font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(image, classes[i - 1][:-1], (int(x1), int(y1)), font, .8, (int(c[0]), int(c[1]), int(c[2])), 2, cv2.LINE_AA) return image if __name__ == '__main__': flag = Flag() images = np.load('dataset/valid_x.npy') labels = np.load('dataset/valid_y.npy') # print(images.shape) image = images[100] label = labels[100] image = detector(image, label) cv2.imshow('image', image) cv2.waitKey(0)
[ "numpy.ones", "numpy.where", "numpy.asarray", "cv2.filter2D", "cv2.imshow", "numpy.max", "cv2.cvtColor", "cv2.findContours", "numpy.load", "cv2.waitKey", "flag.Flag" ]
[((74, 80), 'flag.Flag', 'Flag', ([], {}), '()\n', (78, 80), False, 'from flag import Flag\n'), ((264, 299), 'numpy.asarray', 'np.asarray', (['(image * 255.0)', 'np.uint8'], {}), '(image * 255.0, np.uint8)\n', (274, 299), True, 'import numpy as np\n'), ((311, 349), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2RGB'], {}), '(image, cv2.COLOR_BGR2RGB)\n', (323, 349), False, 'import cv2\n'), ((1865, 1871), 'flag.Flag', 'Flag', ([], {}), '()\n', (1869, 1871), False, 'from flag import Flag\n'), ((1885, 1915), 'numpy.load', 'np.load', (['"""dataset/valid_x.npy"""'], {}), "('dataset/valid_x.npy')\n", (1892, 1915), True, 'import numpy as np\n'), ((1929, 1959), 'numpy.load', 'np.load', (['"""dataset/valid_y.npy"""'], {}), "('dataset/valid_y.npy')\n", (1936, 1959), True, 'import numpy as np\n'), ((2073, 2099), 'cv2.imshow', 'cv2.imshow', (['"""image"""', 'image'], {}), "('image', image)\n", (2083, 2099), False, 'import cv2\n'), ((2104, 2118), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (2115, 2118), False, 'import cv2\n'), ((458, 481), 'numpy.where', 'np.where', (['(indices > 0.5)'], {}), '(indices > 0.5)\n', (466, 481), True, 'import numpy as np\n'), ((525, 567), 'numpy.asarray', 'np.asarray', (['label[:, :, i]'], {'dtype': 'np.float'}), '(label[:, :, i], dtype=np.float)\n', (535, 567), True, 'import numpy as np\n'), ((678, 712), 'numpy.asarray', 'np.asarray', (['output'], {'dtype': 'np.uint8'}), '(output, dtype=np.uint8)\n', (688, 712), True, 'import numpy as np\n'), ((779, 811), 'cv2.filter2D', 'cv2.filter2D', (['output', '(-1)', 'kernel'], {}), '(output, -1, kernel)\n', (791, 811), False, 'import cv2\n'), ((922, 987), 'cv2.findContours', 'cv2.findContours', (['output', 'cv2.RETR_LIST', 'cv2.CHAIN_APPROX_TC89_L1'], {}), '(output, cv2.RETR_LIST, cv2.CHAIN_APPROX_TC89_L1)\n', (938, 987), False, 'import cv2\n'), ((382, 418), 'numpy.max', 'np.max', (['label'], {'axis': '(0)', 'keepdims': '(True)'}), '(label, axis=0, keepdims=True)\n', (388, 418), True, 'import numpy as np\n'), ((730, 757), 'numpy.ones', 'np.ones', (['(2, 2)', 'np.float32'], {}), '((2, 2), np.float32)\n', (737, 757), True, 'import numpy as np\n')]
import retrieve import validation from time_functions import time_delay from selenium.webdriver import ActionChains def like_pic(browser): heart = retrieve.like_button(browser) time_delay() if validation.already_liked(heart): heart.click() def like_pic_in_feed(browser, number = 1): loop = 1 while loop <= number: hearts = retrieve.feed_like_buttons(browser) for h in range(len(hearts)): #print('liking the pic {}'.format(str(self.loop + 1))) time_delay() if validation.already_liked(hearts[h]): actions = ActionChains(browser) actions.move_to_element(hearts[h]) actions.click(hearts[h]) actions.perform() loop = loop + 1 if loop > number: break
[ "time_functions.time_delay", "retrieve.like_button", "validation.already_liked", "retrieve.feed_like_buttons", "selenium.webdriver.ActionChains" ]
[((153, 182), 'retrieve.like_button', 'retrieve.like_button', (['browser'], {}), '(browser)\n', (173, 182), False, 'import retrieve\n'), ((187, 199), 'time_functions.time_delay', 'time_delay', ([], {}), '()\n', (197, 199), False, 'from time_functions import time_delay\n'), ((207, 238), 'validation.already_liked', 'validation.already_liked', (['heart'], {}), '(heart)\n', (231, 238), False, 'import validation\n'), ((353, 388), 'retrieve.feed_like_buttons', 'retrieve.feed_like_buttons', (['browser'], {}), '(browser)\n', (379, 388), False, 'import retrieve\n'), ((490, 502), 'time_functions.time_delay', 'time_delay', ([], {}), '()\n', (500, 502), False, 'from time_functions import time_delay\n'), ((512, 547), 'validation.already_liked', 'validation.already_liked', (['hearts[h]'], {}), '(hearts[h])\n', (536, 547), False, 'import validation\n'), ((567, 588), 'selenium.webdriver.ActionChains', 'ActionChains', (['browser'], {}), '(browser)\n', (579, 588), False, 'from selenium.webdriver import ActionChains\n')]
from context import ascii_magic try: output = ascii_magic.from_url('https://wow.zamimg.com/uploads/blog/images/20516-afterlives-ardenweald-4k-desktop-wallpapers.jpg') ascii_magic.to_terminal(output) except OSError as e: print(f'Could not load the image, server said: {e.code} {e.msg}')
[ "context.ascii_magic.to_terminal", "context.ascii_magic.from_url" ]
[((48, 178), 'context.ascii_magic.from_url', 'ascii_magic.from_url', (['"""https://wow.zamimg.com/uploads/blog/images/20516-afterlives-ardenweald-4k-desktop-wallpapers.jpg"""'], {}), "(\n 'https://wow.zamimg.com/uploads/blog/images/20516-afterlives-ardenweald-4k-desktop-wallpapers.jpg'\n )\n", (68, 178), False, 'from context import ascii_magic\n'), ((170, 201), 'context.ascii_magic.to_terminal', 'ascii_magic.to_terminal', (['output'], {}), '(output)\n', (193, 201), False, 'from context import ascii_magic\n')]
#!/usr/bin/env python3 """ Apple EFI Package Apple EFI Package Extractor Copyright (C) 2019-2021 <NAME> """ print('Apple EFI Package Extractor v2.0_Linux_a1') import os import sys import zlib import shutil import subprocess if len(sys.argv) >= 2 : pkg = sys.argv[1:] else : pkg = [] in_path = input('\nEnter the full folder path: ') print('\nWorking...') for root, dirs, files in os.walk(in_path): for name in files : pkg.append(os.path.join(root, name)) final_path = os.path.join(os.getcwd(), 'AppleEFI') if os.path.exists(final_path) : shutil.rmtree(final_path) for input_file in pkg : file_path = os.path.abspath(input_file) file_name = os.path.basename(input_file) file_dir = os.path.dirname(file_path) file_ext = os.path.splitext(file_path)[1] print('\nFile: %s\n' % file_name) with open(input_file, 'rb') as in_buff : file_adler = zlib.adler32(in_buff.read()) & 0xFFFFFFFF pkg_payload = os.path.join(final_path, '%s_%0.8X' % (file_name, file_adler)) pkg_temp = os.path.join(final_path, '__TEMP_%s_%0.8X' % (file_name, file_adler)) os.makedirs(pkg_temp) subprocess.run(['bsdtar', '-xf', file_path, '-C', pkg_temp], check = True) #subprocess.run(['7z', 'x', '-aou', '-bso0', '-bse0', '-bsp0', '-o' + pkg_temp, file_path]) if os.path.isfile(os.path.join(pkg_temp, 'Scripts')) : scripts_init = os.path.join(pkg_temp, 'Scripts') scripts_cpgz = os.path.join(pkg_temp, 'Scripts.gz') efi_path = os.path.join(pkg_temp, 'Tools', 'EFIPayloads', '') os.replace(scripts_init, scripts_cpgz) os.system('gunzip -k -q %s' % scripts_cpgz) os.system('(cd %s && cpio --quiet -id < %s)' % (pkg_temp, scripts_init)) shutil.copytree(efi_path, pkg_payload) elif os.path.isfile(os.path.join(pkg_temp, 'Payload')) : payload_init = os.path.join(pkg_temp, 'Payload') payload_pbzx = os.path.join(pkg_temp, 'Payload.pbzx') payload_cpio = os.path.join(pkg_temp, 'Payload.cpio') zip_path = os.path.join(pkg_temp, 'usr', 'standalone', 'firmware', 'bridgeOSCustomer.bundle', 'Contents', 'Resources', 'UpdateBundle') efi_path = os.path.join(zip_path, 'boot', 'Firmware', 'MacEFI', '') os.replace(payload_init, payload_pbzx) subprocess.run(['python', 'parse_pbzx_fix.py', payload_pbzx, payload_cpio], check = True, stdout=subprocess.DEVNULL) os.system('(cd %s && cpio --quiet -id < %s)' % (pkg_temp, payload_cpio)) shutil.unpack_archive(zip_path + '.zip', zip_path) if os.path.exists(efi_path) : shutil.copytree(efi_path, pkg_payload) shutil.rmtree(pkg_temp) im4p_files = [] for root, dirs, files in os.walk(pkg_payload): for name in files : if name.endswith('.im4p') : im4p_files.append(os.path.join(root, name)) if im4p_files : subprocess.run(['python', 'Apple_EFI_Split.py', '-skip', *im4p_files], check = True, stdout=subprocess.DEVNULL) for im4p in im4p_files : os.remove(im4p) final_files = [] for root, dirs, files in os.walk(pkg_payload): for name in files : final_files.append(os.path.join(root, name)) if final_files : subprocess.run(['python', 'Apple_EFI_Rename.py', '-skip', *final_files], check = True, stdout=subprocess.DEVNULL) for root, dirs, files in os.walk(pkg_payload): for name in files : if not os.path.isfile(os.path.join(final_path, name)) : shutil.copy2(os.path.join(root, name), os.path.join(final_path, name)) shutil.rmtree(pkg_payload) print('\nDone!')
[ "os.path.exists", "os.makedirs", "subprocess.run", "os.path.join", "os.path.splitext", "os.getcwd", "os.replace", "os.path.dirname", "shutil.copytree", "os.path.basename", "shutil.rmtree", "os.path.abspath", "os.system", "shutil.unpack_archive", "os.walk", "os.remove" ]
[((527, 553), 'os.path.exists', 'os.path.exists', (['final_path'], {}), '(final_path)\n', (541, 553), False, 'import os\n'), ((389, 405), 'os.walk', 'os.walk', (['in_path'], {}), '(in_path)\n', (396, 405), False, 'import os\n'), ((499, 510), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (508, 510), False, 'import os\n'), ((556, 581), 'shutil.rmtree', 'shutil.rmtree', (['final_path'], {}), '(final_path)\n', (569, 581), False, 'import shutil\n'), ((623, 650), 'os.path.abspath', 'os.path.abspath', (['input_file'], {}), '(input_file)\n', (638, 650), False, 'import os\n'), ((664, 692), 'os.path.basename', 'os.path.basename', (['input_file'], {}), '(input_file)\n', (680, 692), False, 'import os\n'), ((705, 731), 'os.path.dirname', 'os.path.dirname', (['file_path'], {}), '(file_path)\n', (720, 731), False, 'import os\n'), ((928, 990), 'os.path.join', 'os.path.join', (['final_path', "('%s_%0.8X' % (file_name, file_adler))"], {}), "(final_path, '%s_%0.8X' % (file_name, file_adler))\n", (940, 990), False, 'import os\n'), ((1003, 1072), 'os.path.join', 'os.path.join', (['final_path', "('__TEMP_%s_%0.8X' % (file_name, file_adler))"], {}), "(final_path, '__TEMP_%s_%0.8X' % (file_name, file_adler))\n", (1015, 1072), False, 'import os\n'), ((1074, 1095), 'os.makedirs', 'os.makedirs', (['pkg_temp'], {}), '(pkg_temp)\n', (1085, 1095), False, 'import os\n'), ((1099, 1171), 'subprocess.run', 'subprocess.run', (["['bsdtar', '-xf', file_path, '-C', pkg_temp]"], {'check': '(True)'}), "(['bsdtar', '-xf', file_path, '-C', pkg_temp], check=True)\n", (1113, 1171), False, 'import subprocess\n'), ((2545, 2568), 'shutil.rmtree', 'shutil.rmtree', (['pkg_temp'], {}), '(pkg_temp)\n', (2558, 2568), False, 'import shutil\n'), ((2614, 2634), 'os.walk', 'os.walk', (['pkg_payload'], {}), '(pkg_payload)\n', (2621, 2634), False, 'import os\n'), ((2956, 2976), 'os.walk', 'os.walk', (['pkg_payload'], {}), '(pkg_payload)\n', (2963, 2976), False, 'import os\n'), ((3210, 3230), 'os.walk', 'os.walk', (['pkg_payload'], {}), '(pkg_payload)\n', (3217, 3230), False, 'import os\n'), ((3393, 3419), 'shutil.rmtree', 'shutil.rmtree', (['pkg_payload'], {}), '(pkg_payload)\n', (3406, 3419), False, 'import shutil\n'), ((744, 771), 'os.path.splitext', 'os.path.splitext', (['file_path'], {}), '(file_path)\n', (760, 771), False, 'import os\n'), ((1291, 1324), 'os.path.join', 'os.path.join', (['pkg_temp', '"""Scripts"""'], {}), "(pkg_temp, 'Scripts')\n", (1303, 1324), False, 'import os\n'), ((1345, 1378), 'os.path.join', 'os.path.join', (['pkg_temp', '"""Scripts"""'], {}), "(pkg_temp, 'Scripts')\n", (1357, 1378), False, 'import os\n'), ((1396, 1432), 'os.path.join', 'os.path.join', (['pkg_temp', '"""Scripts.gz"""'], {}), "(pkg_temp, 'Scripts.gz')\n", (1408, 1432), False, 'import os\n'), ((1446, 1496), 'os.path.join', 'os.path.join', (['pkg_temp', '"""Tools"""', '"""EFIPayloads"""', '""""""'], {}), "(pkg_temp, 'Tools', 'EFIPayloads', '')\n", (1458, 1496), False, 'import os\n'), ((1502, 1540), 'os.replace', 'os.replace', (['scripts_init', 'scripts_cpgz'], {}), '(scripts_init, scripts_cpgz)\n', (1512, 1540), False, 'import os\n'), ((1552, 1595), 'os.system', 'os.system', (["('gunzip -k -q %s' % scripts_cpgz)"], {}), "('gunzip -k -q %s' % scripts_cpgz)\n", (1561, 1595), False, 'import os\n'), ((1607, 1679), 'os.system', 'os.system', (["('(cd %s && cpio --quiet -id < %s)' % (pkg_temp, scripts_init))"], {}), "('(cd %s && cpio --quiet -id < %s)' % (pkg_temp, scripts_init))\n", (1616, 1679), False, 'import os\n'), ((1685, 1723), 'shutil.copytree', 'shutil.copytree', (['efi_path', 'pkg_payload'], {}), '(efi_path, pkg_payload)\n', (1700, 1723), False, 'import shutil\n'), ((2756, 2869), 'subprocess.run', 'subprocess.run', (["['python', 'Apple_EFI_Split.py', '-skip', *im4p_files]"], {'check': '(True)', 'stdout': 'subprocess.DEVNULL'}), "(['python', 'Apple_EFI_Split.py', '-skip', *im4p_files],\n check=True, stdout=subprocess.DEVNULL)\n", (2770, 2869), False, 'import subprocess\n'), ((2894, 2909), 'os.remove', 'os.remove', (['im4p'], {}), '(im4p)\n', (2903, 2909), False, 'import os\n'), ((3068, 3183), 'subprocess.run', 'subprocess.run', (["['python', 'Apple_EFI_Rename.py', '-skip', *final_files]"], {'check': '(True)', 'stdout': 'subprocess.DEVNULL'}), "(['python', 'Apple_EFI_Rename.py', '-skip', *final_files],\n check=True, stdout=subprocess.DEVNULL)\n", (3082, 3183), False, 'import subprocess\n'), ((1748, 1781), 'os.path.join', 'os.path.join', (['pkg_temp', '"""Payload"""'], {}), "(pkg_temp, 'Payload')\n", (1760, 1781), False, 'import os\n'), ((1802, 1835), 'os.path.join', 'os.path.join', (['pkg_temp', '"""Payload"""'], {}), "(pkg_temp, 'Payload')\n", (1814, 1835), False, 'import os\n'), ((1853, 1891), 'os.path.join', 'os.path.join', (['pkg_temp', '"""Payload.pbzx"""'], {}), "(pkg_temp, 'Payload.pbzx')\n", (1865, 1891), False, 'import os\n'), ((1909, 1947), 'os.path.join', 'os.path.join', (['pkg_temp', '"""Payload.cpio"""'], {}), "(pkg_temp, 'Payload.cpio')\n", (1921, 1947), False, 'import os\n'), ((1961, 2088), 'os.path.join', 'os.path.join', (['pkg_temp', '"""usr"""', '"""standalone"""', '"""firmware"""', '"""bridgeOSCustomer.bundle"""', '"""Contents"""', '"""Resources"""', '"""UpdateBundle"""'], {}), "(pkg_temp, 'usr', 'standalone', 'firmware',\n 'bridgeOSCustomer.bundle', 'Contents', 'Resources', 'UpdateBundle')\n", (1973, 2088), False, 'import os\n'), ((2098, 2154), 'os.path.join', 'os.path.join', (['zip_path', '"""boot"""', '"""Firmware"""', '"""MacEFI"""', '""""""'], {}), "(zip_path, 'boot', 'Firmware', 'MacEFI', '')\n", (2110, 2154), False, 'import os\n'), ((2160, 2198), 'os.replace', 'os.replace', (['payload_init', 'payload_pbzx'], {}), '(payload_init, payload_pbzx)\n', (2170, 2198), False, 'import os\n'), ((2204, 2322), 'subprocess.run', 'subprocess.run', (["['python', 'parse_pbzx_fix.py', payload_pbzx, payload_cpio]"], {'check': '(True)', 'stdout': 'subprocess.DEVNULL'}), "(['python', 'parse_pbzx_fix.py', payload_pbzx, payload_cpio],\n check=True, stdout=subprocess.DEVNULL)\n", (2218, 2322), False, 'import subprocess\n'), ((2332, 2404), 'os.system', 'os.system', (["('(cd %s && cpio --quiet -id < %s)' % (pkg_temp, payload_cpio))"], {}), "('(cd %s && cpio --quiet -id < %s)' % (pkg_temp, payload_cpio))\n", (2341, 2404), False, 'import os\n'), ((2416, 2466), 'shutil.unpack_archive', 'shutil.unpack_archive', (["(zip_path + '.zip')", 'zip_path'], {}), "(zip_path + '.zip', zip_path)\n", (2437, 2466), False, 'import shutil\n'), ((2475, 2499), 'os.path.exists', 'os.path.exists', (['efi_path'], {}), '(efi_path)\n', (2489, 2499), False, 'import os\n'), ((443, 467), 'os.path.join', 'os.path.join', (['root', 'name'], {}), '(root, name)\n', (455, 467), False, 'import os\n'), ((2502, 2540), 'shutil.copytree', 'shutil.copytree', (['efi_path', 'pkg_payload'], {}), '(efi_path, pkg_payload)\n', (2517, 2540), False, 'import shutil\n'), ((3022, 3046), 'os.path.join', 'os.path.join', (['root', 'name'], {}), '(root, name)\n', (3034, 3046), False, 'import os\n'), ((2711, 2735), 'os.path.join', 'os.path.join', (['root', 'name'], {}), '(root, name)\n', (2723, 2735), False, 'import os\n'), ((3279, 3309), 'os.path.join', 'os.path.join', (['final_path', 'name'], {}), '(final_path, name)\n', (3291, 3309), False, 'import os\n'), ((3330, 3354), 'os.path.join', 'os.path.join', (['root', 'name'], {}), '(root, name)\n', (3342, 3354), False, 'import os\n'), ((3356, 3386), 'os.path.join', 'os.path.join', (['final_path', 'name'], {}), '(final_path, name)\n', (3368, 3386), False, 'import os\n')]
# -*- coding: utf-8 -*- # This program 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. # # This program 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 this program. If not, see <http://www.gnu.org/licenses/>. import subprocess from helper import rename_font import os import shutil from os import path as p here = p.dirname(p.abspath(__file__)) repos = p.dirname(here) sourcecodepro = p.join(here, 'Fonts', 'SourceCodePro') remove = ( u'∕', # ---- Bad dashes: ---- # [\u00AD \u1806 \uFE63 \uFF0D] u'­', u'᠆', u'﹣', u'-', # ---- OK dashes: ---- # [u2E3A \u2E3B] (multiple of character width) # u'⸺', u'⸻', ) spaces = ( # ---- OK whitespaces: ---- # [\u202F] # u' ', # ---- Bad whitespaces (dont't touch): ---- # [\u1680] # u' ', # ---- Bad whitespaces: ---- # [\u205F \u3000] u' ', u' ', # ---- Bad whitespaces: ---- # [\u2000 \u2001 \u2002 \u2003 \u2004 \u2005 \u2006 \u2009 \u200A] u' ', u' ', u' ', u' ', u' ', u' ', u' ', u' ', u' ', ) dir_ = p.join(repos, '_SourcingCodePro') if not p.exists(dir_): os.makedirs(dir_) # Rename Source Code Pro: # --------------------------------- styles = [ ('SourceCodePro-It', 'Source Code Pro', 'Italic'), ('SourceCodePro-MediumIt', 'Source Code Pro Medium', 'Italic'), ('SourceCodePro-SemiboldIt', 'Source Code Pro Semibold', 'Italic'), ('SourceCodePro-BoldIt', 'Source Code Pro', 'Bold Italic'), ('SourceCodePro-BlackIt', 'Source Code Pro Black', 'Italic'), ('SourceCodePro-LightIt', 'Source Code Pro Light', 'Italic'), ('SourceCodePro-ExtraLightIt', 'Source Code Pro ExtraLight', 'Italic'), ('SourceCodePro-Regular', 'Source Code Pro', 'Regular'), ('SourceCodePro-Medium', 'Source Code Pro Medium', 'Regular'), ('SourceCodePro-Semibold', 'Source Code Pro Semibold', 'Regular'), ('SourceCodePro-Bold', 'Source Code Pro', 'Bold'), ('SourceCodePro-Black', 'Source Code Pro Black', 'Regular'), ('SourceCodePro-Light', 'Source Code Pro Light', 'Regular'), ('SourceCodePro-ExtraLight', 'Source Code Pro ExtraLight', 'Regular'), ] shutil.copy(p.join(sourcecodepro, 'LICENSE.txt'), p.join(dir_, 'LICENSE.txt')) reps = (('Source is a trademark', 'xxyyzz'), ('Source Code Pro', 'Sourcing Code Pro'), ('SourceCodePro', 'SourcingCodePro'), ('xxyyzz', 'Source is a trademark')) def rep(s): return s.replace('Source', 'Sourcing') for fn, ff, style in styles: clean_up = False ref = p.join(sourcecodepro, fn + '.ttf') of = ref # Old Font rename_font(input=of, save_as=p.join(dir_, rep(fn).replace('It', 'Italic') +'.ttf'), fontname=rep(fn), # Font Name familyname=rep(ff), # Font Family fullname=rep(ff) + ((' ' + style) if style != 'Regular' else ''), reps=reps, sfnt_ref=ref, clean_up=clean_up, mono=True, remove=remove, spaces=spaces)
[ "os.path.exists", "os.makedirs", "os.path.join", "os.path.dirname", "os.path.abspath" ]
[((804, 819), 'os.path.dirname', 'p.dirname', (['here'], {}), '(here)\n', (813, 819), True, 'from os import path as p\n'), ((836, 874), 'os.path.join', 'p.join', (['here', '"""Fonts"""', '"""SourceCodePro"""'], {}), "(here, 'Fonts', 'SourceCodePro')\n", (842, 874), True, 'from os import path as p\n'), ((1476, 1509), 'os.path.join', 'p.join', (['repos', '"""_SourcingCodePro"""'], {}), "(repos, '_SourcingCodePro')\n", (1482, 1509), True, 'from os import path as p\n'), ((775, 794), 'os.path.abspath', 'p.abspath', (['__file__'], {}), '(__file__)\n', (784, 794), True, 'from os import path as p\n'), ((1517, 1531), 'os.path.exists', 'p.exists', (['dir_'], {}), '(dir_)\n', (1525, 1531), True, 'from os import path as p\n'), ((1537, 1554), 'os.makedirs', 'os.makedirs', (['dir_'], {}), '(dir_)\n', (1548, 1554), False, 'import os\n'), ((2570, 2606), 'os.path.join', 'p.join', (['sourcecodepro', '"""LICENSE.txt"""'], {}), "(sourcecodepro, 'LICENSE.txt')\n", (2576, 2606), True, 'from os import path as p\n'), ((2608, 2635), 'os.path.join', 'p.join', (['dir_', '"""LICENSE.txt"""'], {}), "(dir_, 'LICENSE.txt')\n", (2614, 2635), True, 'from os import path as p\n'), ((2913, 2947), 'os.path.join', 'p.join', (['sourcecodepro', "(fn + '.ttf')"], {}), "(sourcecodepro, fn + '.ttf')\n", (2919, 2947), True, 'from os import path as p\n')]
# script for daily update from bs4 import BeautifulSoup # from urllib.request import urlopen import requests import csv import time from datetime import datetime, timedelta import os from pathlib import Path from dashboard.models import Case, Country, District, State, Zone def run(): scrapeStateStats() def scrapeCountryStats(): # scrape country level country_url = "http://covid-19.livephotos123.com/en" # page = urlopen(url) # html = page.read().decode("utf-8") # soup = BeautifulSoup(html, "html.parser") country_page = requests.get(country_url) country_soup = BeautifulSoup(country_page.content, "html.parser") # print(soup.prettify()) # subtitle = soup.find_all('span', class_='sub-title') # print(soup.find_all('div', class_='col-xs-12 col-md-6 text-center')) # get country level covid information section = country_soup.find('div', class_='col-xs-12 col-md-6 text-center') types = section.find_all('div') # print(types) all_info = {} for t in types: info = t.find_all('span') # print(info) if info: # get type key = info[0].get_text() cases_num = [] for i in range(1, len(info)): #get changes cases_num.append(info[i].get_text()) # todo : use pandas and save to csv file all_info[key] = cases_num print(all_info) def scrapeStateStats(): BASE_DIR = Path(__file__).resolve(strict=True).parent.parent.parent name_path = os.path.join( BASE_DIR, 'data/state_name.csv') s_path = os.path.join( BASE_DIR, 'data/state_fb.csv') c_path = os.path.join(BASE_DIR, 'data/state_stats_scrapped.csv') updated = False with open(s_path, "r") as f: reader = list(csv.reader(f)) today = time.strftime('%d/%m/%Y') if reader[len(reader)-1][0] == today: print("Updated state_fb.csv as of " + reader[len(reader)-1][0]) updated = True state_stats_updated = False with open(c_path, "r") as fs: reader_fs = list(csv.reader(fs)) today = time.strftime('%d/%m/%Y') if reader_fs[len(reader_fs)-1][0] == today: print("Updated state_stats_scrapped.csv as of " + reader_fs[len(reader_fs)-1][0]) state_stats_updated = True if not updated: # get state info with open(name_path, "r") as state_name: reader = csv.reader(state_name) next(reader) # skip first row for row in reader: print(row) # get state cases case_type = ["Active_14", "In treatment", "Deaths"] state_url = "https://newslab.malaysiakini.com/covid-19/en/state/" + row[0] state_page = requests.get(state_url) state_soup = BeautifulSoup(state_page.content, "html.parser") date_soup = state_soup.find('div', class_="jsx-3636536621 uk-text-large") d = date_soup.get_text().strip("As of ").strip(" PM").strip(" AM") latest_date = datetime.strptime(d, '%b %d, %Y %H:%M') date_updated = latest_date.strftime('%d/%m/%Y') state_info = {} infected = state_soup.find("div", class_="jsx-3636536621 uk-text-center uk-text-large") state_info['Infected'] = int(infected.find("strong", class_= "jsx-3636536621" ).get_text().replace(",", "")) stats = state_soup.find('ul', class_="jsx-3636536621 uk-grid uk-grid-divider uk-grid-small uk-flex-center uk-child-width-1-2 uk-child-width-1-3@s uk-child-width-1-4@m uk-child-width-1-5@l uk-margin") # get info stats = stats.find_all('span', class_= "jsx-3636536621 uk-heading-medium") for i in range(0, len(case_type)): state_info[case_type[i]] = int(stats[i].get_text().replace(",", "")) state_info["Recovered"] = state_info.get("Infected") - state_info.get("In treatment") - state_info.get("Deaths") print(state_info) with open(s_path, "a+") as state_stats: csv_w = csv.writer(state_stats) csv_w = csv_w.writerow([date_updated, row[0], state_info.get("Infected"), state_info.get("Recovered"), state_info.get("Deaths"), state_info.get("In treatment")]) state = State.objects.get(State_Name=row[0]) date = latest_date.strftime('%Y-%m-%d') yesterday = latest_date - timedelta(1) try: case = Case.objects.get(Ref_Key=2, Reference_ID = state.State_ID, Date=yesterday) except Case.DoesNotExist: case = None if not case: state_case, created = Case.objects.get_or_create(Reference_ID = state.State_ID, Date=date, Is_actual=True, defaults = { 'Ref_Key': 2, 'Total_infected' : state_info.get("Infected"), 'Total_deaths': state_info.get("Deaths"),'Total_recoveries': state_info.get("Recovered"), 'Active_cases': state_info.get("In treatment")}) else: state_case, created = Case.objects.get_or_create(Reference_ID = state.State_ID, Date=date, Is_actual=True, defaults = { 'Ref_Key': 2, 'Total_infected' : state_info.get("Infected"), 'Total_deaths': state_info.get("Deaths"),'Total_recoveries': state_info.get("Recovered"), 'Active_cases': state_info.get("In treatment"), 'Daily_infected': state_info.get("Infected") - case.Total_infected if int(state_info.get("Infected")) - case.Total_infected > 0 else 0, 'Daily_deaths' : state_info.get("Deaths") - case.Total_deaths if state_info.get("Deaths") - case.Total_deaths > 0 else 0}) if not created: state_case.Total_infected = state_info.get("Infected") state_case.Total_deaths = state_info.get("Deaths") state_case.Total_recoveries = state_info.get("Recovered") state_case.Active_cases = state_info.get("In treatment") if case: state_case.Daily_deaths = state_info.get("Deaths") - case.Total_deaths if state_info.get("Deaths") - case.Total_deaths > 0 else 0 state_case.Daily_infected = state_info.get("Infected") - case.Total_infected if state_info.get("Infected") - case.Total_infected > 0 else 0 state_case.save() if state_case.Active_cases == 0: zone_colour = "1" elif state_case.Active_cases > 40: zone_colour = "3" else: zone_colour = "2" zone = Zone(Ref_Key=1, Reference_ID=state.State_ID, Date=state_case.Date, Zone_colour=zone_colour) zone.save() if not state_stats_updated: date = latest_date.strftime('%d/%m/%Y') with open(c_path, "a+") as state_stats: csv_w = csv.writer(state_stats) csv_w = csv_w.writerow([date, row[0], state_info.get("Infected"), state_info.get("Recovered"), state_info.get("Deaths"), state_info.get("In treatment")])
[ "dashboard.models.Case.objects.get", "pathlib.Path", "datetime.datetime.strptime", "time.strftime", "os.path.join", "csv.writer", "requests.get", "bs4.BeautifulSoup", "dashboard.models.State.objects.get", "dashboard.models.Zone", "datetime.timedelta", "csv.reader" ]
[((536, 561), 'requests.get', 'requests.get', (['country_url'], {}), '(country_url)\n', (548, 561), False, 'import requests\n'), ((578, 628), 'bs4.BeautifulSoup', 'BeautifulSoup', (['country_page.content', '"""html.parser"""'], {}), "(country_page.content, 'html.parser')\n", (591, 628), False, 'from bs4 import BeautifulSoup\n'), ((1392, 1437), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""data/state_name.csv"""'], {}), "(BASE_DIR, 'data/state_name.csv')\n", (1404, 1437), False, 'import os\n'), ((1449, 1492), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""data/state_fb.csv"""'], {}), "(BASE_DIR, 'data/state_fb.csv')\n", (1461, 1492), False, 'import os\n'), ((1504, 1559), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""data/state_stats_scrapped.csv"""'], {}), "(BASE_DIR, 'data/state_stats_scrapped.csv')\n", (1516, 1559), False, 'import os\n'), ((1649, 1674), 'time.strftime', 'time.strftime', (['"""%d/%m/%Y"""'], {}), "('%d/%m/%Y')\n", (1662, 1674), False, 'import time\n'), ((1910, 1935), 'time.strftime', 'time.strftime', (['"""%d/%m/%Y"""'], {}), "('%d/%m/%Y')\n", (1923, 1935), False, 'import time\n'), ((1624, 1637), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (1634, 1637), False, 'import csv\n'), ((1883, 1897), 'csv.reader', 'csv.reader', (['fs'], {}), '(fs)\n', (1893, 1897), False, 'import csv\n'), ((2192, 2214), 'csv.reader', 'csv.reader', (['state_name'], {}), '(state_name)\n', (2202, 2214), False, 'import csv\n'), ((2459, 2482), 'requests.get', 'requests.get', (['state_url'], {}), '(state_url)\n', (2471, 2482), False, 'import requests\n'), ((2500, 2548), 'bs4.BeautifulSoup', 'BeautifulSoup', (['state_page.content', '"""html.parser"""'], {}), "(state_page.content, 'html.parser')\n", (2513, 2548), False, 'from bs4 import BeautifulSoup\n'), ((2716, 2755), 'datetime.datetime.strptime', 'datetime.strptime', (['d', '"""%b %d, %Y %H:%M"""'], {}), "(d, '%b %d, %Y %H:%M')\n", (2733, 2755), False, 'from datetime import datetime, timedelta\n'), ((3855, 3891), 'dashboard.models.State.objects.get', 'State.objects.get', ([], {'State_Name': 'row[0]'}), '(State_Name=row[0])\n', (3872, 3891), False, 'from dashboard.models import Case, Country, District, State, Zone\n'), ((5815, 5910), 'dashboard.models.Zone', 'Zone', ([], {'Ref_Key': '(1)', 'Reference_ID': 'state.State_ID', 'Date': 'state_case.Date', 'Zone_colour': 'zone_colour'}), '(Ref_Key=1, Reference_ID=state.State_ID, Date=state_case.Date,\n Zone_colour=zone_colour)\n', (5819, 5910), False, 'from dashboard.models import Case, Country, District, State, Zone\n'), ((3647, 3670), 'csv.writer', 'csv.writer', (['state_stats'], {}), '(state_stats)\n', (3657, 3670), False, 'import csv\n'), ((3966, 3978), 'datetime.timedelta', 'timedelta', (['(1)'], {}), '(1)\n', (3975, 3978), False, 'from datetime import datetime, timedelta\n'), ((4000, 4072), 'dashboard.models.Case.objects.get', 'Case.objects.get', ([], {'Ref_Key': '(2)', 'Reference_ID': 'state.State_ID', 'Date': 'yesterday'}), '(Ref_Key=2, Reference_ID=state.State_ID, Date=yesterday)\n', (4016, 4072), False, 'from dashboard.models import Case, Country, District, State, Zone\n'), ((1322, 1336), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (1326, 1336), False, 'from pathlib import Path\n'), ((6060, 6083), 'csv.writer', 'csv.writer', (['state_stats'], {}), '(state_stats)\n', (6070, 6083), False, 'import csv\n')]
from django.urls import path #from api.views import company_list, company_details, company_vacancies, vacancies_list, vacancy_detail from api.views import company_list, company_details urlpatterns = [ path('companies/', company_list), path('companies/<int:company_id>/', company_details), #path('companies/<int:company_id>/vacancies/', company_vacancies), #path('vacancies/', vacancies_list), #path('vacancies/<int:vacancy_id>', vacancy_detail) ]
[ "django.urls.path" ]
[((206, 238), 'django.urls.path', 'path', (['"""companies/"""', 'company_list'], {}), "('companies/', company_list)\n", (210, 238), False, 'from django.urls import path\n'), ((244, 296), 'django.urls.path', 'path', (['"""companies/<int:company_id>/"""', 'company_details'], {}), "('companies/<int:company_id>/', company_details)\n", (248, 296), False, 'from django.urls import path\n')]
from logging import getLogger from lottery_config import LotteryConfig from main import draw_lottery logger = getLogger() def test_draw_lottery(): for test_count in range(10000): draw_results = draw_lottery() logger.info(f'Test #{str(test_count).ljust(4)} Draw Results : {draw_results}') # check if return type is as in the requirement assert isinstance(draw_results, list) # check if properties is as in config assert len(draw_results) == LotteryConfig.DRAW_SIZE.value assert min(draw_results) >= LotteryConfig.BALL_MIN_NO.value assert max(draw_results) <= LotteryConfig.BALL_MAX_NO.value # check that the previous ball is always less than current ball previous_ball = LotteryConfig.BALL_MIN_NO.value - 1 for ball in draw_results: assert ball > previous_ball previous_ball = ball
[ "logging.getLogger", "main.draw_lottery" ]
[((112, 123), 'logging.getLogger', 'getLogger', ([], {}), '()\n', (121, 123), False, 'from logging import getLogger\n'), ((210, 224), 'main.draw_lottery', 'draw_lottery', ([], {}), '()\n', (222, 224), False, 'from main import draw_lottery\n')]
import requests import io import dask from bs4 import BeautifulSoup as BS import nltk import pandas import numpy as np def News(ticker): B = BS(requests.get(f"https://www.wsj.com/market-data/quotes/{ticker}", headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'}).content, features="html.parser") News = B.find('ul', {'id': "newsSummary_c"}) News = [a.getText() for a in News.find_all('a')] News = [nltk.word_tokenize(h) for h in News] return dask.dataframe.from_array(np.asarray(News)) api_key = '<KEY>' def daily(ticker, outputsize = 'compact'): csv = pandas.read_csv(io.StringIO(requests.get(f'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&&symbol={ticker}&apikey={api_key}&outputsize={outputsize}&datatype=csv').content.decode('utf-8'))) return csv def intraday_data(ticker, time='1min', outputsize = 'compact'): return pandas.read_csv(io.StringIO(requests.get(f'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={ticker}&interval={time}&apikey={api_key}&outputsize={outputsize}&datatype=csv').content.decode('utf-8'))) def tickers(): return pandas.read_csv("NYSE_TICKERS.csv").iloc[:,0]
[ "requests.get", "numpy.asarray", "nltk.word_tokenize", "pandas.read_csv" ]
[((504, 525), 'nltk.word_tokenize', 'nltk.word_tokenize', (['h'], {}), '(h)\n', (522, 525), False, 'import nltk\n'), ((578, 594), 'numpy.asarray', 'np.asarray', (['News'], {}), '(News)\n', (588, 594), True, 'import numpy as np\n'), ((150, 370), 'requests.get', 'requests.get', (['f"""https://www.wsj.com/market-data/quotes/{ticker}"""'], {'headers': "{'User-Agent':\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'\n }"}), "(f'https://www.wsj.com/market-data/quotes/{ticker}', headers={\n 'User-Agent':\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'\n })\n", (162, 370), False, 'import requests\n'), ((1247, 1282), 'pandas.read_csv', 'pandas.read_csv', (['"""NYSE_TICKERS.csv"""'], {}), "('NYSE_TICKERS.csv')\n", (1262, 1282), False, 'import pandas\n'), ((717, 884), 'requests.get', 'requests.get', (['f"""https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&&symbol={ticker}&apikey={api_key}&outputsize={outputsize}&datatype=csv"""'], {}), "(\n f'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&&symbol={ticker}&apikey={api_key}&outputsize={outputsize}&datatype=csv'\n )\n", (729, 884), False, 'import requests\n'), ((1026, 1202), 'requests.get', 'requests.get', (['f"""https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={ticker}&interval={time}&apikey={api_key}&outputsize={outputsize}&datatype=csv"""'], {}), "(\n f'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={ticker}&interval={time}&apikey={api_key}&outputsize={outputsize}&datatype=csv'\n )\n", (1038, 1202), False, 'import requests\n')]
from pytest import raises from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec def test_list_path_access(): assert glom(list(range(10)), Path(1)) == 1 def test_path(): _obj = object() target = {'a': {'b.b': [None, {_obj: [None, None, 'd']}]}} assert glom(target, Path('a', 'b.b', 1, _obj, -1)) == 'd' def test_empty_path_access(): target = {} assert glom(target, Path()) is target assert glom(target, (Path(), Path(), Path())) is target dup_dict = glom(target, {'target': Path(), 'target2': Path()}) dup_dict['target'] is target dup_dict['target2'] is target def test_path_t_roundtrip(): # check that T repr roundrips assert repr(T['a'].b.c()) == "T['a'].b.c()" assert repr(T[1:]) == "T[1:]" assert repr(T[::3, 1:, 1:2, :2:3]) == "T[::3, 1:, 1:2, :2:3]" # check that Path repr roundtrips assert repr(Path('a', 1, 'b.b', -1.0)) == "Path('a', 1, 'b.b', -1.0)" # check that Path repr roundtrips when it contains Ts assert repr(Path(T['a'].b, 'c', T['d'].e)) == "Path(T['a'].b, 'c', T['d'].e)" # check that T instances containing Path access revert to repring with Path assert repr(Path(T['a'].b, 'c', T['d'].e).path_t) == "Path(T['a'].b, 'c', T['d'].e)" # check that Paths containing only T objects reduce to a T (joining the T objects) assert repr(Path(T['a'].b, T.c())) == "T['a'].b.c()" # check that multiple nested paths reduce assert repr(Path(Path(Path('a')))) == "Path('a')" # check builtin repr assert repr(T[len]) == 'T[len]' assert repr(T.func(len, sum)) == 'T.func(len, sum)' def test_path_access_error_message(): # test fuzzy access with raises(GlomError) as exc_info: glom({}, 'a.b') assert ("PathAccessError: could not access 'a', part 0 of Path('a', 'b'), got error: KeyError" in exc_info.exconly()) ke = repr(KeyError('a')) # py3.7+ changed the keyerror repr assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', 'b'), 0)" # test multi-part Path with T, catchable as a KeyError with raises(KeyError) as exc_info: # don't actually use glom to copy your data structures please glom({'a': {'b': 'c'}}, Path('a', T.copy(), 'd')) assert ("PathAccessError: could not access 'd', part 3 of Path('a', T.copy(), 'd'), got error: KeyError" in exc_info.exconly()) ke = repr(KeyError('d')) # py3.7+ changed the keyerror repr assert repr(exc_info.value) == "PathAccessError(" + ke + ", Path('a', T.copy(), 'd'), 3)" # test AttributeError with raises(GlomError) as exc_info: glom({'a': {'b': 'c'}}, Path('a', T.b)) assert ("PathAccessError: could not access 'b', part 1 of Path('a', T.b), got error: AttributeError" in exc_info.exconly()) ae = repr(AttributeError("'dict' object has no attribute 'b'")) assert repr(exc_info.value) == "PathAccessError(" + ae + ", Path(\'a\', T.b), 1)" def test_t_picklability(): import pickle class TargetType(object): def __init__(self): self.attribute = lambda: None self.attribute.method = lambda: {'key': lambda x: x * 2} spec = T.attribute.method()['key'](x=5) rt_spec = pickle.loads(pickle.dumps(spec)) assert repr(spec) == repr(rt_spec) assert glom(TargetType(), spec) == 10 s_spec = S.attribute assert repr(s_spec) == repr(pickle.loads(pickle.dumps(s_spec))) def test_a_forbidden(): with raises(BadSpec): A() # cannot assign to function call with raises(BadSpec): glom(1, A) # cannot assign without destination def test_s_magic(): assert glom(None, S.test, scope={'test': 'value'}) == 'value' with raises(PathAccessError): glom(1, S.a) # ref to 'a' which doesn't exist in scope with raises(PathAccessError): glom(1, A.b.c) return def test_path_len(): assert len(Path()) == 0 assert len(Path('a', 'b', 'c')) == 3 assert len(Path.from_text('1.2.3.4')) == 4 assert len(Path(T)) == 0 assert len(Path(T.a.b.c)) == 3 assert len(Path(T.a()['b'].c.d)) == 5 def test_path_getitem(): path = Path(T.a.b.c) assert path[0] == Path(T.a) assert path[1] == Path(T.b) assert path[2] == Path(T.c) assert path[-1] == Path(T.c) assert path[-2] == Path(T.b) with raises(IndexError, match='Path index out of range'): path[4] with raises(IndexError, match='Path index out of range'): path[-14] return def test_path_slices(): path = Path(T.a.b, 1, 2, T(test='yes')) assert path[::] == path # positive indices assert path[3:] == Path(2, T(test='yes')) assert path[1:3] == Path(T.b, 1) assert path[:3] == Path(T.a.b, 1) # positive indices backwards assert path[2:1] == Path() # negative indices forward assert path[-1:] == Path(T(test='yes')) assert path[:-2] == Path(T.a.b, 1) assert path[-3:-1] == Path(1, 2) # negative indices backwards assert path[-1:-3] == Path() # slicing and stepping assert path[1::2] == Path(T.b, 2) def test_path_values(): path = Path(T.a.b, 1, 2, T(test='yes')) assert path.values() == ('a', 'b', 1, 2, ((), {'test': 'yes'})) assert Path().values() == () def test_path_items(): path = Path(T.a, 1, 2, T(test='yes')) assert path.items() == (('.', 'a'), ('P', 1), ('P', 2), ('(', ((), {'test': 'yes'}))) assert Path().items() == () def test_path_eq(): assert Path('a', 'b') == Path('a', 'b') assert Path('a') != Path('b') assert Path() != object() def test_path_eq_t(): assert Path(T.a.b) == T.a.b assert Path(T.a.b.c) != T.a.b def test_startswith(): ref = T.a.b[1] assert Path(ref).startswith(T) assert Path(ref).startswith(T.a.b) assert Path(ref).startswith(ref) assert Path(ref).startswith(ref.c) is False assert Path('a.b.c').startswith(Path()) assert Path('a.b.c').startswith('a.b.c') with raises(TypeError): assert Path('a.b.c').startswith(None) return def test_from_t_identity(): ref = Path(T.a.b) assert ref.from_t() == ref assert ref.from_t() is ref def test_t_dict_key(): target = {'a': 'A'} assert glom(target, {T['a']: 'a'}) == {'A': 'A'} def test_t_dunders(): with raises(AttributeError) as exc_info: T.__name__ assert 'use T.__("name__")' in str(exc_info.value) assert glom(1, T.__('class__')) is int
[ "glom.glom", "glom.T.a", "glom.A", "pickle.dumps", "glom.Path.from_text", "glom.T.__", "glom.T.func", "glom.Path", "glom.T.c", "pytest.raises", "glom.T", "glom.T.copy", "glom.T.attribute.method" ]
[((4219, 4232), 'glom.Path', 'Path', (['T.a.b.c'], {}), '(T.a.b.c)\n', (4223, 4232), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((6223, 6234), 'glom.Path', 'Path', (['T.a.b'], {}), '(T.a.b)\n', (6227, 6234), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((1734, 1751), 'pytest.raises', 'raises', (['GlomError'], {}), '(GlomError)\n', (1740, 1751), False, 'from pytest import raises\n'), ((1773, 1788), 'glom.glom', 'glom', (['{}', '"""a.b"""'], {}), "({}, 'a.b')\n", (1777, 1788), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((2141, 2157), 'pytest.raises', 'raises', (['KeyError'], {}), '(KeyError)\n', (2147, 2157), False, 'from pytest import raises\n'), ((2638, 2655), 'pytest.raises', 'raises', (['GlomError'], {}), '(GlomError)\n', (2644, 2655), False, 'from pytest import raises\n'), ((3301, 3319), 'pickle.dumps', 'pickle.dumps', (['spec'], {}), '(spec)\n', (3313, 3319), False, 'import pickle\n'), ((3532, 3547), 'pytest.raises', 'raises', (['BadSpec'], {}), '(BadSpec)\n', (3538, 3547), False, 'from pytest import raises\n'), ((3557, 3560), 'glom.A', 'A', ([], {}), '()\n', (3558, 3560), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((3604, 3619), 'pytest.raises', 'raises', (['BadSpec'], {}), '(BadSpec)\n', (3610, 3619), False, 'from pytest import raises\n'), ((3629, 3639), 'glom.glom', 'glom', (['(1)', 'A'], {}), '(1, A)\n', (3633, 3639), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((3710, 3753), 'glom.glom', 'glom', (['None', 'S.test'], {'scope': "{'test': 'value'}"}), "(None, S.test, scope={'test': 'value'})\n", (3714, 3753), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((3775, 3798), 'pytest.raises', 'raises', (['PathAccessError'], {}), '(PathAccessError)\n', (3781, 3798), False, 'from pytest import raises\n'), ((3808, 3820), 'glom.glom', 'glom', (['(1)', 'S.a'], {}), '(1, S.a)\n', (3812, 3820), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((3874, 3897), 'pytest.raises', 'raises', (['PathAccessError'], {}), '(PathAccessError)\n', (3880, 3897), False, 'from pytest import raises\n'), ((3907, 3921), 'glom.glom', 'glom', (['(1)', 'A.b.c'], {}), '(1, A.b.c)\n', (3911, 3921), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((4256, 4265), 'glom.Path', 'Path', (['T.a'], {}), '(T.a)\n', (4260, 4265), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((4288, 4297), 'glom.Path', 'Path', (['T.b'], {}), '(T.b)\n', (4292, 4297), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((4320, 4329), 'glom.Path', 'Path', (['T.c'], {}), '(T.c)\n', (4324, 4329), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((4353, 4362), 'glom.Path', 'Path', (['T.c'], {}), '(T.c)\n', (4357, 4362), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((4386, 4395), 'glom.Path', 'Path', (['T.b'], {}), '(T.b)\n', (4390, 4395), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((4406, 4457), 'pytest.raises', 'raises', (['IndexError'], {'match': '"""Path index out of range"""'}), "(IndexError, match='Path index out of range')\n", (4412, 4457), False, 'from pytest import raises\n'), ((4485, 4536), 'pytest.raises', 'raises', (['IndexError'], {'match': '"""Path index out of range"""'}), "(IndexError, match='Path index out of range')\n", (4491, 4536), False, 'from pytest import raises\n'), ((4622, 4635), 'glom.T', 'T', ([], {'test': '"""yes"""'}), "(test='yes')\n", (4623, 4635), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((4760, 4772), 'glom.Path', 'Path', (['T.b', '(1)'], {}), '(T.b, 1)\n', (4764, 4772), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((4796, 4810), 'glom.Path', 'Path', (['T.a.b', '(1)'], {}), '(T.a.b, 1)\n', (4800, 4810), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((4869, 4875), 'glom.Path', 'Path', ([], {}), '()\n', (4873, 4875), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((4976, 4990), 'glom.Path', 'Path', (['T.a.b', '(1)'], {}), '(T.a.b, 1)\n', (4980, 4990), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((5017, 5027), 'glom.Path', 'Path', (['(1)', '(2)'], {}), '(1, 2)\n', (5021, 5027), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((5088, 5094), 'glom.Path', 'Path', ([], {}), '()\n', (5092, 5094), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((5148, 5160), 'glom.Path', 'Path', (['T.b', '(2)'], {}), '(T.b, 2)\n', (5152, 5160), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((5216, 5229), 'glom.T', 'T', ([], {'test': '"""yes"""'}), "(test='yes')\n", (5217, 5229), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((5386, 5399), 'glom.T', 'T', ([], {'test': '"""yes"""'}), "(test='yes')\n", (5387, 5399), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((5614, 5628), 'glom.Path', 'Path', (['"""a"""', '"""b"""'], {}), "('a', 'b')\n", (5618, 5628), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((5632, 5646), 'glom.Path', 'Path', (['"""a"""', '"""b"""'], {}), "('a', 'b')\n", (5636, 5646), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((5658, 5667), 'glom.Path', 'Path', (['"""a"""'], {}), "('a')\n", (5662, 5667), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((5671, 5680), 'glom.Path', 'Path', (['"""b"""'], {}), "('b')\n", (5675, 5680), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((5693, 5699), 'glom.Path', 'Path', ([], {}), '()\n', (5697, 5699), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((5747, 5758), 'glom.Path', 'Path', (['T.a.b'], {}), '(T.a.b)\n', (5751, 5758), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((5779, 5792), 'glom.Path', 'Path', (['T.a.b.c'], {}), '(T.a.b.c)\n', (5783, 5792), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((6043, 6049), 'glom.Path', 'Path', ([], {}), '()\n', (6047, 6049), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((6106, 6123), 'pytest.raises', 'raises', (['TypeError'], {}), '(TypeError)\n', (6112, 6123), False, 'from pytest import raises\n'), ((6357, 6384), 'glom.glom', 'glom', (['target', "{T['a']: 'a'}"], {}), "(target, {T['a']: 'a'})\n", (6361, 6384), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((6432, 6454), 'pytest.raises', 'raises', (['AttributeError'], {}), '(AttributeError)\n', (6438, 6454), False, 'from pytest import raises\n'), ((165, 172), 'glom.Path', 'Path', (['(1)'], {}), '(1)\n', (169, 172), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((306, 335), 'glom.Path', 'Path', (['"""a"""', '"""b.b"""', '(1)', '_obj', '(-1)'], {}), "('a', 'b.b', 1, _obj, -1)\n", (310, 335), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((417, 423), 'glom.Path', 'Path', ([], {}), '()\n', (421, 423), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((535, 541), 'glom.Path', 'Path', ([], {}), '()\n', (539, 541), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((583, 589), 'glom.Path', 'Path', ([], {}), '()\n', (587, 589), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((927, 952), 'glom.Path', 'Path', (['"""a"""', '(1)', '"""b.b"""', '(-1.0)'], {}), "('a', 1, 'b.b', -1.0)\n", (931, 952), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((1060, 1089), 'glom.Path', 'Path', (["T['a'].b", '"""c"""', "T['d'].e"], {}), "(T['a'].b, 'c', T['d'].e)\n", (1064, 1089), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((1620, 1636), 'glom.T.func', 'T.func', (['len', 'sum'], {}), '(len, sum)\n', (1626, 1636), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((2701, 2715), 'glom.Path', 'Path', (['"""a"""', 'T.b'], {}), "('a', T.b)\n", (2705, 2715), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((3240, 3260), 'glom.T.attribute.method', 'T.attribute.method', ([], {}), '()\n', (3258, 3260), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((3973, 3979), 'glom.Path', 'Path', ([], {}), '()\n', (3977, 3979), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((4001, 4020), 'glom.Path', 'Path', (['"""a"""', '"""b"""', '"""c"""'], {}), "('a', 'b', 'c')\n", (4005, 4020), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((4042, 4067), 'glom.Path.from_text', 'Path.from_text', (['"""1.2.3.4"""'], {}), "('1.2.3.4')\n", (4056, 4067), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((4090, 4097), 'glom.Path', 'Path', (['T'], {}), '(T)\n', (4094, 4097), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((4119, 4132), 'glom.Path', 'Path', (['T.a.b.c'], {}), '(T.a.b.c)\n', (4123, 4132), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((4721, 4734), 'glom.T', 'T', ([], {'test': '"""yes"""'}), "(test='yes')\n", (4722, 4734), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((4937, 4950), 'glom.T', 'T', ([], {'test': '"""yes"""'}), "(test='yes')\n", (4938, 4950), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((5858, 5867), 'glom.Path', 'Path', (['ref'], {}), '(ref)\n', (5862, 5867), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((5893, 5902), 'glom.Path', 'Path', (['ref'], {}), '(ref)\n', (5897, 5902), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((5932, 5941), 'glom.Path', 'Path', (['ref'], {}), '(ref)\n', (5936, 5941), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((6018, 6031), 'glom.Path', 'Path', (['"""a.b.c"""'], {}), "('a.b.c')\n", (6022, 6031), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((6062, 6075), 'glom.Path', 'Path', (['"""a.b.c"""'], {}), "('a.b.c')\n", (6066, 6075), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((6563, 6578), 'glom.T.__', 'T.__', (['"""class__"""'], {}), "('class__')\n", (6567, 6578), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((460, 466), 'glom.Path', 'Path', ([], {}), '()\n', (464, 466), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((468, 474), 'glom.Path', 'Path', ([], {}), '()\n', (472, 474), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((476, 482), 'glom.Path', 'Path', ([], {}), '()\n', (480, 482), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((1223, 1252), 'glom.Path', 'Path', (["T['a'].b", '"""c"""', "T['d'].e"], {}), "(T['a'].b, 'c', T['d'].e)\n", (1227, 1252), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((1415, 1420), 'glom.T.c', 'T.c', ([], {}), '()\n', (1418, 1420), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((2283, 2291), 'glom.T.copy', 'T.copy', ([], {}), '()\n', (2289, 2291), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((3474, 3494), 'pickle.dumps', 'pickle.dumps', (['s_spec'], {}), '(s_spec)\n', (3486, 3494), False, 'import pickle\n'), ((5312, 5318), 'glom.Path', 'Path', ([], {}), '()\n', (5316, 5318), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((5560, 5566), 'glom.Path', 'Path', ([], {}), '()\n', (5564, 5566), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((5969, 5978), 'glom.Path', 'Path', (['ref'], {}), '(ref)\n', (5973, 5978), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((6140, 6153), 'glom.Path', 'Path', (['"""a.b.c"""'], {}), "('a.b.c')\n", (6144, 6153), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((1514, 1523), 'glom.Path', 'Path', (['"""a"""'], {}), "('a')\n", (1518, 1523), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n'), ((4159, 4164), 'glom.T.a', 'T.a', ([], {}), '()\n', (4162, 4164), False, 'from glom import glom, Path, S, T, A, PathAccessError, GlomError, BadSpec\n')]
from pygame import * from random import randint import json #fonts and captions font.init() font1 = font.SysFont('Comic Sans', 60) win = font1.render('Dam you actually poggers', True, (255, 255, 255)) lose = font1.render('Yeah you suck, you lost', True, (180, 0, 0)) font2 = font.SysFont('Comic Sans', 36) ammo_lose = font1.render('You ran out of Ammo :(', True, (180, 0, 0)) #we need the following images: img_back = "galaxy.jpg" #game background img_hero = "rocket.png" #hero img_bullet = "bullet.png" #bullet img_enemy = "ufo.png" #enemy img_powerup = "Ruby_Icon.png" # very cool images yummy images score = 0 #ships destroyed lost = 0 #ships missed max_lost = 3 #lose if you miss that many #parent class for other sprites class GameSprite(sprite.Sprite): #class constructor def __init__(self, player_image, player_x, player_y, size_x, size_y, player_speed): #Call for the class (Sprite) constructor: sprite.Sprite.__init__(self) #every sprite must store the image property self.image = transform.scale(image.load(player_image), (size_x, size_y)) self.speed = player_speed #every sprite must have the rect property that represents the rectangle it is fitted in self.rect = self.image.get_rect() self.rect.x = player_x self.rect.y = player_y #method drawing the character on the window def reset(self): window.blit(self.image, (self.rect.x, self.rect.y)) dday = 2 level = 1 #main player class class Player(GameSprite): #method to control the sprite with arrow keys def update(self): keys = key.get_pressed() if keys[K_LEFT] and self.rect.x > 5: self.rect.x -= self.speed if keys[K_RIGHT] and self.rect.x < win_width - 80: self.rect.x += self.speed #method to "shoot" (use the player position to create a bullet there) def fire(self): bullet = Bullet(img_bullet, self.rect.centerx, self.rect.top, 15, 20, -15) bullets.add(bullet) #enemy sprite class class Enemy(GameSprite): #enemy movement def update(self): self.rect.y += self.speed global lost #disappears upon reaching the screen edge if self.rect.y > win_height: self.rect.x = randint(80, win_width - 80) self.rect.y = 0 lost = lost + 1 #bullet sprite class class Bullet(GameSprite): #enemy movement def update(self): self.rect.y += self.speed #disappears upon reaching the screen edge if self.rect.y < 0: self.kill() #Create a window win_width = 700 win_height = 500 display.set_caption("Shooter") window = display.set_mode((win_width, win_height)) background = transform.scale(image.load(img_back), (win_width, win_height)) #create sprites ship = Player(img_hero, 5, win_height - 100, 80, 100, 10) monsters = sprite.Group() powerups = sprite.Group() for i in range(1, dday): monster = Enemy(img_enemy, randint(80, win_width - 80), -40, 80, 50, randint(1, 5)) monsters.add(monster) bullets = sprite.Group() #the finish variable: as soon as True is there, sprites stop working in the main loop finish = False #Main game loop: run = True #the flag is reset by the window close button score_req = 1 total_score = 0 ammo = 20 with open('best_score.json', "r") as f: data = json.load(f) best_play = data["best_score"] def restart(): global score, lost, dday, level, score_req, ammo, best_play score = 0 lost = 0 text = font2.render("Score: " + str(score), 1, (255, 255, 255)) window.blit(text, (10, 20)) text_lose = font2.render("Missed: " + str(lost), 1, (255, 255, 255)) window.blit(text_lose, (10, 50)) for i in bullets: i.kill() for i in monsters: i.kill() dday = dday + 1 level += 1 ammo += 20 with open("best_score.json", "r") as f: data = json.load(f) best_play = data["best_score"] score_req = score_req + randint(1, 5) for i in range(1, dday): monster = Enemy(img_enemy, randint(80, win_width - 80), -40, 80, 50, randint(1, 5)) monsters.add(monster) def update_stats_on_lose(): global best_play, total_score, level, score_req, dday, ammo if best_play < total_score: best_play = total_score data["best_score"] = total_score with open('best_score.json', "w") as f: json.dump(data, f) total_score = 0 level = 0 score_req = 0 dday = 1 ammo = 0 while run: #"Close" button press event for e in event.get(): if e.type == QUIT: run = False #event of pressing the space bar - the sprite shoots elif e.type == KEYDOWN: if e.key == K_SPACE: fire_sound.play() ammo -= 1 ship.fire() if not finish: #update the background window.blit(background,(0,0)) #write text on the screen text_level = font2.render("Level: " + str(level), 1, (255, 255, 255)) window.blit(text_level, (10, 80)) text_ammo = font2.render("Ammo: " + str(ammo), 1, (255, 255, 255)) window.blit(text_ammo, (560, 10)) text_highscore = font2.render("Best Score Ever: " + str(best_play), 1, (255, 255, 255)) window.blit(text_highscore, (10, 140)) text_score_overall = font2.render("Total Score: " + str(total_score), 1, (255,255,255)) window.blit(text_score_overall, (10, 110)) text = font2.render("This Level Score: " + str(score), 1, (255, 255, 255)) window.blit(text, (10, 20)) spriteslist = sprite.groupcollide( monsters, bullets, True, True ) spriteslist2 = sprite.groupcollide( powerups, bullets, True, True ) if spriteslist2: amount_of_powerups_claimed += 1 if ammo == 0: update_stats_on_lose() window.blit(ammo_lose, (10, 200)) finish = True if spriteslist: score += 1 total_score += 1 monster = Enemy(img_enemy, randint(80, win_width - 80), -40, 80, 50, randint(1, 5)) monsters.add(monster) if score >= score_req: window.blit(win, (10, 200)) finish = True text_lose = font2.render("Missed: " + str(lost), 1, (255, 255, 255)) window.blit(text_lose, (10, 50)) if lost >= 3: update_stats_on_lose() window.blit(lose, (10, 200)) finish = True #launch sprite movements ship.update() monsters.update() bullets.update() powerups.update() #update them in a new location in each loop iteration ship.reset() monsters.draw(window) bullets.draw(window) powerups.draw(window) display.update() if finish == True: time.delay(1000) restart() finish = False #the loop is executed each 0.05 sec time.delay(50)
[ "json.load", "random.randint", "json.dump" ]
[((3315, 3327), 'json.load', 'json.load', (['f'], {}), '(f)\n', (3324, 3327), False, 'import json\n'), ((2939, 2966), 'random.randint', 'randint', (['(80)', '(win_width - 80)'], {}), '(80, win_width - 80)\n', (2946, 2966), False, 'from random import randint\n'), ((2981, 2994), 'random.randint', 'randint', (['(1)', '(5)'], {}), '(1, 5)\n', (2988, 2994), False, 'from random import randint\n'), ((3826, 3838), 'json.load', 'json.load', (['f'], {}), '(f)\n', (3835, 3838), False, 'import json\n'), ((3901, 3914), 'random.randint', 'randint', (['(1)', '(5)'], {}), '(1, 5)\n', (3908, 3914), False, 'from random import randint\n'), ((2241, 2268), 'random.randint', 'randint', (['(80)', '(win_width - 80)'], {}), '(80, win_width - 80)\n', (2248, 2268), False, 'from random import randint\n'), ((3972, 3999), 'random.randint', 'randint', (['(80)', '(win_width - 80)'], {}), '(80, win_width - 80)\n', (3979, 3999), False, 'from random import randint\n'), ((4014, 4027), 'random.randint', 'randint', (['(1)', '(5)'], {}), '(1, 5)\n', (4021, 4027), False, 'from random import randint\n'), ((4290, 4308), 'json.dump', 'json.dump', (['data', 'f'], {}), '(data, f)\n', (4299, 4308), False, 'import json\n'), ((5941, 5968), 'random.randint', 'randint', (['(80)', '(win_width - 80)'], {}), '(80, win_width - 80)\n', (5948, 5968), False, 'from random import randint\n'), ((5983, 5996), 'random.randint', 'randint', (['(1)', '(5)'], {}), '(1, 5)\n', (5990, 5996), False, 'from random import randint\n')]
# Copyright (c) 2013 Shotgun Software Inc. # # CONFIDENTIAL AND PROPRIETARY # # This work is provided "AS IS" and subject to the Shotgun Pipeline Toolkit # Source Code License included in this distribution package. See LICENSE. # By accessing, using, copying or modifying this work you indicate your # agreement to the Shotgun Pipeline Toolkit Source Code License. All rights # not expressly granted therein are reserved by Shotgun Software Inc. import tank import unicodedata import os import sys import threading from tank.platform.qt import QtCore, QtGui from tank.platform import restart from .ui.dialog import Ui_Dialog class AppDialog(QtGui.QWidget): def __init__(self, app): QtGui.QWidget.__init__(self) # set up the UI self.ui = Ui_Dialog() self.ui.setupUi(self) self._app = app # set up the browsers self.ui.context_browser.set_app(self._app) self.ui.context_browser.set_label("Your Current Work Context") self.ui.context_browser.enable_search(False) self.ui.context_browser.action_requested.connect( self.show_in_sg ) self.ui.app_browser.set_app(self._app) self.ui.app_browser.set_label("Currently Running Apps") self.ui.app_browser.action_requested.connect( self.show_app_in_app_store ) self.ui.environment_browser.set_app(self._app) self.ui.environment_browser.set_label("The Current Environment") self.ui.environment_browser.enable_search(False) self.ui.environment_browser.action_requested.connect( self.show_engine_in_app_store ) self.ui.jump_to_fs.clicked.connect( self.show_in_fs ) self.ui.support.clicked.connect( self.open_helpdesk ) self.ui.reload_apps.clicked.connect( self.reload ) self.ui.close.clicked.connect( self.close ) # load data from shotgun self.setup_context_list() self.setup_apps_list() self.setup_environment_list() # When there is no file system locations, hide the "Jump to the File System" button. if not self._app.context.filesystem_locations: self.ui.jump_to_fs.setVisible(False) ######################################################################################## # make sure we trap when the dialog is closed so that we can shut down # our threads. Nuke does not do proper cleanup on exit. def closeEvent(self, event): self.ui.context_browser.destroy() self.ui.app_browser.destroy() self.ui.environment_browser.destroy() # okay to close! event.accept() ######################################################################################## # basic business logic def setup_context_list(self): self.ui.context_browser.clear() self.ui.context_browser.load({}) def setup_apps_list(self): self.ui.app_browser.clear() self.ui.app_browser.load({}) def setup_environment_list(self): self.ui.environment_browser.clear() self.ui.environment_browser.load({}) def open_helpdesk(self): QtGui.QDesktopServices.openUrl(QtCore.QUrl("http://support.shotgunsoftware.com")) def reload(self): """ Reload templates and restart engine. """ restart() def show_in_fs(self): """ Jump from context to FS """ # launch one window for each location on disk paths = self._app.context.filesystem_locations for disk_location in paths: # get the setting system = sys.platform # run the app if system == "linux2": cmd = 'xdg-open "%s"' % disk_location elif system == "darwin": cmd = 'open "%s"' % disk_location elif system == "win32": cmd = 'cmd.exe /C start "Folder" "%s"' % disk_location else: raise Exception("Platform '%s' is not supported." % system) exit_code = os.system(cmd) if exit_code != 0: self._app.log_error("Failed to launch '%s'!" % cmd) def show_in_sg(self): """ Jump to shotgun """ curr_selection = self.ui.context_browser.get_selected_item() if curr_selection is None: return data = curr_selection.sg_data # steps do not have detail pages in shotgun so omit those if data["type"] == "Step": return sg_url = "%s/detail/%s/%d" % (self._app.shotgun.base_url, data["type"], data["id"]) QtGui.QDesktopServices.openUrl(QtCore.QUrl(sg_url)) def show_app_in_app_store(self): """ Jump to app store """ curr_selection = self.ui.app_browser.get_selected_item() if curr_selection is None: return doc_url = curr_selection.data.get("documentation_url") if doc_url is None: QtGui.QMessageBox.critical(self, "No Documentation found!", "Sorry, this app does not have any associated documentation!") else: QtGui.QDesktopServices.openUrl(QtCore.QUrl(doc_url)) def show_engine_in_app_store(self): """ Jump to app store """ curr_selection = self.ui.environment_browser.get_selected_item() if curr_selection is None: return doc_url = curr_selection.data.get("documentation_url") if doc_url: QtGui.QDesktopServices.openUrl(QtCore.QUrl(doc_url))
[ "tank.platform.qt.QtCore.QUrl", "tank.platform.restart", "tank.platform.qt.QtGui.QWidget.__init__", "os.system", "tank.platform.qt.QtGui.QMessageBox.critical" ]
[((708, 736), 'tank.platform.qt.QtGui.QWidget.__init__', 'QtGui.QWidget.__init__', (['self'], {}), '(self)\n', (730, 736), False, 'from tank.platform.qt import QtCore, QtGui\n'), ((3428, 3437), 'tank.platform.restart', 'restart', ([], {}), '()\n', (3435, 3437), False, 'from tank.platform import restart\n'), ((3273, 3322), 'tank.platform.qt.QtCore.QUrl', 'QtCore.QUrl', (['"""http://support.shotgunsoftware.com"""'], {}), "('http://support.shotgunsoftware.com')\n", (3284, 3322), False, 'from tank.platform.qt import QtCore, QtGui\n'), ((4212, 4226), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (4221, 4226), False, 'import os\n'), ((4865, 4884), 'tank.platform.qt.QtCore.QUrl', 'QtCore.QUrl', (['sg_url'], {}), '(sg_url)\n', (4876, 4884), False, 'from tank.platform.qt import QtCore, QtGui\n'), ((5214, 5340), 'tank.platform.qt.QtGui.QMessageBox.critical', 'QtGui.QMessageBox.critical', (['self', '"""No Documentation found!"""', '"""Sorry, this app does not have any associated documentation!"""'], {}), "(self, 'No Documentation found!',\n 'Sorry, this app does not have any associated documentation!')\n", (5240, 5340), False, 'from tank.platform.qt import QtCore, QtGui\n'), ((5473, 5493), 'tank.platform.qt.QtCore.QUrl', 'QtCore.QUrl', (['doc_url'], {}), '(doc_url)\n', (5484, 5493), False, 'from tank.platform.qt import QtCore, QtGui\n'), ((5848, 5868), 'tank.platform.qt.QtCore.QUrl', 'QtCore.QUrl', (['doc_url'], {}), '(doc_url)\n', (5859, 5868), False, 'from tank.platform.qt import QtCore, QtGui\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import re try: from setuptools import setup, find_packages except ImportError: from distutils.core import setup, find_packages # Backwards compatibility for Python 2.x try: from itertools import ifilter filter = ifilter except ImportError: pass from os.path import join as pjoin, splitext, split as psplit def get_version(): ''' Version slurping without importing bookstore, since dependencies may not be met until setup is run. ''' version_regex = re.compile(r"__version__\s+=\s+" r"['\"](\d+.\d+.\d+\w*)['\"]$") versions = filter(version_regex.match, open("kyper/__init__.py")) try: version = next(versions) except StopIteration: raise Exception("Bookstore version not set") return version_regex.match(version).group(1) version = get_version() # Utility for publishing the bookstore, courtesy kennethreitz/requests if sys.argv[-1] == 'publish': print("Publishing bookstore {version}".format(version=version)) os.system('python setup.py sdist upload') sys.exit() packages = ['kyper', 'kyper.nbformat', 'kyper.nbformat.v1', 'kyper.nbformat.v2', 'kyper.nbformat.v3', 'kyper.nbformat.v4', 'kyper.utils',] requires = [] with open('requirements.txt') as reqs: requires = reqs.read().splitlines() setup(name='module-tabs', version=version, description='IPython notebook storage on OpenStack Swift + Rackspace.', long_description=open('README.rst').read(), author='<NAME>', author_email='<EMAIL>', url='https://git.kyper.co/wusung.peng/ipython-notebook-fix.git', packages=find_packages(), package_data = { # If any package contains *.txt or *.rst files, include them: '': ['*.json', '*.json'], }, include_package_data=True, install_requires=requires, license=open('LICENSE').read(), zip_safe=False, classifiers=( 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Intended Audience :: Science/Research', 'Framework :: IPython', 'Environment :: OpenStack', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: System :: Distributed Computing', ), scripts={pjoin('bin/kyper-nbconvert'): 'kyper-nbconvert'}, )
[ "re.compile", "os.path.join", "distutils.core.find_packages", "sys.exit", "os.system" ]
[((563, 632), 're.compile', 're.compile', (['"""__version__\\\\s+=\\\\s+[\'\\\\"](\\\\d+.\\\\d+.\\\\d+\\\\w*)[\'\\\\"]$"""'], {}), '(\'__version__\\\\s+=\\\\s+[\\\'\\\\"](\\\\d+.\\\\d+.\\\\d+\\\\w*)[\\\'\\\\"]$\')\n', (573, 632), False, 'import re\n'), ((1100, 1141), 'os.system', 'os.system', (['"""python setup.py sdist upload"""'], {}), "('python setup.py sdist upload')\n", (1109, 1141), False, 'import os\n'), ((1146, 1156), 'sys.exit', 'sys.exit', ([], {}), '()\n', (1154, 1156), False, 'import sys\n'), ((1780, 1795), 'distutils.core.find_packages', 'find_packages', ([], {}), '()\n', (1793, 1795), False, 'from distutils.core import setup, find_packages\n'), ((2633, 2661), 'os.path.join', 'pjoin', (['"""bin/kyper-nbconvert"""'], {}), "('bin/kyper-nbconvert')\n", (2638, 2661), True, 'from os.path import join as pjoin, splitext, split as psplit\n')]
import os from django.test import TransactionTestCase from django.contrib.auth.models import Group from django.conf import settings from hs_core import hydroshare from hs_core.models import BaseResource from hs_core.hydroshare.utils import resource_file_add_process, resource_file_add_pre_process from hs_core.views.utils import create_folder from hs_core.testing import TestCaseCommonUtilities from hs_file_types.models import GenericLogicalFile class CompositeResourceTest(TestCaseCommonUtilities, TransactionTestCase): def setUp(self): super(CompositeResourceTest, self).setUp() super(CompositeResourceTest, self).assert_federated_irods_available() self.group, _ = Group.objects.get_or_create(name='Hydroshare Author') self.user = hydroshare.create_account( '<EMAIL>', username='user1', first_name='Creator_FirstName', last_name='Creator_LastName', superuser=False, groups=[self.group] ) super(CompositeResourceTest, self).create_irods_user_in_user_zone() self.raster_file_name = 'small_logan.tif' self.raster_file = 'hs_composite_resource/tests/data/{}'.format(self.raster_file_name) # transfer this valid tif file to user zone space for testing # only need to test that tif file stored in iRODS user zone space can be used to create a # composite resource and the file gets set to GenericLogicalFile type # Other relevant tests are adding a file to resource, deleting a file from resource # and deleting composite resource stored in iRODS user zone # Other detailed tests don't need to be retested for irods user zone space scenario since # as long as the tif file in iRODS user zone space can be read with metadata extracted # correctly, other functionalities are done with the same common functions regardless of # where the tif file comes from, either from local disk or from a federated user zone irods_target_path = '/' + settings.HS_USER_IRODS_ZONE + '/home/' + self.user.username + '/' file_list_dict = {self.raster_file: irods_target_path + self.raster_file_name} super(CompositeResourceTest, self).save_files_to_user_zone(file_list_dict) def tearDown(self): super(CompositeResourceTest, self).tearDown() super(CompositeResourceTest, self).assert_federated_irods_available() super(CompositeResourceTest, self).delete_irods_user_in_user_zone() def test_file_add_to_composite_resource(self): # only do federation testing when REMOTE_USE_IRODS is True and irods docker containers # are set up properly super(CompositeResourceTest, self).assert_federated_irods_available() # test that when we add file to an existing composite resource, the added file # automatically set to genericlogicalfile type self.assertEqual(BaseResource.objects.count(), 0) self.composite_resource = hydroshare.create_resource( resource_type='CompositeResource', owner=self.user, title='Test Composite Resource With Files Added From Federated Zone', auto_aggregate=False ) # there should not be any GenericLogicalFile object at this point self.assertEqual(GenericLogicalFile.objects.count(), 0) # add a file to the resource fed_test_file_full_path = '/{zone}/home/{username}/{fname}'.format( zone=settings.HS_USER_IRODS_ZONE, username=self.user.username, fname=self.raster_file_name) res_upload_files = [] resource_file_add_pre_process(resource=self.composite_resource, files=res_upload_files, source_names=[fed_test_file_full_path], user=self.user, folder=None) resource_file_add_process(resource=self.composite_resource, files=res_upload_files, source_names=[fed_test_file_full_path], user=self.user, auto_aggregate=False) # there should be one resource at this point self.assertEqual(BaseResource.objects.count(), 1) self.assertEqual(self.composite_resource.resource_type, "CompositeResource") self.assertEqual(self.composite_resource.files.all().count(), 1) res_file = self.composite_resource.files.first() # create the generic aggregation (logical file) GenericLogicalFile.set_file_type(self.composite_resource, self.user, res_file.id) # check that the resource file is associated with GenericLogicalFile res_file = self.composite_resource.files.first() self.assertEqual(res_file.has_logical_file, True) self.assertEqual(res_file.logical_file_type_name, "GenericLogicalFile") # there should be 1 GenericLogicalFile object at this point self.assertEqual(GenericLogicalFile.objects.count(), 1) # test adding a file to a folder (Note the UI does not support uploading a iRODS file # to a specific folder) # create the folder new_folder = "my-new-folder" new_folder_path = os.path.join("data", "contents", new_folder) create_folder(self.composite_resource.short_id, new_folder_path) resource_file_add_pre_process(resource=self.composite_resource, files=res_upload_files, source_names=[fed_test_file_full_path], user=self.user, folder=new_folder) resource_file_add_process(resource=self.composite_resource, files=res_upload_files, source_names=[fed_test_file_full_path], user=self.user, folder=new_folder, auto_aggregate=False) self.assertEqual(self.composite_resource.files.all().count(), 2) self.composite_resource.delete()
[ "hs_file_types.models.GenericLogicalFile.set_file_type", "hs_core.views.utils.create_folder", "os.path.join", "django.contrib.auth.models.Group.objects.get_or_create", "hs_file_types.models.GenericLogicalFile.objects.count", "hs_core.models.BaseResource.objects.count", "hs_core.hydroshare.create_resourc...
[((703, 756), 'django.contrib.auth.models.Group.objects.get_or_create', 'Group.objects.get_or_create', ([], {'name': '"""Hydroshare Author"""'}), "(name='Hydroshare Author')\n", (730, 756), False, 'from django.contrib.auth.models import Group\n'), ((777, 940), 'hs_core.hydroshare.create_account', 'hydroshare.create_account', (['"""<EMAIL>"""'], {'username': '"""user1"""', 'first_name': '"""Creator_FirstName"""', 'last_name': '"""Creator_LastName"""', 'superuser': '(False)', 'groups': '[self.group]'}), "('<EMAIL>', username='user1', first_name=\n 'Creator_FirstName', last_name='Creator_LastName', superuser=False,\n groups=[self.group])\n", (802, 940), False, 'from hs_core import hydroshare\n'), ((3022, 3206), 'hs_core.hydroshare.create_resource', 'hydroshare.create_resource', ([], {'resource_type': '"""CompositeResource"""', 'owner': 'self.user', 'title': '"""Test Composite Resource With Files Added From Federated Zone"""', 'auto_aggregate': '(False)'}), "(resource_type='CompositeResource', owner=self.\n user, title=\n 'Test Composite Resource With Files Added From Federated Zone',\n auto_aggregate=False)\n", (3048, 3206), False, 'from hs_core import hydroshare\n'), ((3658, 3824), 'hs_core.hydroshare.utils.resource_file_add_pre_process', 'resource_file_add_pre_process', ([], {'resource': 'self.composite_resource', 'files': 'res_upload_files', 'source_names': '[fed_test_file_full_path]', 'user': 'self.user', 'folder': 'None'}), '(resource=self.composite_resource, files=\n res_upload_files, source_names=[fed_test_file_full_path], user=self.\n user, folder=None)\n', (3687, 3824), False, 'from hs_core.hydroshare.utils import resource_file_add_process, resource_file_add_pre_process\n'), ((3899, 4070), 'hs_core.hydroshare.utils.resource_file_add_process', 'resource_file_add_process', ([], {'resource': 'self.composite_resource', 'files': 'res_upload_files', 'source_names': '[fed_test_file_full_path]', 'user': 'self.user', 'auto_aggregate': '(False)'}), '(resource=self.composite_resource, files=\n res_upload_files, source_names=[fed_test_file_full_path], user=self.\n user, auto_aggregate=False)\n', (3924, 4070), False, 'from hs_core.hydroshare.utils import resource_file_add_process, resource_file_add_pre_process\n'), ((4520, 4605), 'hs_file_types.models.GenericLogicalFile.set_file_type', 'GenericLogicalFile.set_file_type', (['self.composite_resource', 'self.user', 'res_file.id'], {}), '(self.composite_resource, self.user,\n res_file.id)\n', (4552, 4605), False, 'from hs_file_types.models import GenericLogicalFile\n'), ((5225, 5269), 'os.path.join', 'os.path.join', (['"""data"""', '"""contents"""', 'new_folder'], {}), "('data', 'contents', new_folder)\n", (5237, 5269), False, 'import os\n'), ((5278, 5342), 'hs_core.views.utils.create_folder', 'create_folder', (['self.composite_resource.short_id', 'new_folder_path'], {}), '(self.composite_resource.short_id, new_folder_path)\n', (5291, 5342), False, 'from hs_core.views.utils import create_folder\n'), ((5351, 5523), 'hs_core.hydroshare.utils.resource_file_add_pre_process', 'resource_file_add_pre_process', ([], {'resource': 'self.composite_resource', 'files': 'res_upload_files', 'source_names': '[fed_test_file_full_path]', 'user': 'self.user', 'folder': 'new_folder'}), '(resource=self.composite_resource, files=\n res_upload_files, source_names=[fed_test_file_full_path], user=self.\n user, folder=new_folder)\n', (5380, 5523), False, 'from hs_core.hydroshare.utils import resource_file_add_process, resource_file_add_pre_process\n'), ((5598, 5788), 'hs_core.hydroshare.utils.resource_file_add_process', 'resource_file_add_process', ([], {'resource': 'self.composite_resource', 'files': 'res_upload_files', 'source_names': '[fed_test_file_full_path]', 'user': 'self.user', 'folder': 'new_folder', 'auto_aggregate': '(False)'}), '(resource=self.composite_resource, files=\n res_upload_files, source_names=[fed_test_file_full_path], user=self.\n user, folder=new_folder, auto_aggregate=False)\n', (5623, 5788), False, 'from hs_core.hydroshare.utils import resource_file_add_process, resource_file_add_pre_process\n'), ((2954, 2982), 'hs_core.models.BaseResource.objects.count', 'BaseResource.objects.count', ([], {}), '()\n', (2980, 2982), False, 'from hs_core.models import BaseResource\n'), ((3351, 3385), 'hs_file_types.models.GenericLogicalFile.objects.count', 'GenericLogicalFile.objects.count', ([], {}), '()\n', (3383, 3385), False, 'from hs_file_types.models import GenericLogicalFile\n'), ((4208, 4236), 'hs_core.models.BaseResource.objects.count', 'BaseResource.objects.count', ([], {}), '()\n', (4234, 4236), False, 'from hs_core.models import BaseResource\n'), ((4967, 5001), 'hs_file_types.models.GenericLogicalFile.objects.count', 'GenericLogicalFile.objects.count', ([], {}), '()\n', (4999, 5001), False, 'from hs_file_types.models import GenericLogicalFile\n')]
# conftest.py import pytest import os from myapp import create_app, create_contentful from dotenv import load_dotenv load_dotenv() SPACE_ID = os.getenv("SPACE_ID") DELIVERY_API_KEY = os.getenv("DELIVERY_API_KEY") TESTING_ENV = "circle_testing" @pytest.fixture def app(): app = create_app(SPACE_ID, DELIVERY_API_KEY, environment_id=TESTING_ENV) app.debug = True return app @pytest.fixture def contentful_client(): contentful_client = create_contentful( SPACE_ID, DELIVERY_API_KEY, environment_id=TESTING_ENV ) return contentful_client
[ "myapp.create_app", "myapp.create_contentful", "os.getenv", "dotenv.load_dotenv" ]
[((118, 131), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (129, 131), False, 'from dotenv import load_dotenv\n'), ((144, 165), 'os.getenv', 'os.getenv', (['"""SPACE_ID"""'], {}), "('SPACE_ID')\n", (153, 165), False, 'import os\n'), ((185, 214), 'os.getenv', 'os.getenv', (['"""DELIVERY_API_KEY"""'], {}), "('DELIVERY_API_KEY')\n", (194, 214), False, 'import os\n'), ((285, 351), 'myapp.create_app', 'create_app', (['SPACE_ID', 'DELIVERY_API_KEY'], {'environment_id': 'TESTING_ENV'}), '(SPACE_ID, DELIVERY_API_KEY, environment_id=TESTING_ENV)\n', (295, 351), False, 'from myapp import create_app, create_contentful\n'), ((455, 528), 'myapp.create_contentful', 'create_contentful', (['SPACE_ID', 'DELIVERY_API_KEY'], {'environment_id': 'TESTING_ENV'}), '(SPACE_ID, DELIVERY_API_KEY, environment_id=TESTING_ENV)\n', (472, 528), False, 'from myapp import create_app, create_contentful\n')]
#!/usr/bin/python3.6 import sqlite3 def make_connect(): conn = sqlite3.connect("bot.db") cursor = conn.cursor() return conn, cursor def create_tables(): conn, cursor = make_connect() try: cursor.execute("CREATE TABLE users(user_id INTEGER, bal FLOAT, count_games INTEGER, sum_games FLOAT, ref_id INTEGER, ref_sum FLOAT)") except: pass try: cursor.execute("CREATE TABLE qiwi_popoln(user_id INTEGER, sum FLOAT, phone INTEGER, random_code INTEGER)") except: pass try: cursor.execute("CREATE TABLE withdraw(user_id INTEGER, sum FLOAT, num TEXT, type INTEGER)") except: pass try: cursor.execute("CREATE TABLE dice(hash INTEGER, sum_bet FLOAT, creator_user_id INTEGER, player_user_id INTEGER, creator_value INTEGER, player_value INTEGER, type TEXT)") except: pass try: cursor.execute("CREATE TABLE history_dice(user_id INTEGER, hash INTEGER, sum_win FLOAT)") except: pass try: cursor.execute("CREATE TABLE ban(user_id INTEGER, S INTEGER)") except: pass try: cursor.execute("CREATE TABLE nontrueusers(user_id INTEGER, S INTEGER)") except: pass try: cursor.execute("CREATE TABLE quetions(hash TEXT, quetion TEXT, answer TEXT)") except: pass try: cursor.execute("CREATE TABLE support(user_id INTEGER, quetion TEXT)") except: pass
[ "sqlite3.connect" ]
[((67, 92), 'sqlite3.connect', 'sqlite3.connect', (['"""bot.db"""'], {}), "('bot.db')\n", (82, 92), False, 'import sqlite3\n')]
# -*- coding: utf-8 -*- """ :copyright: Copyright 2020-2022 Sphinx Confluence Builder Contributors (AUTHORS) :license: BSD-2-Clause (LICENSE) """ from tests.lib.testcase import ConfluenceTestCase from tests.lib.testcase import setup_builder from tests.lib import parse import os class TestConfluenceRstLists(ConfluenceTestCase): @classmethod def setUpClass(cls): super(TestConfluenceRstLists, cls).setUpClass() cls.dataset = os.path.join(cls.datasets, 'common') cls.filenames = [ 'lists', ] @setup_builder('confluence') def test_storage_rst_lists(self): out_dir = self.build(self.dataset, filenames=self.filenames) with parse('lists', out_dir) as data: root_tags = data.find_all(recursive=False) self.assertEqual(len(root_tags), 3) # ########################################################## # bullet list # ########################################################## bullet_list = root_tags.pop(0) self.assertEqual(bullet_list.name, 'ul') items = bullet_list.find_all('li', recursive=False) self.assertEqual(len(items), 4) self.assertEqual(items[0].text.strip(), 'first bullet') self.assertEqual(items[2].text.strip(), 'third item') self.assertEqual(items[3].text.strip(), 'forth item') complex_list = items[1] complex_tags = complex_list.find_all(recursive=False) self.assertEqual(complex_tags[0].name, 'p') self.assertEqual(complex_tags[0].text.strip(), 'second item') self.assertEqual(complex_tags[1].name, 'p') self.assertEqual(complex_tags[1].text.strip(), 'second paragraph in the second item') self.assertEqual(complex_tags[2].name, 'p') self.assertEqual(complex_tags[2].text.strip(), 'third paragraph in the second item') self.assertEqual(complex_tags[3].name, 'ul') sublist = complex_tags[3].find_all('li', recursive=False) self.assertEqual(len(sublist), 3) # ########################################################## # enumerated list # ########################################################## enumerated_list = root_tags.pop(0) self.assertEqual(enumerated_list.name, 'ol') css_style = 'list-style-type: decimal' self.assertTrue(enumerated_list.has_attr('style')) self.assertTrue(css_style in enumerated_list['style']) items = enumerated_list.find_all('li', recursive=False) self.assertEqual(len(items), 2) self.assertEqual(items[0].text.strip(), 'enumerated a1') self.assertEqual(items[1].text.strip(), 'enumerated a2') # ########################################################## # enumerated list (styled) # ########################################################## enumerated_list = root_tags.pop(0) self.assertEqual(enumerated_list.name, 'ol') css_style = 'list-style-type: decimal' self.assertTrue(enumerated_list.has_attr('style')) self.assertTrue(css_style in enumerated_list['style']) items = enumerated_list.find_all('li', recursive=False) self.assertEqual(len(items), 4) css_style = 'list-style-type: lower-alpha' sublist1 = items[0].find('ol', recursive=False) self.assertIsNotNone(sublist1) self.assertTrue(sublist1.has_attr('style')) self.assertTrue(css_style in sublist1['style']) css_style = 'list-style-type: upper-alpha' sublist2 = items[1].find('ol', recursive=False) self.assertIsNotNone(sublist2) self.assertTrue(sublist2.has_attr('style')) self.assertTrue(css_style in sublist2['style']) css_style = 'list-style-type: decimal' sublist3 = items[2].find('ol', recursive=False) self.assertIsNotNone(sublist3) self.assertTrue(sublist3.has_attr('style')) self.assertTrue(css_style in sublist3['style']) css_style = 'list-style-type: lower-roman' sublist4 = items[3].find('ol', recursive=False) self.assertIsNotNone(sublist4) self.assertTrue(sublist4.has_attr('style')) self.assertTrue(css_style in sublist4['style'])
[ "os.path.join", "tests.lib.parse", "tests.lib.testcase.setup_builder" ]
[((553, 580), 'tests.lib.testcase.setup_builder', 'setup_builder', (['"""confluence"""'], {}), "('confluence')\n", (566, 580), False, 'from tests.lib.testcase import setup_builder\n'), ((453, 489), 'os.path.join', 'os.path.join', (['cls.datasets', '"""common"""'], {}), "(cls.datasets, 'common')\n", (465, 489), False, 'import os\n'), ((702, 725), 'tests.lib.parse', 'parse', (['"""lists"""', 'out_dir'], {}), "('lists', out_dir)\n", (707, 725), False, 'from tests.lib import parse\n')]
import os os.system("pip install tqsdk -i https://pypi.tuna.tsinghua.edu.cn/simple") os.system("pip install numba -i https://pypi.tuna.tsinghua.edu.cn/simple") os.system("pip install janus -i https://pypi.tuna.tsinghua.edu.cn/simple") os.system("pip install redis -i https://pypi.tuna.tsinghua.edu.cn/simple") os.system("pip install aioredis -i https://pypi.tuna.tsinghua.edu.cn/simple") os.system("pip install schedule -i https://pypi.tuna.tsinghua.edu.cn/simple") os.system("pip install pyqt5 -i https://pypi.tuna.tsinghua.edu.cn/simple") os.system("pip install PyQt5-tools -i http://pypi.douban.com/simple --trusted-host=pypi.douban.com")
[ "os.system" ]
[((14, 88), 'os.system', 'os.system', (['"""pip install tqsdk -i https://pypi.tuna.tsinghua.edu.cn/simple"""'], {}), "('pip install tqsdk -i https://pypi.tuna.tsinghua.edu.cn/simple')\n", (23, 88), False, 'import os\n'), ((90, 164), 'os.system', 'os.system', (['"""pip install numba -i https://pypi.tuna.tsinghua.edu.cn/simple"""'], {}), "('pip install numba -i https://pypi.tuna.tsinghua.edu.cn/simple')\n", (99, 164), False, 'import os\n'), ((166, 240), 'os.system', 'os.system', (['"""pip install janus -i https://pypi.tuna.tsinghua.edu.cn/simple"""'], {}), "('pip install janus -i https://pypi.tuna.tsinghua.edu.cn/simple')\n", (175, 240), False, 'import os\n'), ((242, 316), 'os.system', 'os.system', (['"""pip install redis -i https://pypi.tuna.tsinghua.edu.cn/simple"""'], {}), "('pip install redis -i https://pypi.tuna.tsinghua.edu.cn/simple')\n", (251, 316), False, 'import os\n'), ((318, 395), 'os.system', 'os.system', (['"""pip install aioredis -i https://pypi.tuna.tsinghua.edu.cn/simple"""'], {}), "('pip install aioredis -i https://pypi.tuna.tsinghua.edu.cn/simple')\n", (327, 395), False, 'import os\n'), ((397, 474), 'os.system', 'os.system', (['"""pip install schedule -i https://pypi.tuna.tsinghua.edu.cn/simple"""'], {}), "('pip install schedule -i https://pypi.tuna.tsinghua.edu.cn/simple')\n", (406, 474), False, 'import os\n'), ((476, 550), 'os.system', 'os.system', (['"""pip install pyqt5 -i https://pypi.tuna.tsinghua.edu.cn/simple"""'], {}), "('pip install pyqt5 -i https://pypi.tuna.tsinghua.edu.cn/simple')\n", (485, 550), False, 'import os\n'), ((552, 662), 'os.system', 'os.system', (['"""pip install PyQt5-tools -i http://pypi.douban.com/simple --trusted-host=pypi.douban.com"""'], {}), "(\n 'pip install PyQt5-tools -i http://pypi.douban.com/simple --trusted-host=pypi.douban.com'\n )\n", (561, 662), False, 'import os\n')]
from __future__ import absolute_import, print_function, unicode_literals import unittest from doozerlib import distgit class TestDistgitConvertSourceURLToHTTPS(unittest.TestCase): def test_conversion_from_ssh_source(self): source = "git@github.com:myorg/myproject.git" actual = distgit.convert_source_url_to_https(source) expected = "https://github.com/myorg/myproject" self.assertEqual(actual, expected) def test_conversion_from_already_https_source(self): source = "https://github.com/myorg/myproject" actual = distgit.convert_source_url_to_https(source) expected = "https://github.com/myorg/myproject" self.assertEqual(actual, expected) def test_conversion_from_https_source_with_dotgit_suffix(self): source = "https://github.com/myorg/myproject.git" actual = distgit.convert_source_url_to_https(source) expected = "https://github.com/myorg/myproject" self.assertEqual(actual, expected) def test_conversion_from_https_source_with_dotgit_elsewhere(self): source = "https://foo.gitlab.com/myorg/myproject" actual = distgit.convert_source_url_to_https(source) expected = "https://foo.gitlab.com/myorg/myproject" self.assertEqual(actual, expected) if __name__ == '__main__': unittest.main()
[ "unittest.main", "doozerlib.distgit.convert_source_url_to_https" ]
[((1338, 1353), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1351, 1353), False, 'import unittest\n'), ((302, 345), 'doozerlib.distgit.convert_source_url_to_https', 'distgit.convert_source_url_to_https', (['source'], {}), '(source)\n', (337, 345), False, 'from doozerlib import distgit\n'), ((576, 619), 'doozerlib.distgit.convert_source_url_to_https', 'distgit.convert_source_url_to_https', (['source'], {}), '(source)\n', (611, 619), False, 'from doozerlib import distgit\n'), ((865, 908), 'doozerlib.distgit.convert_source_url_to_https', 'distgit.convert_source_url_to_https', (['source'], {}), '(source)\n', (900, 908), False, 'from doozerlib import distgit\n'), ((1157, 1200), 'doozerlib.distgit.convert_source_url_to_https', 'distgit.convert_source_url_to_https', (['source'], {}), '(source)\n', (1192, 1200), False, 'from doozerlib import distgit\n')]
import requests import ssl from requests.adapters import HTTPAdapter, PoolManager class MyAdapter(HTTPAdapter): def init_poolmanager(self, connections, maxsize): super(MyAdapter, self).__init__() self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize, ssl_version=ssl.PROTOCOL_SSLv3) s = requests.Session() s.mount('https://', MyAdapter()) # 所有的https连接都用ssl.PROTOCOL_SSLV3去连接 s.get('https://xxx.com')
[ "requests.adapters.PoolManager", "requests.Session" ]
[((327, 345), 'requests.Session', 'requests.Session', ([], {}), '()\n', (343, 345), False, 'import requests\n'), ((237, 325), 'requests.adapters.PoolManager', 'PoolManager', ([], {'num_pools': 'connections', 'maxsize': 'maxsize', 'ssl_version': 'ssl.PROTOCOL_SSLv3'}), '(num_pools=connections, maxsize=maxsize, ssl_version=ssl.\n PROTOCOL_SSLv3)\n', (248, 325), False, 'from requests.adapters import HTTPAdapter, PoolManager\n')]
# Generated by Django 3.0.2 on 2020-04-29 20:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('assessment', '0009_auto_20200426_1103'), ] operations = [ migrations.AddField( model_name='assessment', name='open_status', field=models.BooleanField(default=True, verbose_name='open status'), ), ]
[ "django.db.models.BooleanField" ]
[((346, 407), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)', 'verbose_name': '"""open status"""'}), "(default=True, verbose_name='open status')\n", (365, 407), False, 'from django.db import migrations, models\n')]
# -*- coding: utf-8 -*- import json import math import random import argparse import networkx as nx class Node: def __init__ (self, nodeNumber, nodeType): self.nodeNumber = nodeNumber self.nodeType = nodeType def add_vm (self, vm): if not hasattr(self,'vms'): self.vms = [] self.vms.append(vm) class VM: def __init__ (self, vmNumber, cpu, ram): self.vmNumber = vmNumber self.cpu = cpu self.ram = ram class Link: def __init__ (self, linkNumber, fromNode, toNode, capacity, delay): self.linkNumber = linkNumber self.fromNode = fromNode self.toNode = toNode self.delay = delay self.capacity = capacity def serialize (obj): return obj.__dict__ def gen_vms_profile (): vms_profile = [] processor = [1, 2, 4, 8] memory = [1024, 2048, 4096, 8192] for vcpus in processor: for ram in memory: vms_profile.append({'cpu': vcpus, 'ram': ram}) return vms_profile def gen_link_profile (): links_profile = [] mm_wave_bw = [0.9, 1.25, 1.5, 2, 3, 4, 8] micro_wave_bw = [0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.25, 1.5, 2] copper_bw = [1, 10, 40] smf_fiber_1310_bw = [1, 10, 40, 100] smf_fiber_1550_bw = [1, 10, 40, 100] tbe_bw = [200, 400] mm_wave_delay = range(1, 21) micro_wave_delay = range(1, 101) copper_delay = [] n = 0.05 for i in range(50): copper_delay.append(n + (i * 0.02)) smf_fiber_1310_delay = range(1, 201) smf_fiber_1550_delay = range(1, 351) tbe_delay = range (1, 51) for bw in mm_wave_bw: for delay in mm_wave_delay: dist = delay * 0.3 links_profile.append({'delay': delay, 'bw': bw, 'dist': dist}) for bw in micro_wave_bw: for delay in micro_wave_delay: dist = delay * 0.3 links_profile.append({'delay': delay, 'bw': bw, 'dist': dist}) for bw in copper_bw: if(bw == 1): for delay in copper_delay: dist = delay * 0.02 links_profile.append({'delay': delay, 'bw': bw, 'dist': dist}) elif(bw == 10): delay = 0.275 dist = 0.055 links_profile.append({'delay': delay, 'bw': bw, 'dist': dist}) else: delay = 0.15 dist = 0.03 links_profile.append({'delay': delay, 'bw': bw, 'dist': dist}) for bw in smf_fiber_1310_bw: if(bw == 1): for delay in smf_fiber_1310_delay: dist = delay * 0.2 links_profile.append({'delay': delay, 'bw': bw, 'dist': dist}) else: delay = 50 dist = 10 links_profile.append({'delay': delay, 'bw': bw, 'dist': dist}) for bw in smf_fiber_1550_bw: if(bw == 1): for delay in smf_fiber_1550_delay: dist = delay * 0.2 links_profile.append({'delay': delay, 'bw': bw, 'dist': dist}) else: delay = 200 dist = 40 links_profile.append({'delay': delay, 'bw': bw, 'dist': dist}) for bw in tbe_bw: for delay in tbe_delay: dist = delay * 0.2 links_profile.append({'delay': delay, 'bw': bw, 'dist': dist}) return links_profile def draw_nodes (graph, vms_profile): node_list = [] node_type = ["MECHost", "BaseStation", "Forwarding"] nodeCount = 0 vmCount = 1 num_nodes = nx.number_of_nodes(graph) number_mec = int(round(num_nodes * 0.05)) number_Base_Station = int(round(num_nodes * 0.3)) number_forwarding = num_nodes - number_Base_Station - number_mec graph_nodes = list(graph.nodes) for i in range(number_mec): choice = random.choice(graph_nodes) graph_nodes.remove(choice) node = (Node(nodeCount, 'MECHost')) nodeCount += 1 numberVMs = random.randint(1, 10) for j in range (numberVMs): profile = random.choice(vms_profile) node.add_vm(VM(vmCount, profile['cpu'], profile['ram'])) vmCount += 1 node_list.append(node) for i in range(number_Base_Station): choice = random.choice(graph_nodes) graph_nodes.remove(choice) node = (Node(nodeCount, 'BaseStation')) node.add_vm(VM(vmCount, 1, 1024)) node_list.append(node) nodeCount += 1 vmCount += 1 for i in range(number_forwarding): choice = random.choice(graph_nodes) graph_nodes.remove(choice) node_list.append(Node(nodeCount, 'Forwarding')) nodeCount += 1 return node_list def closest_dist(links_profile, distance): aux = [] min_diff = 1000000 closest_dist = -1 for link in links_profile: if abs(link['dist'] - distance) < min_diff: min_diff = abs(link['dist'] - distance) closest_dist = link['dist'] return closest_dist def draw_links (graph, links_profile, L): links_list = [] nodeCount = 0 pos = nx.get_node_attributes(graph, 'pos') for edge in graph.edges: x1, y1 = pos[edge[0]] x2, y2 = pos[edge[1]] distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) * L closest = closest_dist(links_profile, distance) profile = random.choice([link for link in links_profile if link['dist'] == closest]) links_list.append(Link(nodeCount + 1, edge[0], edge[1], profile['bw'], profile['delay'])) nodeCount += 1 return links_list def gen_topology(num_nodes, alpha, beta, L): graph = nx.waxman_graph(num_nodes, beta, alpha, L) while not nx.is_connected(graph): graph = nx.waxman_graph(num_nodes, beta, alpha, L) return graph def save_json(node_list, links_list, user): topology = {"user": user, "nodes": node_list, "links": links_list} json_out_file = open('topology.json', 'w') json.dump(topology, json_out_file, default=serialize) def generate_topology(num_nodes, alpha, beta, L, user): graph = gen_topology(num_nodes, alpha, beta, L) links_profile = gen_link_profile() links_list = draw_links(graph, links_profile, L) vms_profile = gen_vms_profile() node_list = draw_nodes(graph, vms_profile) save_json(node_list, links_list, user) def main (): parser = argparse.ArgumentParser() parser.add_argument("-u", "--username", help="Your username") parser.add_argument("-n", "--nodes", help="Number of nodes", type=int) parser.add_argument("-a", "--alpha", help="Alpha Model parameter", type=float) parser.add_argument("-b", "--beta", help="Beta Model parameter", type=float) parser.add_argument("-l", "--dist", help="Maximum distance between nodes", type=float) args = parser.parse_args() generate_topology(args.nodes, args.alpha, args.beta, args.dist, args.username) if __name__ == '__main__': main()
[ "random.choice", "argparse.ArgumentParser", "networkx.is_connected", "math.sqrt", "networkx.get_node_attributes", "networkx.waxman_graph", "networkx.number_of_nodes", "random.randint", "json.dump" ]
[((2993, 3018), 'networkx.number_of_nodes', 'nx.number_of_nodes', (['graph'], {}), '(graph)\n', (3011, 3018), True, 'import networkx as nx\n'), ((4359, 4395), 'networkx.get_node_attributes', 'nx.get_node_attributes', (['graph', '"""pos"""'], {}), "(graph, 'pos')\n", (4381, 4395), True, 'import networkx as nx\n'), ((4855, 4897), 'networkx.waxman_graph', 'nx.waxman_graph', (['num_nodes', 'beta', 'alpha', 'L'], {}), '(num_nodes, beta, alpha, L)\n', (4870, 4897), True, 'import networkx as nx\n'), ((5162, 5215), 'json.dump', 'json.dump', (['topology', 'json_out_file'], {'default': 'serialize'}), '(topology, json_out_file, default=serialize)\n', (5171, 5215), False, 'import json\n'), ((5550, 5575), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (5573, 5575), False, 'import argparse\n'), ((3254, 3280), 'random.choice', 'random.choice', (['graph_nodes'], {}), '(graph_nodes)\n', (3267, 3280), False, 'import random\n'), ((3380, 3401), 'random.randint', 'random.randint', (['(1)', '(10)'], {}), '(1, 10)\n', (3394, 3401), False, 'import random\n'), ((3628, 3654), 'random.choice', 'random.choice', (['graph_nodes'], {}), '(graph_nodes)\n', (3641, 3654), False, 'import random\n'), ((3868, 3894), 'random.choice', 'random.choice', (['graph_nodes'], {}), '(graph_nodes)\n', (3881, 3894), False, 'import random\n'), ((4595, 4669), 'random.choice', 'random.choice', (["[link for link in links_profile if link['dist'] == closest]"], {}), "([link for link in links_profile if link['dist'] == closest])\n", (4608, 4669), False, 'import random\n'), ((4911, 4933), 'networkx.is_connected', 'nx.is_connected', (['graph'], {}), '(graph)\n', (4926, 4933), True, 'import networkx as nx\n'), ((4945, 4987), 'networkx.waxman_graph', 'nx.waxman_graph', (['num_nodes', 'beta', 'alpha', 'L'], {}), '(num_nodes, beta, alpha, L)\n', (4960, 4987), True, 'import networkx as nx\n'), ((3446, 3472), 'random.choice', 'random.choice', (['vms_profile'], {}), '(vms_profile)\n', (3459, 3472), False, 'import random\n'), ((4488, 4530), 'math.sqrt', 'math.sqrt', (['((x2 - x1) ** 2 + (y2 - y1) ** 2)'], {}), '((x2 - x1) ** 2 + (y2 - y1) ** 2)\n', (4497, 4530), False, 'import math\n')]
"""Simple Bot to reply to Telegram messages. This is built on the API wrapper, see echobot2.py to see the same example built on the telegram.ext bot framework. This program is dedicated to the public domain under the CC0 license. """ import logging import telegram import requests, json import traceback from time import sleep import model as ml import tensorflow as tf from earlystop import EarlyStopping import random import math import os, sys import data import datetime from configs import DEFINES update_id = 0 def __del__(self): bot = telegram.Bot('auth') bot.send_message(chat_id = -116418298, text="Penta 서비스가 종료되었습니다.") def main(): """Run the bot.""" global update_id # Telegram Bot Authorization Token bot = telegram.Bot('auth') URL = "https://unopenedbox.com/develop/square/api.php" last_message = "" bootcount = 0 lcount = 0 readingold = False readingold_lastcount = 0 now = datetime.datetime.now() # get the first pending update_id, this is so we can skip over it in case # we get an "Unauthorized" exception. # 데이터를 통한 사전 구성 한다. char2idx, idx2char, vocabulary_length = data.load_vocabulary() # 에스티메이터 구성한다. classifier = tf.estimator.Estimator( model_fn=ml.Model, # 모델 등록한다. model_dir=DEFINES.check_point_path, # 체크포인트 위치 등록한다. params={ # 모델 쪽으로 파라메터 전달한다. 'hidden_size': DEFINES.hidden_size, # 가중치 크기 설정한다. 'layer_size': DEFINES.layer_size, # 멀티 레이어 층 개수를 설정한다. 'learning_rate': DEFINES.learning_rate, # 학습율 설정한다. 'teacher_forcing_rate': DEFINES.teacher_forcing_rate, # 학습시 디코더 인풋 정답 지원율 설정 'vocabulary_length': vocabulary_length, # 딕셔너리 크기를 설정한다. 'embedding_size': DEFINES.embedding_size, # 임베딩 크기를 설정한다. 'embedding': DEFINES.embedding, # 임베딩 사용 유무를 설정한다. 'multilayer': DEFINES.multilayer, # 멀티 레이어 사용 유무를 설정한다. 'attention': DEFINES.attention, # 어텐션 지원 유무를 설정한다. 'teacher_forcing': DEFINES.teacher_forcing, # 학습시 디코더 인풋 정답 지원 유무 설정한다. 'loss_mask': DEFINES.loss_mask, # PAD에 대한 마스크를 통한 loss를 제한 한다. 'serving': DEFINES.serving # 모델 저장 및 serving 유무를 설정한다. }) while 1: sleep(3) now = datetime.datetime.now() bootcount = bootcount + 1 lcount = lcount + 1 try: #data = {'a': 'penta_check', 'auth': '<PASSWORD>', 'start_num' : '0', 'number' : '15'} #res = requests.post(URL, data=data) #answer = "[보고]" + res.json()[0]['description']; answer = "" if bootcount == 1 : #answer = "다시 시작했습니다. Penta 버전 1.0.625 밀린 채팅을 읽는 중 입니다..." readingold = True readingold_lastcount = bootcount if readingold_lastcount < bootcount and readingold is True : readingold = False #bot.send_message(chat_id = -116418298, text="이전글 읽기 완료.") if last_message != answer and answer != "" : bot.send_message(chat_id = -116418298, text=answer) last_message = answer if last_message == answer : tlm = "" last_user = 0 last_talk = "" updates = bot.get_updates(offset=update_id) for i in updates: if i.message: if last_user != i.message.from_user.id : last_talk = tlm tlm = "" last_user = i.message.from_user.id # with open("./data_in/ChatBotData.csv", "a") as myfile: # myfile.write("\n") if i.message.text is not None and tlm != "" : tlm = tlm + " " + i.message.text # with open("./data_in/ChatBotData.csv", "a") as myfile: # myfile.write(" " + i.message.text) if i.message.text is not None and tlm == "" : tlm = i.message.text # with open("./data_in/ChatBotData.csv", "a") as myfile: # myfile.write(i.message.text) update_id = i.update_id + 1 now_last_id = updates[-1].update_id if tlm != "" and tlm is not None and now_last_id + 1 <= update_id: readingold_lastcount = readingold_lastcount +1 lcount = 0 if not readingold : predic_input_enc, predic_input_enc_length = data.enc_processing([tlm], char2idx) predic_target_dec, _ = data.dec_target_processing([""], char2idx) # 예측을 하는 부분이다. predictions = classifier.predict( input_fn=lambda:data.eval_input_fn(predic_input_enc, predic_target_dec, DEFINES.batch_size)) # 예측한 값을 인지 할 수 있도록 # 텍스트로 변경하는 부분이다. aimessage = data.pred2string(predictions, idx2char) if aimessage != "" : bot.send_message(chat_id = -116418298, text=aimessage) except IndexError: update_id = None except: if last_message != traceback.format_exc() and "Message text is empty" not in traceback.format_exc(): bot.send_message(chat_id = -11641828, text="[오류] 오류가 발생했습니다. 점검이 필요합니다. \n"+ traceback.format_exc()) last_message = traceback.format_exc() logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') def echo(bot): """Echo the message the user sent.""" global update_id # Request updates after the last update_id for update in bot.get_updates(offset=update_id, timeout=10): update_id = update.update_id + 1 if update.message: # your bot can receive updates without messages # Reply to the message update.message.reply_text("HI") if __name__ == '__main__': main()
[ "logging.basicConfig", "traceback.format_exc", "data.enc_processing", "tensorflow.estimator.Estimator", "telegram.Bot", "time.sleep", "data.dec_target_processing", "datetime.datetime.now", "data.pred2string", "data.eval_input_fn", "data.load_vocabulary" ]
[((551, 571), 'telegram.Bot', 'telegram.Bot', (['"""auth"""'], {}), "('auth')\n", (563, 571), False, 'import telegram\n'), ((751, 771), 'telegram.Bot', 'telegram.Bot', (['"""auth"""'], {}), "('auth')\n", (763, 771), False, 'import telegram\n'), ((948, 971), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (969, 971), False, 'import datetime\n'), ((1162, 1184), 'data.load_vocabulary', 'data.load_vocabulary', ([], {}), '()\n', (1182, 1184), False, 'import data\n'), ((1225, 1797), 'tensorflow.estimator.Estimator', 'tf.estimator.Estimator', ([], {'model_fn': 'ml.Model', 'model_dir': 'DEFINES.check_point_path', 'params': "{'hidden_size': DEFINES.hidden_size, 'layer_size': DEFINES.layer_size,\n 'learning_rate': DEFINES.learning_rate, 'teacher_forcing_rate': DEFINES\n .teacher_forcing_rate, 'vocabulary_length': vocabulary_length,\n 'embedding_size': DEFINES.embedding_size, 'embedding': DEFINES.\n embedding, 'multilayer': DEFINES.multilayer, 'attention': DEFINES.\n attention, 'teacher_forcing': DEFINES.teacher_forcing, 'loss_mask':\n DEFINES.loss_mask, 'serving': DEFINES.serving}"}), "(model_fn=ml.Model, model_dir=DEFINES.\n check_point_path, params={'hidden_size': DEFINES.hidden_size,\n 'layer_size': DEFINES.layer_size, 'learning_rate': DEFINES.\n learning_rate, 'teacher_forcing_rate': DEFINES.teacher_forcing_rate,\n 'vocabulary_length': vocabulary_length, 'embedding_size': DEFINES.\n embedding_size, 'embedding': DEFINES.embedding, 'multilayer': DEFINES.\n multilayer, 'attention': DEFINES.attention, 'teacher_forcing': DEFINES.\n teacher_forcing, 'loss_mask': DEFINES.loss_mask, 'serving': DEFINES.\n serving})\n", (1247, 1797), True, 'import tensorflow as tf\n'), ((2268, 2276), 'time.sleep', 'sleep', (['(3)'], {}), '(3)\n', (2273, 2276), False, 'from time import sleep\n'), ((2288, 2311), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (2309, 2311), False, 'import datetime\n'), ((5389, 5476), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s - %(name)s - %(levelname)s - %(message)s"""'}), "(format=\n '%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n", (5408, 5476), False, 'import logging\n'), ((5360, 5382), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (5380, 5382), False, 'import traceback\n'), ((5140, 5162), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (5160, 5162), False, 'import traceback\n'), ((5198, 5220), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (5218, 5220), False, 'import traceback\n'), ((4474, 4510), 'data.enc_processing', 'data.enc_processing', (['[tlm]', 'char2idx'], {}), '([tlm], char2idx)\n', (4493, 4510), False, 'import data\n'), ((4552, 4594), 'data.dec_target_processing', 'data.dec_target_processing', (["['']", 'char2idx'], {}), "([''], char2idx)\n", (4578, 4594), False, 'import data\n'), ((4896, 4935), 'data.pred2string', 'data.pred2string', (['predictions', 'idx2char'], {}), '(predictions, idx2char)\n', (4912, 4935), False, 'import data\n'), ((5333, 5355), 'traceback.format_exc', 'traceback.format_exc', ([], {}), '()\n', (5353, 5355), False, 'import traceback\n'), ((4714, 4789), 'data.eval_input_fn', 'data.eval_input_fn', (['predic_input_enc', 'predic_target_dec', 'DEFINES.batch_size'], {}), '(predic_input_enc, predic_target_dec, DEFINES.batch_size)\n', (4732, 4789), False, 'import data\n')]
""" This module exports a Log class that wraps the logging python package Uses the standard python logging utilities, just provides nice formatting out of the box. Usage: from apertools.log import get_log logger = get_log() logger.info("Something happened") logger.warning("Something concerning happened") logger.error("Something bad happened") logger.critical("Something just awful happened") logger.debug("Extra printing we often don't need to see.") # Custom output for this module: logger.success("Something great happened: highlight this success") """ import logging import time from functools import wraps try: from colorlog import ColoredFormatter COLORS = True except ImportError: from logging import Formatter COLORS = False def get_log(debug=False, name=__file__, verbose=False): """Creates a nice log format for use across multiple files. Default logging level is INFO Args: name (Optional[str]): The name the logger will use when printing statements debug (Optional[bool]): If true, sets logging level to DEBUG """ logger = logging.getLogger(name) return format_log(logger, debug=debug, verbose=verbose) def format_log(logger, debug=False, verbose=False): """Makes the logging output pretty and colored with times""" log_level = logging.DEBUG if debug else logging.INFO log_colors = { "DEBUG": "blue", "INFO": "cyan", "WARNING": "yellow", "ERROR": "red", "CRITICAL": "black,bg_red", "SUCCESS": "white,bg_blue", } if COLORS: format_ = "[%(asctime)s] [%(log_color)s%(levelname)s %(filename)s%(reset)s] %(message)s%(reset)s" formatter = ColoredFormatter( format_, datefmt="%m/%d %H:%M:%S", log_colors=log_colors ) else: format_ = "[%(asctime)s] [%(levelname)s %(filename)s] %(message)s" formatter = Formatter(format_, datefmt="%m/%d %H:%M:%S") handler = logging.StreamHandler() handler.setFormatter(formatter) logging.SUCCESS = 25 # between WARNING and INFO logging.addLevelName(logging.SUCCESS, "SUCCESS") setattr( logger, "success", lambda message, *args: logger._log(logging.SUCCESS, message, args), ) if not logger.handlers: logger.addHandler(handler) logger.setLevel(log_level) if verbose: logger.info("Logger initialized: %s" % (logger.name,)) if debug: logger.setLevel(debug) return logger logger = get_log() def log_runtime(f): """ Logs how long a decorated function takes to run Args: f (function): The function to wrap Returns: function: The wrapped function Example: >>> @log_runtime ... def test_func(): ... return 2 + 4 >>> test_func() 6 This prints out to stderr the following in addition to the answer: [05/26 10:05:51] [INFO log.py] Total elapsed time for test_func (minutes): 0.00 """ @wraps(f) def wrapper(*args, **kwargs): t1 = time.time() result = f(*args, **kwargs) t2 = time.time() elapsed_time = t2 - t1 time_string = "Total elapsed time for {} : {} minutes ({} seconds)".format( f.__name__, "{0:.2f}".format(elapsed_time / 60.0), "{0:.2f}".format(elapsed_time), ) logger.info(time_string) return result return wrapper
[ "logging.getLogger", "logging.StreamHandler", "logging.Formatter", "functools.wraps", "logging.addLevelName", "time.time", "colorlog.ColoredFormatter" ]
[((1136, 1159), 'logging.getLogger', 'logging.getLogger', (['name'], {}), '(name)\n', (1153, 1159), False, 'import logging\n'), ((1999, 2022), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (2020, 2022), False, 'import logging\n'), ((2116, 2164), 'logging.addLevelName', 'logging.addLevelName', (['logging.SUCCESS', '"""SUCCESS"""'], {}), "(logging.SUCCESS, 'SUCCESS')\n", (2136, 2164), False, 'import logging\n'), ((3058, 3066), 'functools.wraps', 'wraps', (['f'], {}), '(f)\n', (3063, 3066), False, 'from functools import wraps\n'), ((1737, 1811), 'colorlog.ColoredFormatter', 'ColoredFormatter', (['format_'], {'datefmt': '"""%m/%d %H:%M:%S"""', 'log_colors': 'log_colors'}), "(format_, datefmt='%m/%d %H:%M:%S', log_colors=log_colors)\n", (1753, 1811), False, 'from colorlog import ColoredFormatter\n'), ((1939, 1983), 'logging.Formatter', 'Formatter', (['format_'], {'datefmt': '"""%m/%d %H:%M:%S"""'}), "(format_, datefmt='%m/%d %H:%M:%S')\n", (1948, 1983), False, 'from logging import Formatter\n'), ((3114, 3125), 'time.time', 'time.time', ([], {}), '()\n', (3123, 3125), False, 'import time\n'), ((3177, 3188), 'time.time', 'time.time', ([], {}), '()\n', (3186, 3188), False, 'import time\n')]
# 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 django.urls import reverse from unittest.mock import patch from monitoring.notifications import constants from monitoring.test import helpers INDEX_URL = reverse( constants.URL_PREFIX + 'index') CREATE_URL = reverse( constants.URL_PREFIX + 'notification_create') EDIT_URL = reverse( constants.URL_PREFIX + 'notification_edit', args=('12345',)) class AlarmsTest(helpers.TestCase): def test_index(self): with patch('monitoring.api.monitor', **{ 'spec_set': ['notification_list'], 'notification_list.return_value': [], }) as mock: res = self.client.get(INDEX_URL) self.assertEqual(mock.notification_list.call_count, 2) self.assertTemplateUsed( res, 'monitoring/notifications/index.html') def test_notifications_create(self): with patch('monitoring.api.monitor', **{ 'spec_set': ['notification_type_list'], 'notification_type_list.return_value': [], }) as mock: res = self.client.get(CREATE_URL) self.assertEqual(mock. notification_type_list.call_count, 1) self.assertTemplateUsed( res, 'monitoring/notifications/_create.html') def test_notifications_edit(self): with patch('monitoring.api.monitor', **{ 'spec_set': ['notification_get', 'notification_type_list'], 'notification_get.return_value': { 'alarm_actions': [] }, 'notification_type_list.return_value': [], }) as mock: res = self.client.get(EDIT_URL) self.assertEqual(mock.notification_get.call_count, 1) self.assertEqual(mock.notification_type_list.call_count, 1) self.assertTemplateUsed( res, 'monitoring/notifications/_edit.html')
[ "unittest.mock.patch", "django.urls.reverse" ]
[((717, 756), 'django.urls.reverse', 'reverse', (["(constants.URL_PREFIX + 'index')"], {}), "(constants.URL_PREFIX + 'index')\n", (724, 756), False, 'from django.urls import reverse\n'), ((775, 828), 'django.urls.reverse', 'reverse', (["(constants.URL_PREFIX + 'notification_create')"], {}), "(constants.URL_PREFIX + 'notification_create')\n", (782, 828), False, 'from django.urls import reverse\n'), ((845, 913), 'django.urls.reverse', 'reverse', (["(constants.URL_PREFIX + 'notification_edit')"], {'args': "('12345',)"}), "(constants.URL_PREFIX + 'notification_edit', args=('12345',))\n", (852, 913), False, 'from django.urls import reverse\n'), ((997, 1109), 'unittest.mock.patch', 'patch', (['"""monitoring.api.monitor"""'], {}), "('monitoring.api.monitor', **{'spec_set': ['notification_list'],\n 'notification_list.return_value': []})\n", (1002, 1109), False, 'from unittest.mock import patch\n'), ((1407, 1529), 'unittest.mock.patch', 'patch', (['"""monitoring.api.monitor"""'], {}), "('monitoring.api.monitor', **{'spec_set': ['notification_type_list'],\n 'notification_type_list.return_value': []})\n", (1412, 1529), False, 'from unittest.mock import patch\n'), ((1834, 2037), 'unittest.mock.patch', 'patch', (['"""monitoring.api.monitor"""'], {}), "('monitoring.api.monitor', **{'spec_set': ['notification_get',\n 'notification_type_list'], 'notification_get.return_value': {\n 'alarm_actions': []}, 'notification_type_list.return_value': []})\n", (1839, 2037), False, 'from unittest.mock import patch\n')]
# Copyright (c) 2014 Evalf # # 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. """ The matrix module defines an abstract :class:`Matrix` object and several implementations. Matrix objects support basic addition and subtraction operations and provide a consistent insterface for solving linear systems. Matrices can be converted into other forms suitable for external processing via the ``export`` method. """ from . import numpy, numeric, warnings, cache, types, config, util import abc, sys, ctypes, treelog as log class MatrixError(Exception): pass class Backend(metaclass=abc.ABCMeta): 'backend base class' def __enter__(self): if hasattr(self, '_old_backend'): raise RuntimeError('This context manager is not reentrant.') global _current_backend self._old_backend = _current_backend _current_backend = self return self def __exit__(self, etype, value, tb): if not hasattr(self, '_old_backend'): raise RuntimeError('This context manager is not yet entered.') global _current_backend _current_backend = self._old_backend del self._old_backend @abc.abstractmethod def assemble(self, data, index, shape): '''Assemble a (sparse) tensor based on index-value pairs. .. Note:: This function is abstract. ''' class Matrix(metaclass=types.CacheMeta): 'matrix base class' def __init__(self, shape): assert len(shape) == 2 self.shape = shape @abc.abstractmethod def __add__(self, other): 'add two matrices' @abc.abstractmethod def __mul__(self, other): 'multiply matrix with a scalar' @abc.abstractmethod def __neg__(self, other): 'negate matrix' def __sub__(self, other): return self.__add__(-other) def __rmul__(self, other): return self.__mul__(other) def __truediv__(self, other): return self.__mul__(1/other) @property @abc.abstractmethod def T(self): 'transpose matrix' @property def size(self): return numpy.prod(self.shape) def rowsupp(self, tol=0): 'return row indices with nonzero/non-small entries' data, (row, col) = self.export('coo') supp = numpy.zeros(self.shape[0], dtype=bool) supp[row[abs(data) > tol]] = True return supp @abc.abstractmethod def solve(self, rhs=None, *, lhs0=None, constrain=None, rconstrain=None, **solverargs): '''Solve system given right hand side vector and/or constraints. Args ---- rhs : :class:`float` vector or :any:`None` Right hand side vector. `None` implies all zeros. lhs0 : class:`float` vector or :any:`None` Initial values. `None` implies all zeros. constrain : :class:`float` or :class:`bool` array, or :any:`None` Column constraints. For float values, a number signifies a constraint, NaN signifies a free dof. For boolean, a True value signifies a constraint to the value in `lhs0`, a False value signifies a free dof. `None` implies no constraints. rconstrain : :class:`bool` array or :any:`None` Row constrains. A True value signifies a constrains, a False value a free dof. `None` implies that the constraints follow those defined in `constrain` (by implication the matrix must be square). Returns ------- :class:`numpy.ndarray` Left hand side vector. ''' @abc.abstractmethod def submatrix(self, rows, cols): '''Create submatrix from selected rows, columns. Args ---- rows : :class:`bool`/:class:`int` array selecting rows for keeping cols : :class:`bool`/:class:`int` array selecting columns for keeping Returns ------- :class:`Matrix` Matrix instance of reduced dimensions ''' def export(self, form): '''Export matrix data to any of supported forms. Args ---- form : :class:`str` - "dense" : return matrix as a single dense array - "csr" : return matrix as 3-tuple of (data, indices, indptr) - "coo" : return matrix as 2-tuple of (data, (row, col)) ''' raise NotImplementedError('cannot export {} to {!r}'.format(self.__class__.__name__, form)) def __repr__(self): return '{}<{}x{}>'.format(type(self).__qualname__, *self.shape) def preparesolvearguments(wrapped): '''Make rhs optional, add lhs0, constrain, rconstrain arguments. See Matrix.solve.''' def solve(self, rhs=None, *, lhs0=None, constrain=None, rconstrain=None, **solverargs): nrows, ncols = self.shape if lhs0 is None: x = numpy.zeros(ncols) else: x = numpy.array(lhs0, dtype=float) assert x.shape == (ncols,) if constrain is None: J = numpy.ones(ncols, dtype=bool) else: assert constrain.shape == (ncols,) if constrain.dtype == bool: J = ~constrain else: J = numpy.isnan(constrain) x[~J] = constrain[~J] if rconstrain is None: assert nrows == ncols I = J else: assert rconstrain.shape == (nrows,) and constrain.dtype == bool I = ~rconstrain assert I.sum() == J.sum(), 'constrained matrix is not square: {}x{}'.format(I.sum(), J.sum()) if rhs is None: rhs = 0. b = (rhs - self.matvec(x))[J] if b.any(): x[J] += wrapped(self if I.all() and J.all() else self.submatrix(I, J), b, **solverargs) if not numpy.isfinite(x).all(): raise MatrixError('solver returned non-finite left hand side') log.info('solver returned with residual {:.0e}'.format(numpy.linalg.norm((rhs - self.matvec(x))[J]))) else: log.info('skipping solver because initial vector is exact') return x return log.withcontext(solve) ## NUMPY BACKEND class Numpy(Backend): '''matrix backend based on numpy array''' def assemble(self, data, index, shape): array = numeric.accumulate(data, index, shape) return NumpyMatrix(array) if len(shape) == 2 else array class NumpyMatrix(Matrix): '''matrix based on numpy array''' def __init__(self, core): assert numeric.isarray(core) self.core = core super().__init__(core.shape) def __add__(self, other): if not isinstance(other, NumpyMatrix) or self.shape != other.shape: return NotImplemented return NumpyMatrix(self.core + other.core) def __mul__(self, other): if not numeric.isnumber(other): return NotImplemented return NumpyMatrix(self.core * other) def __neg__(self): return NumpyMatrix(-self.core) @property def T(self): return NumpyMatrix(self.core.T) def matvec(self, vec): return numpy.dot(self.core, vec) def export(self, form): if form == 'dense': return self.core if form == 'coo': ij = self.core.nonzero() return self.core[ij], ij if form == 'csr': rows, cols = self.core.nonzero() return self.core[rows, cols], cols, rows.searchsorted(numpy.arange(self.shape[0]+1)) raise NotImplementedError('cannot export NumpyMatrix to {!r}'.format(form)) def rowsupp(self, tol=0): return numpy.greater(abs(self.core), tol).any(axis=1) @preparesolvearguments def solve(self, rhs): try: return numpy.linalg.solve(self.core, rhs) except numpy.linalg.LinAlgError as e: raise MatrixError(e) from e def submatrix(self, rows, cols): return NumpyMatrix(self.core[numpy.ix_(rows, cols)]) ## SCIPY BACKEND try: import scipy.sparse.linalg except ImportError: pass else: class Scipy(Backend): '''matrix backend based on scipy's sparse matrices''' def assemble(self, data, index, shape): if len(shape) < 2: return numeric.accumulate(data, index, shape) if len(shape) == 2: csr = scipy.sparse.csr_matrix((data, index), shape) return ScipyMatrix(csr) raise MatrixError('{}d data not supported by scipy backend'.format(len(shape))) class ScipyMatrix(Matrix): '''matrix based on any of scipy's sparse matrices''' def __init__(self, core): self.core = core super().__init__(core.shape) def __add__(self, other): if not isinstance(other, ScipyMatrix) or self.shape != other.shape: return NotImplemented return ScipyMatrix(self.core + other.core) def __sub__(self, other): if not isinstance(other, ScipyMatrix) or self.shape != other.shape: return NotImplemented return ScipyMatrix(self.core - other.core) def __mul__(self, other): if not numeric.isnumber(other): return NotImplemented return ScipyMatrix(self.core * other) def __neg__(self): return ScipyMatrix(-self.core) def matvec(self, vec): return self.core.dot(vec) def export(self, form): if form == 'dense': return self.core.toarray() if form == 'csr': csr = self.core.tocsr() return csr.data, csr.indices, csr.indptr if form == 'coo': coo = self.core.tocoo() return coo.data, (coo.row, coo.col) raise NotImplementedError('cannot export NumpyMatrix to {!r}'.format(form)) @property def T(self): return ScipyMatrix(self.core.transpose()) @preparesolvearguments def solve(self, rhs, atol=0, solver='spsolve', callback=None, precon=None, **solverargs): if solver == 'spsolve': log.info('solving system using sparse direct solver') return scipy.sparse.linalg.spsolve(self.core, rhs) assert atol, 'tolerance must be specified for iterative solver' rhsnorm = numpy.linalg.norm(rhs) if rhsnorm <= atol: return numpy.zeros(self.shape[1]) log.info('solving system using {} iterative solver'.format(solver)) solverfun = getattr(scipy.sparse.linalg, solver) myrhs = rhs / rhsnorm # normalize right hand side vector for best control over scipy's stopping criterion mytol = atol / rhsnorm niter = numpy.array(0) def mycallback(arg): niter[...] += 1 # some solvers provide the residual, others the left hand side vector res = numpy.linalg.norm(myrhs - self.matvec(arg)) if numpy.ndim(arg) == 1 else float(arg) if callback: callback(res) with log.context('residual {:.2e} ({:.0f}%)'.format(res, 100. * numpy.log10(res) / numpy.log10(mytol) if res > 0 else 0)): pass M = self.getprecon(precon) if isinstance(precon, str) else precon(self.core) if callable(precon) else precon mylhs, status = solverfun(self.core, myrhs, M=M, tol=mytol, callback=mycallback, **solverargs) if status != 0: raise MatrixError('{} solver failed with status {}'.format(solver, status)) log.info('solver converged in {} iterations'.format(niter)) return mylhs * rhsnorm def getprecon(self, name): name = name.lower() assert self.shape[0] == self.shape[1], 'constrained matrix must be square' log.info('building {} preconditioner'.format(name)) if name == 'splu': try: precon = scipy.sparse.linalg.splu(self.core.tocsc()).solve except RuntimeError as e: raise MatrixError(e) from e elif name == 'spilu': try: precon = scipy.sparse.linalg.spilu(self.core.tocsc(), drop_tol=1e-5, fill_factor=None, drop_rule=None, permc_spec=None, diag_pivot_thresh=None, relax=None, panel_size=None, options=None).solve except RuntimeError as e: raise MatrixError(e) from e elif name == 'diag': diag = self.core.diagonal() if not diag.all(): raise MatrixError("building 'diag' preconditioner: diagonal has zero entries") precon = numpy.reciprocal(diag).__mul__ else: raise MatrixError('invalid preconditioner {!r}'.format(name)) return scipy.sparse.linalg.LinearOperator(self.shape, precon, dtype=float) def submatrix(self, rows, cols): return ScipyMatrix(self.core[rows,:][:,cols]) ## INTEL MKL BACKEND libmkl = util.loadlib(linux='libmkl_rt.so', darwin='libmkl_rt.dylib', win32='mkl_rt.dll') if libmkl is not None: # typedefs c_int = types.c_array[numpy.int32] c_long = types.c_array[numpy.int64] c_double = types.c_array[numpy.float64] libtbb = util.loadlib(linux='libtbb.so.2', darwin='libtbb.dylib', win32='tbb.dll') class MKL(Backend): '''matrix backend based on Intel's Math Kernel Library''' def __enter__(self): super().__enter__() usethreads = config.nprocs > 1 libmkl.mkl_set_threading_layer(c_long(4 if usethreads else 1)) # 1:SEQUENTIAL, 4:TBB if usethreads and libtbb: self.tbbhandle = ctypes.c_void_p() libtbb._ZN3tbb19task_scheduler_init10initializeEim(ctypes.byref(self.tbbhandle), ctypes.c_int(config.nprocs), ctypes.c_int(2)) else: self.tbbhandle = None return self def __exit__(self, etype, value, tb): if self.tbbhandle: libtbb._ZN3tbb19task_scheduler_init9terminateEv(ctypes.byref(self.tbbhandle)) super().__exit__(etype, value, tb) @staticmethod def assemble(data, index, shape): if len(shape) < 2: return numeric.accumulate(data, index, shape) if len(shape) == 2: return MKLMatrix(data, index, shape) raise MatrixError('{}d data not supported by scipy backend'.format(len(shape))) class Pardiso: '''simple wrapper for libmkl.pardiso https://software.intel.com/en-us/mkl-developer-reference-c-pardiso ''' _pardiso = libmkl.pardiso _errorcodes = { -1: 'input inconsistent', -2: 'not enough memory', -3: 'reordering problem', -4: 'zero pivot, numerical factorization or iterative refinement problem', -5: 'unclassified (internal) error', -6: 'reordering failed (matrix types 11 and 13 only)', -7: 'diagonal matrix is singular', -8: '32-bit integer overflow problem', -9: 'not enough memory for OOC', -10: 'error opening OOC files', -11: 'read/write error with OOC files', -12: 'pardiso_64 called from 32-bit library', } def __init__(self): self.pt = numpy.zeros(64, numpy.int64) # handle to data structure @types.apply_annotations def __call__(self, *, phase:c_int, iparm:c_int, maxfct:c_int=1, mnum:c_int=1, mtype:c_int=0, n:c_int=0, a:c_double=None, ia:c_int=None, ja:c_int=None, perm:c_int=None, nrhs:c_int=0, msglvl:c_int=0, b:c_double=None, x:c_double=None): error = ctypes.c_int32(1) self._pardiso(self.pt.ctypes, maxfct, mnum, mtype, phase, n, a, ia, ja, perm, nrhs, iparm, msglvl, b, x, ctypes.byref(error)) if error.value: raise MatrixError(self._errorcodes.get(error.value, 'unknown error {}'.format(error.value))) def __del__(self): if self.pt.any(): # release all internal memory for all matrices self(phase=-1, iparm=numpy.zeros(64, dtype=numpy.int32)) assert not self.pt.any(), 'it appears that Pardiso failed to release its internal memory' class MKLMatrix(Matrix): '''matrix implementation based on sorted coo data''' __cache__ = 'indptr', _factors = False def __init__(self, data, index, shape): assert index.shape == (2, len(data)) if len(data): # sort rows, columns reorder = numpy.lexsort(index[::-1]) index = index[:,reorder] data = data[reorder] # sum duplicate entries keep = numpy.empty(len(reorder), dtype=bool) keep[0] = True numpy.not_equal(index[:,1:], index[:,:-1]).any(axis=0, out=keep[1:]) if not keep.all(): index = index[:,keep] data = numeric.accumulate(data, [keep.cumsum()-1], [index.shape[1]]) if not data.all(): nz = data.astype(bool) data = data[nz] index = index[:,nz] self.data = numpy.ascontiguousarray(data, dtype=numpy.float64) self.index = numpy.ascontiguousarray(index, dtype=numpy.int32) super().__init__(shape) @property def indptr(self): return self.index[0].searchsorted(numpy.arange(self.shape[0]+1)).astype(numpy.int32, copy=False) def __add__(self, other): if not isinstance(other, MKLMatrix) or self.shape != other.shape: return NotImplemented return MKLMatrix(numpy.concatenate([self.data, other.data]), numpy.concatenate([self.index, other.index], axis=1), self.shape) def __sub__(self, other): if not isinstance(other, MKLMatrix) or self.shape != other.shape: return NotImplemented return MKLMatrix(numpy.concatenate([self.data, -other.data]), numpy.concatenate([self.index, other.index], axis=1), self.shape) def __mul__(self, other): if not numeric.isnumber(other): return NotImplemented return MKLMatrix(self.data * other, self.index, self.shape) def __neg__(self): return MKLMatrix(-self.data, self.index, self.shape) @property def T(self): return MKLMatrix(self.data, self.index[::-1], self.shape[::-1]) def matvec(self, vec): rows, cols = self.index return numeric.accumulate(self.data * vec[cols], [rows], [self.shape[0]]) def export(self, form): if form == 'dense': return numeric.accumulate(self.data, self.index, self.shape) if form == 'csr': return self.data, self.index[1], self.indptr if form == 'coo': return self.data, self.index raise NotImplementedError('cannot export MKLMatrix to {!r}'.format(form)) def submatrix(self, rows, cols): I, J = self.index keep = numpy.logical_and(rows[I], cols[J]) csI = rows.cumsum() csJ = cols.cumsum() return MKLMatrix(self.data[keep], numpy.array([csI[I[keep]]-1, csJ[J[keep]]-1]), shape=(csI[-1], csJ[-1])) @preparesolvearguments def solve(self, rhs): log.info('solving {0}x{0} system using MKL Pardiso'.format(self.shape[0])) if self._factors: log.info('reusing existing factorization') pardiso, iparm, mtype = self._factors phase = 33 # solve, iterative refinement else: pardiso = Pardiso() iparm = numpy.zeros(64, dtype=numpy.int32) # https://software.intel.com/en-us/mkl-developer-reference-c-pardiso-iparm-parameter iparm[0] = 1 # supply all values in components iparm[1:64] iparm[1] = 2 # fill-in reducing ordering for the input matrix: nested dissection algorithm from the METIS package iparm[9] = 13 # pivoting perturbation threshold 1e-13 (default for nonsymmetric) iparm[10] = 1 # enable scaling vectors (default for nonsymmetric) iparm[12] = 1 # enable improved accuracy using (non-) symmetric weighted matching (default for nonsymmetric) iparm[34] = 1 # zero base indexing mtype = 11 # real and nonsymmetric phase = 13 # analysis, numerical factorization, solve, iterative refinement self._factors = pardiso, iparm, mtype lhs = numpy.empty(self.shape[1], dtype=numpy.float64) pardiso(phase=phase, mtype=mtype, iparm=iparm, n=self.shape[0], nrhs=1, b=rhs, x=lhs, a=self.data, ia=self.indptr, ja=self.index[1]) return lhs ## MODULE METHODS _current_backend = Numpy() def backend(names): for name in names.lower().split(','): for cls in Backend.__subclasses__(): if cls.__name__.lower() == name: return cls() raise RuntimeError('matrix backend {!r} is not available'.format(names)) def assemble(data, index, shape): return _current_backend.assemble(data, index, shape) def diag(d): assert d.ndim == 1 return assemble(d, index=numpy.arange(len(d))[numpy.newaxis].repeat(2, axis=0), shape=d.shape*2) def eye(n): return diag(numpy.ones(n)) # vim:sw=2:sts=2:et
[ "ctypes.byref", "ctypes.c_int32", "treelog.info", "treelog.withcontext", "ctypes.c_void_p", "ctypes.c_int" ]
[((6603, 6625), 'treelog.withcontext', 'log.withcontext', (['solve'], {}), '(solve)\n', (6618, 6625), True, 'import abc, sys, ctypes, treelog as log\n'), ((6521, 6580), 'treelog.info', 'log.info', (['"""skipping solver because initial vector is exact"""'], {}), "('skipping solver because initial vector is exact')\n", (6529, 6580), True, 'import abc, sys, ctypes, treelog as log\n'), ((15302, 15319), 'ctypes.c_int32', 'ctypes.c_int32', (['(1)'], {}), '(1)\n', (15316, 15319), False, 'import abc, sys, ctypes, treelog as log\n'), ((10217, 10270), 'treelog.info', 'log.info', (['"""solving system using sparse direct solver"""'], {}), "('solving system using sparse direct solver')\n", (10225, 10270), True, 'import abc, sys, ctypes, treelog as log\n'), ((13489, 13506), 'ctypes.c_void_p', 'ctypes.c_void_p', ([], {}), '()\n', (13504, 13506), False, 'import abc, sys, ctypes, treelog as log\n'), ((15431, 15450), 'ctypes.byref', 'ctypes.byref', (['error'], {}), '(error)\n', (15443, 15450), False, 'import abc, sys, ctypes, treelog as log\n'), ((18764, 18806), 'treelog.info', 'log.info', (['"""reusing existing factorization"""'], {}), "('reusing existing factorization')\n", (18772, 18806), True, 'import abc, sys, ctypes, treelog as log\n'), ((13566, 13594), 'ctypes.byref', 'ctypes.byref', (['self.tbbhandle'], {}), '(self.tbbhandle)\n', (13578, 13594), False, 'import abc, sys, ctypes, treelog as log\n'), ((13596, 13623), 'ctypes.c_int', 'ctypes.c_int', (['config.nprocs'], {}), '(config.nprocs)\n', (13608, 13623), False, 'import abc, sys, ctypes, treelog as log\n'), ((13625, 13640), 'ctypes.c_int', 'ctypes.c_int', (['(2)'], {}), '(2)\n', (13637, 13640), False, 'import abc, sys, ctypes, treelog as log\n'), ((13826, 13854), 'ctypes.byref', 'ctypes.byref', (['self.tbbhandle'], {}), '(self.tbbhandle)\n', (13838, 13854), False, 'import abc, sys, ctypes, treelog as log\n')]
"""Plaza Items (in particular, Things and Rooms) representing the setting of Lost One.""" __author__ = '<NAME>' __copyright__ = 'Copyright 2011 <NAME>' __license__ = 'ISC' __version__ = '0.5.0.0' __status__ = 'Development' from item_model import Room, Thing items = [ Room('@plaza_center', article='the', called='center of the plaza', referring='center broad plaza of | plaza americas center middle', sight=""" [*'s] senses [hum/ing/2/v] as [*/s] [view/v] [@plaza_center/o] the morning [conclude/1/ed/v] it [is/1/v] midday [now] """, exits={ 'north':'@plaza_n', 'northeast':'@plaza_ne', 'east':'@plaza_e', 'southeast':'@plaza_se', 'south':'@plaza_s', 'southwest':'@plaza_sw', 'west':'@plaza_w', 'northwest':'@plaza_nw'}, view={ '@plaza_n': (.5, 'to the north'), '@plaza_ne': (.5, 'to the northeast'), '@plaza_e': (.5, 'to the east'), '@plaza_se': (.5, 'to the southeast'), '@plaza_s': (.5, 'to the south'), '@plaza_sw': (.5, 'to the southwest'), '@plaza_w': (.5, 'to the west'), '@plaza_nw': (.5, 'to the northwest')}), Room('@plaza_n', article='the', called='northern area', referring='broad plaza of northern | plaza americas part expanse space', sight=""" the space north of the plaza's center, which [is/1/v] particularly barren of vegetation and ornament""", exits={ 'east':'@plaza_ne', 'southeast':'@plaza_e', 'south':'@plaza_center', 'west':'@plaza_nw', 'southwest':'@plaza_w',}, view={ '@plaza_ne': (.5, 'to the east'), '@plaza_e': (.5, 'to the southeast'), '@plaza_center': (.5, 'to the south'), '@plaza_nw': (.5, 'to the west'), '@plaza_w': (.5, 'to the southwest'), '@plaza_se': (.25, 'off toward the southeast'), '@plaza_s': (.25, 'across the plaza'), '@plaza_sw': (.25, 'off toward the southwest')}), Thing('@rock in @plaza_n', article='a', called=' rock', referring='fist-sized fist sized | rock stone', sight='a fist-sized rock', prominence=0.3), Thing('@statue part_of @plaza_n', article='a', called='statue', referring='marble | likeness Einstein', sight=""" [*/s] [see/v] a marble likeness of Einstein there [is/1/v] almost no hint [here] of the playful, disheveled scientist so often seen in the photographs that were popular in the early twenty-first century""", qualities=['stone'], prominence=0.8), Room('@plaza_ne', article='the', called='northeastern area', referring=('broad of northeastern | plaza americas part side ' + 'expanse space'), sight="the space northeast of the plaza's center", exits={ 'south':'@plaza_e', 'southwest':'@plaza_center', 'west':'@plaza_n'}, view={ '@plaza_e': (.5, 'to the south'), '@plaza_center': (.5, 'to the southwest'), '@plaza_n': (.5, 'to the west'), '@plaza_nw': (.25, 'to the far west'), '@plaza_w': (.25, 'off toward the west'), '@plaza_sw': (.25, 'across the plaza'), '@plaza_s': (.25, 'off toward the south'), '@plaza_se': (.25, 'to the far south')}), Room('@plaza_e', article='the', called='eastern area', referring='broad of eastern | plaza americas part side expanse space', sight="the space east of the plaza's center", exits={ 'north':'@plaza_ne', 'south':'@plaza_se', 'southwest':'@plaza_s', 'west':'@plaza_center', 'northwest':'@plaza_n'}, view={ '@plaza_ne': (.5, 'to the north'), '@plaza_center': (.5, 'to the west'), '@plaza_se': (.5, 'to the south'), '@plaza_n': (.5, 'to the northwest'), '@plaza_s': (.5, 'to the southwest'), '@plaza_nw': (.25, 'off toward the northwest'), '@plaza_w': (.25, 'across the plaza'), '@plaza_sw': (.25, 'off toward the southwest')}), Thing('@shredded_shirt in @plaza_e', article='a', called='shredded shirt', referring=('shredded torn flesh-colored flesh colored useless of | ' + 'cloth shirt mess'), sight='a useless mess of flesh-colored cloth', qualities=['clothing', 'trash'], prominence=0.3), Thing('@newspaper_sheet in @plaza_e', article='a', called=' newspaper (sheet)', referring='news newspaper | sheet page paper newspaper', sight=""" there [are/2/v] summary texts LEADER WORKING THROUGH NIGHT FOR COUNTRY, MONUMENT NEARS COMPLETION, and PURITY ACCOMPLISHED """, qualities=['trash'], prominence=0.3), Thing('@fountain part_of @plaza_e', article='a', called='fountain', referring='rectangular plain | fountain basin jet', sight='a single jet [fan/1/v] out, feeding a basin', prominence=0.8), Room('@plaza_se', article='the', called='southeastern area', referring=('broad plaza of southeastern | plaza americas part ' + 'expanse space'), sight="the space southeast of the plaza's center", exits={ 'north':'@plaza_e', 'west':'@plaza_s', 'northwest':'@plaza_center'}, view={ '@plaza_e': (.5, 'to the north'), '@plaza_s': (.5, 'to the west'), '@plaza_center': (.5, 'to the northwest'), '@plaza_sw': (.25, 'to the far west'), '@plaza_w': (.25, 'off to the west'), '@plaza_ne': (.25, 'to the far north'), '@plaza_n': (.25, 'off to the north'), '@plaza_nw': (.25, 'across the plaza')}), Thing('@scrap in @plaza_se', article='a', called='plastic scrap', referring='plastic black | scrap', sight='something that was perhaps once part of a black plastic bag', qualities=['trash'], prominence=0.3), Room('@plaza_s', article='the', called='southern area', referring=('broad plaza of southern | plaza americas part ' + 'expanse space'), sight="the space south of the plaza's center", exits={ 'north':'@plaza_center', 'northeast':'@plaza_e', 'northwest':'@plaza_w', 'east':'@plaza_se', 'west':'@plaza_sw'}, view={ '@plaza_se': (.5, 'to the east'), '@plaza_e': (.5, 'to the northeast'), '@plaza_center': (.5, 'to the north'), '@plaza_sw': (.5, 'to the west'), '@plaza_w': (.5, 'to the northwest'), '@plaza_ne': (.25, 'off toward the northeast'), '@plaza_n': (.25, 'across the plaza'), '@plaza_nw': (.25, 'off toward the northwest')}), Thing('@obelisk part_of @plaza_s', article='an', called='obelisk', referring='| obelisk', sight='the stone pointing the way it has for centuries', qualities=['stone'], prominence=1.0), Room('@plaza_sw', article='the', called='southwestern area', referring=('broad plaza of southwestern | plaza americas part ' + 'expanse space'), sight="the space southwest of the plaza's center", exits={ 'north':'@plaza_w', 'northeast':'@plaza_center', 'east':'@plaza_s'}, view={ '@plaza_w': (.5, 'to the north'), '@plaza_s': (.5, 'to the east'), '@plaza_center': (.5, 'to the northeast'), '@plaza_se': (.25, 'to the far east'), '@plaza_e': (.25, 'off to the east'), '@plaza_nw': (.25, 'to the far north'), '@plaza_n': (.25, 'off to the north'), '@plaza_ne': (.25, 'across the plaza')}), Thing('@candy_wrapper in @plaza_sw', article='a', called='candy wrapper', referring="candy commodity's | wrapper husk", sight="a commodity's husk", qualities=['trash'], prominence=0.3), Room('@plaza_w', article='the', called='western area', referring='broad plaza of western | plaza americas part expanse space', sight="the space west of the plaza's center", exits={ 'north':'@plaza_nw', 'east':'@plaza_center', 'south':'@plaza_sw', 'northeast':'@plaza_n', 'southeast':'@plaza_s'}, view={ '@plaza_nw': (.5, 'to the north'), '@plaza_center': (.5, 'to the east'), '@plaza_sw': (.5, 'to the south'), '@plaza_n': (.5, 'to the northeast'), '@plaza_s': (.5, 'to the southeast'), '@plaza_ne': (.25, 'off toward the northeast'), '@plaza_e': (.25, 'across the plaza'), '@plaza_se': (.25, 'off toward the southeast')}), Thing('@smashed_cup in @plaza_w', article='a', called='smashed cup', referring='smashed paper drinking | cup vessel', sight='what was once a paper drinking vessel', qualities=['trash'], prominence=0.3), Thing('@tree part_of @plaza_w', article='a', called='tree', referring='large immense sprawling |', sight='a tree sprawling by itself on the west side of the plaza', prominence=1.0), Room('@plaza_nw', article='the', called='northwestern area', referring=('broad plaza of northwestern | plaza americas part ' + 'expanse space'), sight="the space northwest of the plaza's center", exits={ 'east':'@plaza_n', 'southeast':'@plaza_center', 'south':'@plaza_w'}, view={ '@plaza_w': (.5, 'to the south'), '@plaza_n': (.5, 'to the east'), '@plaza_center': (.5, 'to the southeast'), '@plaza_ne': (.25, 'to the far east'), '@plaza_e': (.25, 'off to the east'), '@plaza_sw': (.25, 'to the far south'), '@plaza_s': (.25, 'off to the south'), '@plaza_se': (.25, 'across the plaza')})]
[ "item_model.Thing", "item_model.Room" ]
[((277, 1126), 'item_model.Room', 'Room', (['"""@plaza_center"""'], {'article': '"""the"""', 'called': '"""center of the plaza"""', 'referring': '"""center broad plaza of | plaza americas center middle"""', 'sight': '"""\n\n [*\'s] senses [hum/ing/2/v] as [*/s] [view/v] [@plaza_center/o]\n\n the morning [conclude/1/ed/v]\n\n it [is/1/v] midday [now]\n """', 'exits': "{'north': '@plaza_n', 'northeast': '@plaza_ne', 'east': '@plaza_e',\n 'southeast': '@plaza_se', 'south': '@plaza_s', 'southwest': '@plaza_sw',\n 'west': '@plaza_w', 'northwest': '@plaza_nw'}", 'view': "{'@plaza_n': (0.5, 'to the north'), '@plaza_ne': (0.5, 'to the northeast'),\n '@plaza_e': (0.5, 'to the east'), '@plaza_se': (0.5, 'to the southeast'\n ), '@plaza_s': (0.5, 'to the south'), '@plaza_sw': (0.5,\n 'to the southwest'), '@plaza_w': (0.5, 'to the west'), '@plaza_nw': (\n 0.5, 'to the northwest')}"}), '(\'@plaza_center\', article=\'the\', called=\'center of the plaza\',\n referring=\'center broad plaza of | plaza americas center middle\', sight\n =\n """\n\n [*\'s] senses [hum/ing/2/v] as [*/s] [view/v] [@plaza_center/o]\n\n the morning [conclude/1/ed/v]\n\n it [is/1/v] midday [now]\n """\n , exits={\'north\': \'@plaza_n\', \'northeast\': \'@plaza_ne\', \'east\':\n \'@plaza_e\', \'southeast\': \'@plaza_se\', \'south\': \'@plaza_s\', \'southwest\':\n \'@plaza_sw\', \'west\': \'@plaza_w\', \'northwest\': \'@plaza_nw\'}, view={\n \'@plaza_n\': (0.5, \'to the north\'), \'@plaza_ne\': (0.5,\n \'to the northeast\'), \'@plaza_e\': (0.5, \'to the east\'), \'@plaza_se\': (\n 0.5, \'to the southeast\'), \'@plaza_s\': (0.5, \'to the south\'),\n \'@plaza_sw\': (0.5, \'to the southwest\'), \'@plaza_w\': (0.5, \'to the west\'\n ), \'@plaza_nw\': (0.5, \'to the northwest\')})\n', (281, 1126), False, 'from item_model import Room, Thing\n'), ((1245, 2015), 'item_model.Room', 'Room', (['"""@plaza_n"""'], {'article': '"""the"""', 'called': '"""northern area"""', 'referring': '"""broad plaza of northern | plaza americas part expanse space"""', 'sight': '"""\n \n the space north of the plaza\'s center, which [is/1/v] particularly \n barren of vegetation and ornament"""', 'exits': "{'east': '@plaza_ne', 'southeast': '@plaza_e', 'south': '@plaza_center',\n 'west': '@plaza_nw', 'southwest': '@plaza_w'}", 'view': "{'@plaza_ne': (0.5, 'to the east'), '@plaza_e': (0.5, 'to the southeast'),\n '@plaza_center': (0.5, 'to the south'), '@plaza_nw': (0.5,\n 'to the west'), '@plaza_w': (0.5, 'to the southwest'), '@plaza_se': (\n 0.25, 'off toward the southeast'), '@plaza_s': (0.25,\n 'across the plaza'), '@plaza_sw': (0.25, 'off toward the southwest')}"}), '(\'@plaza_n\', article=\'the\', called=\'northern area\', referring=\n \'broad plaza of northern | plaza americas part expanse space\', sight=\n """\n \n the space north of the plaza\'s center, which [is/1/v] particularly \n barren of vegetation and ornament"""\n , exits={\'east\': \'@plaza_ne\', \'southeast\': \'@plaza_e\', \'south\':\n \'@plaza_center\', \'west\': \'@plaza_nw\', \'southwest\': \'@plaza_w\'}, view={\n \'@plaza_ne\': (0.5, \'to the east\'), \'@plaza_e\': (0.5, \'to the southeast\'\n ), \'@plaza_center\': (0.5, \'to the south\'), \'@plaza_nw\': (0.5,\n \'to the west\'), \'@plaza_w\': (0.5, \'to the southwest\'), \'@plaza_se\': (\n 0.25, \'off toward the southeast\'), \'@plaza_s\': (0.25,\n \'across the plaza\'), \'@plaza_sw\': (0.25, \'off toward the southwest\')})\n', (1249, 2015), False, 'from item_model import Room, Thing\n'), ((2122, 2277), 'item_model.Thing', 'Thing', (['"""@rock in @plaza_n"""'], {'article': '"""a"""', 'called': '""" rock"""', 'referring': '"""fist-sized fist sized | rock stone"""', 'sight': '"""a fist-sized rock"""', 'prominence': '(0.3)'}), "('@rock in @plaza_n', article='a', called=' rock', referring=\n 'fist-sized fist sized | rock stone', sight='a fist-sized rock',\n prominence=0.3)\n", (2127, 2277), False, 'from item_model import Room, Thing\n'), ((2315, 2739), 'item_model.Thing', 'Thing', (['"""@statue part_of @plaza_n"""'], {'article': '"""a"""', 'called': '"""statue"""', 'referring': '"""marble | likeness Einstein"""', 'sight': '"""\n \n [*/s] [see/v] a marble likeness of Einstein\n \n there [is/1/v] almost no hint [here] of the playful, disheveled \n scientist so often seen in the photographs that were popular in the \n early twenty-first century"""', 'qualities': "['stone']", 'prominence': '(0.8)'}), '(\'@statue part_of @plaza_n\', article=\'a\', called=\'statue\', referring=\n \'marble | likeness Einstein\', sight=\n """\n \n [*/s] [see/v] a marble likeness of Einstein\n \n there [is/1/v] almost no hint [here] of the playful, disheveled \n scientist so often seen in the photographs that were popular in the \n early twenty-first century"""\n , qualities=[\'stone\'], prominence=0.8)\n', (2320, 2739), False, 'from item_model import Room, Thing\n'), ((2783, 3418), 'item_model.Room', 'Room', (['"""@plaza_ne"""'], {'article': '"""the"""', 'called': '"""northeastern area"""', 'referring': "('broad of northeastern | plaza americas part side ' + 'expanse space')", 'sight': '"""the space northeast of the plaza\'s center"""', 'exits': "{'south': '@plaza_e', 'southwest': '@plaza_center', 'west': '@plaza_n'}", 'view': "{'@plaza_e': (0.5, 'to the south'), '@plaza_center': (0.5,\n 'to the southwest'), '@plaza_n': (0.5, 'to the west'), '@plaza_nw': (\n 0.25, 'to the far west'), '@plaza_w': (0.25, 'off toward the west'),\n '@plaza_sw': (0.25, 'across the plaza'), '@plaza_s': (0.25,\n 'off toward the south'), '@plaza_se': (0.25, 'to the far south')}"}), '(\'@plaza_ne\', article=\'the\', called=\'northeastern area\', referring=\n \'broad of northeastern | plaza americas part side \' + \'expanse space\',\n sight="the space northeast of the plaza\'s center", exits={\'south\':\n \'@plaza_e\', \'southwest\': \'@plaza_center\', \'west\': \'@plaza_n\'}, view={\n \'@plaza_e\': (0.5, \'to the south\'), \'@plaza_center\': (0.5,\n \'to the southwest\'), \'@plaza_n\': (0.5, \'to the west\'), \'@plaza_nw\': (\n 0.25, \'to the far west\'), \'@plaza_w\': (0.25, \'off toward the west\'),\n \'@plaza_sw\': (0.25, \'across the plaza\'), \'@plaza_s\': (0.25,\n \'off toward the south\'), \'@plaza_se\': (0.25, \'to the far south\')})\n', (2787, 3418), False, 'from item_model import Room, Thing\n'), ((3531, 4202), 'item_model.Room', 'Room', (['"""@plaza_e"""'], {'article': '"""the"""', 'called': '"""eastern area"""', 'referring': '"""broad of eastern | plaza americas part side expanse space"""', 'sight': '"""the space east of the plaza\'s center"""', 'exits': "{'north': '@plaza_ne', 'south': '@plaza_se', 'southwest': '@plaza_s',\n 'west': '@plaza_center', 'northwest': '@plaza_n'}", 'view': "{'@plaza_ne': (0.5, 'to the north'), '@plaza_center': (0.5, 'to the west'),\n '@plaza_se': (0.5, 'to the south'), '@plaza_n': (0.5,\n 'to the northwest'), '@plaza_s': (0.5, 'to the southwest'), '@plaza_nw':\n (0.25, 'off toward the northwest'), '@plaza_w': (0.25,\n 'across the plaza'), '@plaza_sw': (0.25, 'off toward the southwest')}"}), '(\'@plaza_e\', article=\'the\', called=\'eastern area\', referring=\n \'broad of eastern | plaza americas part side expanse space\', sight=\n "the space east of the plaza\'s center", exits={\'north\': \'@plaza_ne\',\n \'south\': \'@plaza_se\', \'southwest\': \'@plaza_s\', \'west\': \'@plaza_center\',\n \'northwest\': \'@plaza_n\'}, view={\'@plaza_ne\': (0.5, \'to the north\'),\n \'@plaza_center\': (0.5, \'to the west\'), \'@plaza_se\': (0.5,\n \'to the south\'), \'@plaza_n\': (0.5, \'to the northwest\'), \'@plaza_s\': (\n 0.5, \'to the southwest\'), \'@plaza_nw\': (0.25,\n \'off toward the northwest\'), \'@plaza_w\': (0.25, \'across the plaza\'),\n \'@plaza_sw\': (0.25, \'off toward the southwest\')})\n', (3535, 4202), False, 'from item_model import Room, Thing\n'), ((4302, 4574), 'item_model.Thing', 'Thing', (['"""@shredded_shirt in @plaza_e"""'], {'article': '"""a"""', 'called': '"""shredded shirt"""', 'referring': "('shredded torn flesh-colored flesh colored useless of | ' + 'cloth shirt mess'\n )", 'sight': '"""a useless mess of flesh-colored cloth"""', 'qualities': "['clothing', 'trash']", 'prominence': '(0.3)'}), "('@shredded_shirt in @plaza_e', article='a', called='shredded shirt',\n referring='shredded torn flesh-colored flesh colored useless of | ' +\n 'cloth shirt mess', sight='a useless mess of flesh-colored cloth',\n qualities=['clothing', 'trash'], prominence=0.3)\n", (4307, 4574), False, 'from item_model import Room, Thing\n'), ((4642, 5006), 'item_model.Thing', 'Thing', (['"""@newspaper_sheet in @plaza_e"""'], {'article': '"""a"""', 'called': '""" newspaper (sheet)"""', 'referring': '"""news newspaper | sheet page paper newspaper"""', 'sight': '"""\n \n there [are/2/v] summary texts LEADER WORKING THROUGH NIGHT FOR COUNTRY,\n MONUMENT NEARS COMPLETION, and PURITY ACCOMPLISHED\n """', 'qualities': "['trash']", 'prominence': '(0.3)'}), '(\'@newspaper_sheet in @plaza_e\', article=\'a\', called=\n \' newspaper (sheet)\', referring=\n \'news newspaper | sheet page paper newspaper\', sight=\n """\n \n there [are/2/v] summary texts LEADER WORKING THROUGH NIGHT FOR COUNTRY,\n MONUMENT NEARS COMPLETION, and PURITY ACCOMPLISHED\n """\n , qualities=[\'trash\'], prominence=0.3)\n', (4647, 5006), False, 'from item_model import Room, Thing\n'), ((5041, 5238), 'item_model.Thing', 'Thing', (['"""@fountain part_of @plaza_e"""'], {'article': '"""a"""', 'called': '"""fountain"""', 'referring': '"""rectangular plain | fountain basin jet"""', 'sight': '"""a single jet [fan/1/v] out, feeding a basin"""', 'prominence': '(0.8)'}), "('@fountain part_of @plaza_e', article='a', called='fountain',\n referring='rectangular plain | fountain basin jet', sight=\n 'a single jet [fan/1/v] out, feeding a basin', prominence=0.8)\n", (5046, 5238), False, 'from item_model import Room, Thing\n'), ((5276, 5903), 'item_model.Room', 'Room', (['"""@plaza_se"""'], {'article': '"""the"""', 'called': '"""southeastern area"""', 'referring': "('broad plaza of southeastern | plaza americas part ' + 'expanse space')", 'sight': '"""the space southeast of the plaza\'s center"""', 'exits': "{'north': '@plaza_e', 'west': '@plaza_s', 'northwest': '@plaza_center'}", 'view': "{'@plaza_e': (0.5, 'to the north'), '@plaza_s': (0.5, 'to the west'),\n '@plaza_center': (0.5, 'to the northwest'), '@plaza_sw': (0.25,\n 'to the far west'), '@plaza_w': (0.25, 'off to the west'), '@plaza_ne':\n (0.25, 'to the far north'), '@plaza_n': (0.25, 'off to the north'),\n '@plaza_nw': (0.25, 'across the plaza')}"}), '(\'@plaza_se\', article=\'the\', called=\'southeastern area\', referring=\n \'broad plaza of southeastern | plaza americas part \' + \'expanse space\',\n sight="the space southeast of the plaza\'s center", exits={\'north\':\n \'@plaza_e\', \'west\': \'@plaza_s\', \'northwest\': \'@plaza_center\'}, view={\n \'@plaza_e\': (0.5, \'to the north\'), \'@plaza_s\': (0.5, \'to the west\'),\n \'@plaza_center\': (0.5, \'to the northwest\'), \'@plaza_sw\': (0.25,\n \'to the far west\'), \'@plaza_w\': (0.25, \'off to the west\'), \'@plaza_ne\':\n (0.25, \'to the far north\'), \'@plaza_n\': (0.25, \'off to the north\'),\n \'@plaza_nw\': (0.25, \'across the plaza\')})\n', (5280, 5903), False, 'from item_model import Room, Thing\n'), ((6021, 6241), 'item_model.Thing', 'Thing', (['"""@scrap in @plaza_se"""'], {'article': '"""a"""', 'called': '"""plastic scrap"""', 'referring': '"""plastic black | scrap"""', 'sight': '"""something that was perhaps once part of a black plastic bag"""', 'qualities': "['trash']", 'prominence': '(0.3)'}), "('@scrap in @plaza_se', article='a', called='plastic scrap', referring\n ='plastic black | scrap', sight=\n 'something that was perhaps once part of a black plastic bag',\n qualities=['trash'], prominence=0.3)\n", (6026, 6241), False, 'from item_model import Room, Thing\n'), ((6282, 6959), 'item_model.Room', 'Room', (['"""@plaza_s"""'], {'article': '"""the"""', 'called': '"""southern area"""', 'referring': "('broad plaza of southern | plaza americas part ' + 'expanse space')", 'sight': '"""the space south of the plaza\'s center"""', 'exits': "{'north': '@plaza_center', 'northeast': '@plaza_e', 'northwest': '@plaza_w',\n 'east': '@plaza_se', 'west': '@plaza_sw'}", 'view': "{'@plaza_se': (0.5, 'to the east'), '@plaza_e': (0.5, 'to the northeast'),\n '@plaza_center': (0.5, 'to the north'), '@plaza_sw': (0.5,\n 'to the west'), '@plaza_w': (0.5, 'to the northwest'), '@plaza_ne': (\n 0.25, 'off toward the northeast'), '@plaza_n': (0.25,\n 'across the plaza'), '@plaza_nw': (0.25, 'off toward the northwest')}"}), '(\'@plaza_s\', article=\'the\', called=\'southern area\', referring=\n \'broad plaza of southern | plaza americas part \' + \'expanse space\',\n sight="the space south of the plaza\'s center", exits={\'north\':\n \'@plaza_center\', \'northeast\': \'@plaza_e\', \'northwest\': \'@plaza_w\',\n \'east\': \'@plaza_se\', \'west\': \'@plaza_sw\'}, view={\'@plaza_se\': (0.5,\n \'to the east\'), \'@plaza_e\': (0.5, \'to the northeast\'), \'@plaza_center\':\n (0.5, \'to the north\'), \'@plaza_sw\': (0.5, \'to the west\'), \'@plaza_w\': (\n 0.5, \'to the northwest\'), \'@plaza_ne\': (0.25,\n \'off toward the northeast\'), \'@plaza_n\': (0.25, \'across the plaza\'),\n \'@plaza_nw\': (0.25, \'off toward the northwest\')})\n', (6286, 6959), False, 'from item_model import Room, Thing\n'), ((7090, 7286), 'item_model.Thing', 'Thing', (['"""@obelisk part_of @plaza_s"""'], {'article': '"""an"""', 'called': '"""obelisk"""', 'referring': '"""| obelisk"""', 'sight': '"""the stone pointing the way it has for centuries"""', 'qualities': "['stone']", 'prominence': '(1.0)'}), "('@obelisk part_of @plaza_s', article='an', called='obelisk',\n referring='| obelisk', sight=\n 'the stone pointing the way it has for centuries', qualities=['stone'],\n prominence=1.0)\n", (7095, 7286), False, 'from item_model import Room, Thing\n'), ((7328, 7955), 'item_model.Room', 'Room', (['"""@plaza_sw"""'], {'article': '"""the"""', 'called': '"""southwestern area"""', 'referring': "('broad plaza of southwestern | plaza americas part ' + 'expanse space')", 'sight': '"""the space southwest of the plaza\'s center"""', 'exits': "{'north': '@plaza_w', 'northeast': '@plaza_center', 'east': '@plaza_s'}", 'view': "{'@plaza_w': (0.5, 'to the north'), '@plaza_s': (0.5, 'to the east'),\n '@plaza_center': (0.5, 'to the northeast'), '@plaza_se': (0.25,\n 'to the far east'), '@plaza_e': (0.25, 'off to the east'), '@plaza_nw':\n (0.25, 'to the far north'), '@plaza_n': (0.25, 'off to the north'),\n '@plaza_ne': (0.25, 'across the plaza')}"}), '(\'@plaza_sw\', article=\'the\', called=\'southwestern area\', referring=\n \'broad plaza of southwestern | plaza americas part \' + \'expanse space\',\n sight="the space southwest of the plaza\'s center", exits={\'north\':\n \'@plaza_w\', \'northeast\': \'@plaza_center\', \'east\': \'@plaza_s\'}, view={\n \'@plaza_w\': (0.5, \'to the north\'), \'@plaza_s\': (0.5, \'to the east\'),\n \'@plaza_center\': (0.5, \'to the northeast\'), \'@plaza_se\': (0.25,\n \'to the far east\'), \'@plaza_e\': (0.25, \'off to the east\'), \'@plaza_nw\':\n (0.25, \'to the far north\'), \'@plaza_n\': (0.25, \'off to the north\'),\n \'@plaza_ne\': (0.25, \'across the plaza\')})\n', (7332, 7955), False, 'from item_model import Room, Thing\n'), ((8076, 8269), 'item_model.Thing', 'Thing', (['"""@candy_wrapper in @plaza_sw"""'], {'article': '"""a"""', 'called': '"""candy wrapper"""', 'referring': '"""candy commodity\'s | wrapper husk"""', 'sight': '"""a commodity\'s husk"""', 'qualities': "['trash']", 'prominence': '(0.3)'}), '(\'@candy_wrapper in @plaza_sw\', article=\'a\', called=\'candy wrapper\',\n referring="candy commodity\'s | wrapper husk", sight=\n "a commodity\'s husk", qualities=[\'trash\'], prominence=0.3)\n', (8081, 8269), False, 'from item_model import Room, Thing\n'), ((8315, 8987), 'item_model.Room', 'Room', (['"""@plaza_w"""'], {'article': '"""the"""', 'called': '"""western area"""', 'referring': '"""broad plaza of western | plaza americas part expanse space"""', 'sight': '"""the space west of the plaza\'s center"""', 'exits': "{'north': '@plaza_nw', 'east': '@plaza_center', 'south': '@plaza_sw',\n 'northeast': '@plaza_n', 'southeast': '@plaza_s'}", 'view': "{'@plaza_nw': (0.5, 'to the north'), '@plaza_center': (0.5, 'to the east'),\n '@plaza_sw': (0.5, 'to the south'), '@plaza_n': (0.5,\n 'to the northeast'), '@plaza_s': (0.5, 'to the southeast'), '@plaza_ne':\n (0.25, 'off toward the northeast'), '@plaza_e': (0.25,\n 'across the plaza'), '@plaza_se': (0.25, 'off toward the southeast')}"}), '(\'@plaza_w\', article=\'the\', called=\'western area\', referring=\n \'broad plaza of western | plaza americas part expanse space\', sight=\n "the space west of the plaza\'s center", exits={\'north\': \'@plaza_nw\',\n \'east\': \'@plaza_center\', \'south\': \'@plaza_sw\', \'northeast\': \'@plaza_n\',\n \'southeast\': \'@plaza_s\'}, view={\'@plaza_nw\': (0.5, \'to the north\'),\n \'@plaza_center\': (0.5, \'to the east\'), \'@plaza_sw\': (0.5,\n \'to the south\'), \'@plaza_n\': (0.5, \'to the northeast\'), \'@plaza_s\': (\n 0.5, \'to the southeast\'), \'@plaza_ne\': (0.25,\n \'off toward the northeast\'), \'@plaza_e\': (0.25, \'across the plaza\'),\n \'@plaza_se\': (0.25, \'off toward the southeast\')})\n', (8319, 8987), False, 'from item_model import Room, Thing\n'), ((9096, 9310), 'item_model.Thing', 'Thing', (['"""@smashed_cup in @plaza_w"""'], {'article': '"""a"""', 'called': '"""smashed cup"""', 'referring': '"""smashed paper drinking | cup vessel"""', 'sight': '"""what was once a paper drinking vessel"""', 'qualities': "['trash']", 'prominence': '(0.3)'}), "('@smashed_cup in @plaza_w', article='a', called='smashed cup',\n referring='smashed paper drinking | cup vessel', sight=\n 'what was once a paper drinking vessel', qualities=['trash'],\n prominence=0.3)\n", (9101, 9310), False, 'from item_model import Room, Thing\n'), ((9352, 9542), 'item_model.Thing', 'Thing', (['"""@tree part_of @plaza_w"""'], {'article': '"""a"""', 'called': '"""tree"""', 'referring': '"""large immense sprawling |"""', 'sight': '"""a tree sprawling by itself on the west side of the plaza"""', 'prominence': '(1.0)'}), "('@tree part_of @plaza_w', article='a', called='tree', referring=\n 'large immense sprawling |', sight=\n 'a tree sprawling by itself on the west side of the plaza', prominence=1.0)\n", (9357, 9542), False, 'from item_model import Room, Thing\n'), ((9579, 10206), 'item_model.Room', 'Room', (['"""@plaza_nw"""'], {'article': '"""the"""', 'called': '"""northwestern area"""', 'referring': "('broad plaza of northwestern | plaza americas part ' + 'expanse space')", 'sight': '"""the space northwest of the plaza\'s center"""', 'exits': "{'east': '@plaza_n', 'southeast': '@plaza_center', 'south': '@plaza_w'}", 'view': "{'@plaza_w': (0.5, 'to the south'), '@plaza_n': (0.5, 'to the east'),\n '@plaza_center': (0.5, 'to the southeast'), '@plaza_ne': (0.25,\n 'to the far east'), '@plaza_e': (0.25, 'off to the east'), '@plaza_sw':\n (0.25, 'to the far south'), '@plaza_s': (0.25, 'off to the south'),\n '@plaza_se': (0.25, 'across the plaza')}"}), '(\'@plaza_nw\', article=\'the\', called=\'northwestern area\', referring=\n \'broad plaza of northwestern | plaza americas part \' + \'expanse space\',\n sight="the space northwest of the plaza\'s center", exits={\'east\':\n \'@plaza_n\', \'southeast\': \'@plaza_center\', \'south\': \'@plaza_w\'}, view={\n \'@plaza_w\': (0.5, \'to the south\'), \'@plaza_n\': (0.5, \'to the east\'),\n \'@plaza_center\': (0.5, \'to the southeast\'), \'@plaza_ne\': (0.25,\n \'to the far east\'), \'@plaza_e\': (0.25, \'off to the east\'), \'@plaza_sw\':\n (0.25, \'to the far south\'), \'@plaza_s\': (0.25, \'off to the south\'),\n \'@plaza_se\': (0.25, \'across the plaza\')})\n', (9583, 10206), False, 'from item_model import Room, Thing\n')]
from pathlib import Path from typing import List FILE_DIR = Path(__file__).parent def create_boards(boards: List[str]) -> List[str]: defined_boards = [] for board in boards: b = board.split('\n') d_board = [db.split() for db in b] defined_boards.append(d_board) return defined_boards def get_bingo_rankings(boards: List[str], numbers: List[str]): # have a pool of bingo numbers we slowly expand and check, return the first board # that we encounter with all the numbers on a single column or row. Rank boards in # length of the pool of numbers to see which are first, which are last. ranking = {} # exhaustive approach, hopefully pays off for pt2? for ii, board in enumerate(boards): ni = 0 nj = 5 # then we search for where the first number is in any boards, and search along # rows and columns for the remaining numbers. while nj < len(numbers): pool = numbers[ni:nj] for row in board: if set(row).issubset(pool): if ii not in ranking.values(): ranking[len(pool)] = ii break t_board = [[board[j][i] for j in range(len(board))] for i in range(len(board[0]))] for row in t_board: if set(row).issubset(pool): if ii not in ranking.values(): ranking[len(pool)] = ii break nj += 1 return ranking def get_unmarked_nums(checklist, board) -> List: nums = [] for row in board: for num in row: if num not in checklist: nums.append(num) return nums if __name__ == "__main__": DATA = (FILE_DIR / "input.txt").read_text().strip() data = [x for x in DATA.split('\n\n')] numbers = data[0].split(",") boards = data[1:] d_boards = create_boards(boards) ranks = get_bingo_rankings(d_boards, numbers) fastest = d_boards[ranks[min(ranks.keys())]] slowest = d_boards[ranks[max(ranks.keys())]] marked1 = numbers[:min(ranks.keys())] marked2 = numbers[:max(ranks.keys())] sol_one = sum([int(x) for x in get_unmarked_nums(marked1, fastest)]) * int(marked1[-1]) print(sol_one) #72770 sol_two = sum([int(x) for x in get_unmarked_nums(marked2, slowest)]) * int(marked2[-1]) print(sol_two) # 13912
[ "pathlib.Path" ]
[((61, 75), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (65, 75), False, 'from pathlib import Path\n')]
from flask import Flask, render_template, jsonify import random as r import csv app = Flask(__name__) # define global words dictionary words = {} words["easy"] = [] words["medium"] = [] words["hard"] = [] # load words (russian and english) with open('words.csv', newline='\n', encoding="UTF8") as csvfile: wordreader = csv.reader(csvfile, delimiter=';') for row in wordreader: rus = row[0] eng = row[1] if len(rus) <= 4: words["easy"].append((rus, eng)) if len(rus) >= 5 and len(rus) <= 8: words["medium"].append((rus, eng)) if len(rus) > 8: words["hard"].append((rus, eng)) def scramble_word(word): if len(word) == 0: return "" scramble = word l = list(word) while scramble == word: r.shuffle(l) scramble = "".join(l) return scramble @app.route('/') def index(): rand = r.randint(0, len(words["medium"])) word = words["medium"][rand][0] eng = words["medium"][rand][1] scrable = scramble_word(word) result = {"word": word, "scramble": scrable, "eng": eng} return render_template("index.html", result=result) @app.route('/next/<level>') def next(level): l = int(level) word = "" eng = "" if l == 1: rand = r.randint(0, len(words["easy"])) word = words["easy"][rand][0] eng = words["easy"][rand][1] if l == 2: rand = r.randint(0, len(words["medium"])) word = words["medium"][rand][0] eng = words["medium"][rand][1] if l == 3: rand = r.randint(0, len(words["hard"])) word = words["hard"][rand][0] eng = words["hard"][rand][1] scramble = scramble_word(word) result = {"word": word, "scramble": scramble, "eng": eng} return jsonify(result)
[ "flask.render_template", "random.shuffle", "flask.Flask", "csv.reader", "flask.jsonify" ]
[((87, 102), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (92, 102), False, 'from flask import Flask, render_template, jsonify\n'), ((326, 360), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""";"""'}), "(csvfile, delimiter=';')\n", (336, 360), False, 'import csv\n'), ((1122, 1166), 'flask.render_template', 'render_template', (['"""index.html"""'], {'result': 'result'}), "('index.html', result=result)\n", (1137, 1166), False, 'from flask import Flask, render_template, jsonify\n'), ((1788, 1803), 'flask.jsonify', 'jsonify', (['result'], {}), '(result)\n', (1795, 1803), False, 'from flask import Flask, render_template, jsonify\n'), ((805, 817), 'random.shuffle', 'r.shuffle', (['l'], {}), '(l)\n', (814, 817), True, 'import random as r\n')]
from setuptools import setup, find_packages with open("README.md", "r") as fh: long_description = fh.read() setup( name='cexpay', version='2.0.4', description="A support bot for CEX Pay's products. See more https://developers.cexpay.io/.", long_description=long_description, long_description_content_type="text/markdown", url='https://github.com/cexiolabs/cexpay.support-bot', author='<NAME>', author_email='<EMAIL>', license='Apache-2.0', packages=find_packages(exclude=["*test*"]), install_requires=['requests'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3.10', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Software Development :: Libraries', ], )
[ "setuptools.find_packages" ]
[((495, 528), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "['*test*']"}), "(exclude=['*test*'])\n", (508, 528), False, 'from setuptools import setup, find_packages\n')]
# -*- coding:utf-8 -*- # -------------------------------------------------------- # Copyright (C), 2016-2020, lizhe, All rights reserved # -------------------------------------------------------- # @Name: serial_actions.py # @Author: lizhe # @Created: 2021/5/2 - 0:02 # -------------------------------------------------------- from typing import List from automotive.utils.serial_utils import SerialUtils from automotive.logger.logger import logger from automotive.utils.common.enums import SystemTypeEnum from ..common.interfaces import BaseDevice class SerialActions(BaseDevice): """ 串口操作类 """ def __init__(self, port: str, baud_rate: int): super().__init__() self.__serial = SerialUtils() self.__port = port.upper() self.__baud_rate = baud_rate @property def serial_utils(self): return self.__serial def open(self): """ 打开串口 """ logger.info("初始化串口") logger.info("打开串口") buffer = 32768 self.__serial.connect(port=self.__port, baud_rate=self.__baud_rate) logger.info(f"*************串口初始化成功*************") self.__serial.serial_port.set_buffer(buffer, buffer) logger.info(f"串口缓存为[{buffer}]") def close(self): """ 关闭串口 """ logger.info("关闭串口") self.__serial.disconnect() def write(self, command: str): """ 向串口写入数据 :param command: """ self.__serial.write(command) def read(self) -> str: """ 从串口中读取数据 :return: """ return self.__serial.read() def read_lines(self) -> List[str]: """ 从串口中读取数据,按行来读取 :return: """ return self.__serial.read_lines() def clear_buffer(self): """ 清空串口缓存数据 """ self.read() def file_exist(self, file: str, check_times: int = None, interval: float = 0.5, timeout: int = 10) -> bool: """ 检查文件是否存在 :param file: 文件名(绝对路径) :param check_times: 检查次数 :param interval: 间隔时间 :param timeout: 超时时间 :return: 存在/不存在 """ logger.info(f"检查文件{file}是否存在") return self.__serial.file_exist(file, check_times, interval, timeout) def login(self, username: str, password: str, double_check: bool = False, login_locator: str = "login"): """ 登陆系统 :param username: 用户名 :param password: 密码 :param double_check: 登陆后的二次检查 :param login_locator: 登陆定位符 """ logger.info(f"登陆系统,用户名{username}, 密码{password}") self.__serial.login(username, password, double_check, login_locator) def copy_file(self, remote_folder: str, target_folder: str, system_type: SystemTypeEnum, timeout: float = 300): """ 复制文件 :param remote_folder: 原始文件 :param target_folder: 目标文件夹 :param system_type: 系统类型,目前支持QNX和Linux :param timeout: 超时时间 """ logger.info(f"复制{remote_folder}下面所有的文件到{target_folder}") self.__serial.copy_file(remote_folder, target_folder, system_type, timeout) def check_text(self, contents: str) -> bool: """ 检查是否重启 :param contents: 重启的标识内容 :return: True: 串口输出找到了匹配的内容 False: 串口输出没有找到匹配的内容 """ logger.warning("使用前请调用clear_buffer方法清除缓存") data = self.read() result = True for content in contents: logger.debug(f"现在检查{content}是否在串口数据中存在") result = result and content in data return result
[ "automotive.utils.serial_utils.SerialUtils", "automotive.logger.logger.logger.warning", "automotive.logger.logger.logger.debug", "automotive.logger.logger.logger.info" ]
[((730, 743), 'automotive.utils.serial_utils.SerialUtils', 'SerialUtils', ([], {}), '()\n', (741, 743), False, 'from automotive.utils.serial_utils import SerialUtils\n'), ((954, 974), 'automotive.logger.logger.logger.info', 'logger.info', (['"""初始化串口"""'], {}), "('初始化串口')\n", (965, 974), False, 'from automotive.logger.logger import logger\n'), ((983, 1002), 'automotive.logger.logger.logger.info', 'logger.info', (['"""打开串口"""'], {}), "('打开串口')\n", (994, 1002), False, 'from automotive.logger.logger import logger\n'), ((1110, 1159), 'automotive.logger.logger.logger.info', 'logger.info', (['f"""*************串口初始化成功*************"""'], {}), "(f'*************串口初始化成功*************')\n", (1121, 1159), False, 'from automotive.logger.logger import logger\n'), ((1229, 1260), 'automotive.logger.logger.logger.info', 'logger.info', (['f"""串口缓存为[{buffer}]"""'], {}), "(f'串口缓存为[{buffer}]')\n", (1240, 1260), False, 'from automotive.logger.logger import logger\n'), ((1328, 1347), 'automotive.logger.logger.logger.info', 'logger.info', (['"""关闭串口"""'], {}), "('关闭串口')\n", (1339, 1347), False, 'from automotive.logger.logger import logger\n'), ((2194, 2224), 'automotive.logger.logger.logger.info', 'logger.info', (['f"""检查文件{file}是否存在"""'], {}), "(f'检查文件{file}是否存在')\n", (2205, 2224), False, 'from automotive.logger.logger import logger\n'), ((2594, 2642), 'automotive.logger.logger.logger.info', 'logger.info', (['f"""登陆系统,用户名{username}, 密码{password}"""'], {}), "(f'登陆系统,用户名{username}, 密码{password}')\n", (2605, 2642), False, 'from automotive.logger.logger import logger\n'), ((3033, 3089), 'automotive.logger.logger.logger.info', 'logger.info', (['f"""复制{remote_folder}下面所有的文件到{target_folder}"""'], {}), "(f'复制{remote_folder}下面所有的文件到{target_folder}')\n", (3044, 3089), False, 'from automotive.logger.logger import logger\n'), ((3385, 3427), 'automotive.logger.logger.logger.warning', 'logger.warning', (['"""使用前请调用clear_buffer方法清除缓存"""'], {}), "('使用前请调用clear_buffer方法清除缓存')\n", (3399, 3427), False, 'from automotive.logger.logger import logger\n'), ((3522, 3562), 'automotive.logger.logger.logger.debug', 'logger.debug', (['f"""现在检查{content}是否在串口数据中存在"""'], {}), "(f'现在检查{content}是否在串口数据中存在')\n", (3534, 3562), False, 'from automotive.logger.logger import logger\n')]
import xml.etree.ElementTree as ElementTree import os class CARISObject: """A generic CARIS object with a name""" def __init__(self): """Initialize with empty name""" self.name = '' def __init__(self, name): """Initialize with a name provided""" self.name = name def set_name(self, name): """Set the name""" if name: self.name = name def get_name(self): """Return the name""" return self.name class CARISSource(CARISObject): """A CARIS source object under Process Model 1.0""" def __init__(self): """Initialize with empty name, type and data""" self.name = '' self.stype = '' self.sdata = '' def set_type(self, dtype): """Set the type""" if dtype: self.stype = dtype def set_data(self, data): """Set the data""" if data: self.sdata = data def get_type(self): """Return the type""" return self.stype def get_data(self): """Return the data""" return self.sdata class CARISLog(): """A CARIS log object under Process Model 1.0""" def __init__(self): """Initialize with empty user, software, start/end times""" self.user = '' self.software = '' self.startTime = '' self.endTime = '' def set_user(self, user): """Set the user""" if user: self.user = user def set_software(self, software): """Set the software""" if software: self.software = software def set_start_time(self, startTime): """Set the start time""" if startTime: self.startTime = startTime def set_end_time(self, endTime): """Set the end time""" if endTime: self.endTime = endTime def get_user(self): """Return the user""" return self.user def get_software(self): """Return the software""" return self.software def get_start_time(self): """Return the start time""" return self.startTime def get_end_time(self): """Return the end time""" return self.endTime class CARISPort(CARISObject): """A CARIS port under Process Model 1.0""" def __init__(self): """Initialize with empty name and sources list""" self.name = '' self.sources = [] def set_sources(self, sources): """Set the sources list""" if sources: self.sources = sources def get_sources(self): """Get the sources list""" return self.sources def get_source(self, index): """Get a source by index""" return self.sources[index] class CARISProcess(CARISObject): """ A CARIS Process under Process Model 1.0""" def __init__(self): """Initialize with empty name, version, ports dictionary, and log list""" self.name = '' self.version = '' self.ports = {} self.log = [] def set_version(self, version): """Set the version""" if version: self.version = version def set_ports(self, ports): """Set the ports dictionary""" if ports: self.ports = ports def add_port(self, name, port): """Add a port to the dictionary""" if port: self.ports[name] = port def set_log(self, log): """Set the log list""" if log: self.log = log def get_version(self): """Return the version""" return self.version def get_ports(self): """Return the ports dictionary""" return self.ports def get_port(self, name): """Return a port value by key""" return self.ports[name] def get_log(self): """Return the log list""" return self.log class HIPSLog: """ A class representing a HIPS line log. Applicable only for logs created in HIPS v10.0.0 and above (Process.log) """ def __init__(self): """Initialize with empty source path, process list and version""" self.source_path = '' self.processes = [] self.version = '' def __init__(self, log_path): """Initialize from an existing log path, which processes all entries into this object.""" self.source_path = log_path self.processes = [] tree = ElementTree.parse(log_path) root = tree.getroot() self.version = root.find('version').text for process in root.findall('process'): proc_obj = self.__parse_process(process) self.processes.append(proc_obj) def set_source_path(self, path): """Set the source path""" if path: self.source_path = path def set_version(self, version): """Set the version""" if version: self.version = version def set_processes(self, process): """Set the processes list""" if process: self.processes = process def get_source_path(self): """Return the source path""" return self.source_path def get_version(self): """Return the version""" return self.version def get_processes(self): """Return the list of processes""" return self.processes def get_process(self, index): """Return a specific process object by index""" return self.processes[index] def get_last_process(self, process_name): """Returns the last log entry of the provided name.""" return self.get_process(next(i for i, v in zip(list(range(len( self.processes) - 1, -1, -1)), reversed(self.processes)) if v.get_name() == process_name)) def has_process(self, process_name): """Check if the process exists in the log""" return any(process_name in s.get_name() for s in self.processes) def __parse_process(self, process): """Internal process to parse the process XML""" proc_obj = CARISProcess() # set metadata proc_obj.set_name(process.find('id').text) proc_obj.set_version(process.find('version').text) log = process.find('log') log_obj = CARISLog() log_obj.set_user(log.find('user').text) log_obj.set_start_time(log.find('start').text) log_obj.set_end_time(log.find('end').text) soft = log.find('software') log_obj.set_software( soft.find('id').text + ' ' + soft.find('version').text) proc_obj.set_log(log_obj) # add ports for option in process.findall('port'): opt_obj = self.__parse_port(option) proc_obj.add_port(opt_obj.get_name(), opt_obj) return proc_obj def __parse_port(self, option): """Internal process to parse each port (option) of the log entry""" opt_obj = CARISPort() opt_obj.set_name(option.find('id').text) for source in option.findall('source'): src_obj = self.__parse_source(source) opt_obj.sources.append(src_obj) return opt_obj def __parse_source(self, source): """Internal process to parse each source of a given port""" src_obj = CARISSource() data = source.find('data') simple = data.find('simple') if simple: src_obj.set_name('simple') src_obj.set_type(simple.find('type').text) src_obj.set_data(simple.find('value').text) else: complex_v = data.find('complex') if complex_v: src_obj.set_name('complex') src_obj.set_type('complex') # simply store this part of the ETree src_obj.set_data(complex_v) return src_obj
[ "xml.etree.ElementTree.parse" ]
[((4451, 4478), 'xml.etree.ElementTree.parse', 'ElementTree.parse', (['log_path'], {}), '(log_path)\n', (4468, 4478), True, 'import xml.etree.ElementTree as ElementTree\n')]
from django.contrib.auth.decorators import login_required from django.shortcuts import render, get_object_or_404 from .models import BlogPost from .forms import BlogPostModelForm # render intial html page of list of published blogs def blog_post_list_view(request): qs = BlogPost.objects.all().published() # queryset -> list of python objects if request.user.is_authenticated: my_qs = BlogPost.objects.filter(user=request.user) qs = (qs | my_qs).distinct() context = {'object_list':qs} return render(request, 'blog/list.html', context) # create new blog post @login_required def blog_post_create_view(request): form = BlogPostModelForm(request.POST or None, request.FILES or None) if form.is_valid(): obj = form.save(commit=False) obj.user = request.user obj.save() form = BlogPostModelForm() context = {'form':form} return render(request, 'blog/form.html', context) # click on blog 'view' on blog list page to see details of a single blog def blog_post_detail_view(request, slug): obj = get_object_or_404(BlogPost, slug=slug) context = {'object':obj} return render(request, 'blog/detail.html', context) # blog author can update/edit the blog post that user created @login_required def blog_post_update_view(request, slug): obj = get_object_or_404(BlogPost, slug=slug) form = BlogPostModelForm(request.POST or None, instance=obj) if form.is_valid(): form.save() context = { "form":form, "title":f"Update {obj.title}", } return render(request, 'blog/update.html', context) # blog author can delete the blog post that user created @login_required def blog_post_delete_view(request, slug): obj = get_object_or_404(BlogPost, slug=slug) if request.method == "POST": obj.delete() context = {'object':obj} return render(request, 'blog/delete.html', context)
[ "django.shortcuts.render", "django.shortcuts.get_object_or_404" ]
[((526, 568), 'django.shortcuts.render', 'render', (['request', '"""blog/list.html"""', 'context'], {}), "(request, 'blog/list.html', context)\n", (532, 568), False, 'from django.shortcuts import render, get_object_or_404\n'), ((906, 948), 'django.shortcuts.render', 'render', (['request', '"""blog/form.html"""', 'context'], {}), "(request, 'blog/form.html', context)\n", (912, 948), False, 'from django.shortcuts import render, get_object_or_404\n'), ((1075, 1113), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['BlogPost'], {'slug': 'slug'}), '(BlogPost, slug=slug)\n', (1092, 1113), False, 'from django.shortcuts import render, get_object_or_404\n'), ((1154, 1198), 'django.shortcuts.render', 'render', (['request', '"""blog/detail.html"""', 'context'], {}), "(request, 'blog/detail.html', context)\n", (1160, 1198), False, 'from django.shortcuts import render, get_object_or_404\n'), ((1330, 1368), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['BlogPost'], {'slug': 'slug'}), '(BlogPost, slug=slug)\n', (1347, 1368), False, 'from django.shortcuts import render, get_object_or_404\n'), ((1579, 1623), 'django.shortcuts.render', 'render', (['request', '"""blog/update.html"""', 'context'], {}), "(request, 'blog/update.html', context)\n", (1585, 1623), False, 'from django.shortcuts import render, get_object_or_404\n'), ((1750, 1788), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['BlogPost'], {'slug': 'slug'}), '(BlogPost, slug=slug)\n', (1767, 1788), False, 'from django.shortcuts import render, get_object_or_404\n'), ((1883, 1927), 'django.shortcuts.render', 'render', (['request', '"""blog/delete.html"""', 'context'], {}), "(request, 'blog/delete.html', context)\n", (1889, 1927), False, 'from django.shortcuts import render, get_object_or_404\n')]
from PyQt5.QtCore import QTimer, QTime from PyQt5 import QtGui, QtWidgets import time import random import os import datetime import requests import sqlite3 as sql import database_impl as db from date_tools import dt def datetime_diff(old_datetime, new_datetime, dates_are_strings=True): """ String dates should be in this format "%Y-%m-%d %H:%M:%S" """ seconds_in_day = 24 * 60 * 60 if dates_are_strings: d1 = datetime.datetime.strptime(old_datetime, "%Y-%m-%d %H:%M:%S") d2 = datetime.datetime.strptime(new_datetime, "%Y-%m-%d %H:%M:%S") else: d1, d2 = old_datetime, new_datetime difference = d1 - d2 x = divmod(difference.days * seconds_in_day + difference.seconds, 60) minutes, seconds = x[0], x[1] return minutes, seconds def current_time(): t = QTime.currentTime().toString() am_pm = "pm" if 12 < int(t[:2]) < 23 else "am" return t + " " + am_pm def message_discord_server(message, user_data={}): try: discord_webhook_url = user_data['discordwebhook'] Message = { "content": str(message) } requests.post(discord_webhook_url, data=Message) except Exception as e: print("ERROR discord", e) class Presets: def event_log(self, message): t, c = current_time(), self.ui.mouseList.count() self.ui.mouseList.setCurrentRow(c-1) self.ui.mouseLastUpdate.setText(' {}'.format(t)) if c > 100: self.ui.mouseList.clear() self.ui.mouseList.addItem("CLEARED --> {}".format(t)) self.ui.mouseList.takeItem(c-1) self.ui.mouseList.addItem("[{}] {}".format(t, message)) self.ui.mouseList.addItem("") def init_ui(self): self.ui.password.setEchoMode(QtWidgets.QLineEdit.Password) self.ui.bar.setMaximum(100) self.ui.bar.setValue(100) self.setWindowIcon(QtGui.QIcon('images/discord.png')) # Presets.mouse_loop(self) self.ui.close.clicked.connect(lambda: self.close()) self.ui.minimize.clicked.connect(lambda: self.showMinimized()) self.ui.startBtn.clicked.connect(lambda: Presets.start(self)) self.ui.stopBtn.clicked.connect(lambda: Presets.stop(self)) self.ui.password.returnPressed.connect(lambda: Presets.start(self)) self.ui.stopBtn.hide() def progress_bar_count(self): self.ui.SECONDS -= 1 self.ui.bar.setValue(self.ui.SECONDS) def start(self): CON = sql.connect('userData/user.db') if db.valid_login_password(CON, self.ui.password.text(), commit=False) and not db.select_stop_session_status(CON, commit=False): self.ui.user_data = db.user_data_by_password(CON, self.ui.password.text(), commit=False) if self.ui.mins.value() != 0.0 or self.ui.hrs.value() != 0.0: self.ui.start_timer = QTimer() self.ui.start_timer.timeout.connect(lambda: Presets.awake_loop(self)) hrs_to_secs, mins_to_secs = (self.ui.hrs.value() * 60) * 60000, self.ui.mins.value() * 60000 self.ui.start_timer.start(hrs_to_secs + mins_to_secs) self.ui.SECONDS = (hrs_to_secs + mins_to_secs) / 1000 Presets.event_log(self, "Start") Presets.event_log(self, "Interval set to {} minute(s).".format(self.ui.SECONDS / 60)) self.ui.bar.setMaximum(self.ui.SECONDS) self.ui.bar.setValue(self.ui.SECONDS) self.ui.progress_timer = QTimer() self.ui.progress_timer.timeout.connect(lambda: Presets.progress_bar_count(self)) self.ui.progress_timer.start(1000) self.ui.stopBtn.show() self.ui.startBtn.hide() else: Presets.event_log(self, "Set an interval! :)") else: if not db.valid_login_password(CON, self.ui.password.text(), commit=False): Presets.event_log(self, "Enter an application password. :)") if db.select_stop_session_status(CON, commit=False): Presets.event_log(self, "Start live trading session. :)") def stop(self): self.ui.start_timer.stop() self.ui.progress_timer.stop() self.ui.bar.setMaximum(100) self.ui.bar.setValue(100) Presets.event_log(self, "Stop") self.ui.stopBtn.hide() self.ui.startBtn.show() def awake_loop(self): CON = sql.connect('userData/user.db') data = db.get_timestamps_from_livetrade(CON, commit=False) # current set current_min_diff, sec1 = datetime_diff(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), data[-1]) # last set previous_min_diff, sec2 = datetime_diff(data[-1], data[-2]) #second to last set min3, sec3 = datetime_diff(data[-2], data[-3]) message = "_" """ if interval check is greater than min diff then success """ checkup_interval = self.ui.mins.value() + (self.ui.hrs.value() * 60) livetrade_loop_rate = min3 if previous_min_diff == min3 else "unknown" if data[-1] != "2000-01-01 00:00:00": if checkup_interval < current_min_diff: message = "```diff\n-Error! Application stopped live trading!\n-Stoppage occurred after: {}\n``` ".format(data[-1]) elif current_min_diff > previous_min_diff: message = "```ini\n[Warning! Application either slowed down or stopped live trading.]\n[Last loop occurrence: {}]\n``` ".format(data[-1]) else: message = "```diff\n+Success! Application is live trading.\n+Last loop occurrence: {}\n+Live Trade Loop Rate: {} minute(s)``` ".format(data[-1], livetrade_loop_rate) else: lastItem = self.ui.mouseList.currentItem().text() if "bypassing" not in lastItem or "_" not in lastItem: db.drop_table(CON, "live_trade_timestamps", commit=True) db.insert_timestamp_livetrade(CON, data=("2000-01-01 00:00:00", ""), commit=False) db.insert_timestamp_livetrade(CON, data=("2000-01-01 00:00:00", ""), commit=False) db.insert_timestamp_livetrade(CON, data=("2000-01-01 00:00:00", ""), commit=True) message = "Market Closed: bypassing checkup..." Presets.event_log(self, message) if message != "": message_discord_server(message, self.ui.user_data) Presets.event_log(self, "\n"+message.replace("```", "").replace("diff", "").replace("ini", "")) hrs_to_secs, mins_to_secs = (self.ui.hrs.value() * 60) * 60000, self.ui.mins.value() * 60000 self.ui.SECONDS = (hrs_to_secs + mins_to_secs)/1000 self.ui.bar.setMaximum(self.ui.SECONDS) self.ui.bar.setValue(self.ui.SECONDS)
[ "requests.post", "PyQt5.QtGui.QIcon", "sqlite3.connect", "database_impl.select_stop_session_status", "datetime.datetime.strptime", "PyQt5.QtCore.QTime.currentTime", "database_impl.drop_table", "PyQt5.QtCore.QTimer", "database_impl.insert_timestamp_livetrade", "database_impl.get_timestamps_from_liv...
[((441, 502), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['old_datetime', '"""%Y-%m-%d %H:%M:%S"""'], {}), "(old_datetime, '%Y-%m-%d %H:%M:%S')\n", (467, 502), False, 'import datetime\n'), ((516, 577), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['new_datetime', '"""%Y-%m-%d %H:%M:%S"""'], {}), "(new_datetime, '%Y-%m-%d %H:%M:%S')\n", (542, 577), False, 'import datetime\n'), ((1126, 1174), 'requests.post', 'requests.post', (['discord_webhook_url'], {'data': 'Message'}), '(discord_webhook_url, data=Message)\n', (1139, 1174), False, 'import requests\n'), ((2504, 2535), 'sqlite3.connect', 'sql.connect', (['"""userData/user.db"""'], {}), "('userData/user.db')\n", (2515, 2535), True, 'import sqlite3 as sql\n'), ((4475, 4506), 'sqlite3.connect', 'sql.connect', (['"""userData/user.db"""'], {}), "('userData/user.db')\n", (4486, 4506), True, 'import sqlite3 as sql\n'), ((4522, 4573), 'database_impl.get_timestamps_from_livetrade', 'db.get_timestamps_from_livetrade', (['CON'], {'commit': '(False)'}), '(CON, commit=False)\n', (4554, 4573), True, 'import database_impl as db\n'), ((823, 842), 'PyQt5.QtCore.QTime.currentTime', 'QTime.currentTime', ([], {}), '()\n', (840, 842), False, 'from PyQt5.QtCore import QTimer, QTime\n'), ((1912, 1945), 'PyQt5.QtGui.QIcon', 'QtGui.QIcon', (['"""images/discord.png"""'], {}), "('images/discord.png')\n", (1923, 1945), False, 'from PyQt5 import QtGui, QtWidgets\n'), ((4043, 4091), 'database_impl.select_stop_session_status', 'db.select_stop_session_status', (['CON'], {'commit': '(False)'}), '(CON, commit=False)\n', (4072, 4091), True, 'import database_impl as db\n'), ((2623, 2671), 'database_impl.select_stop_session_status', 'db.select_stop_session_status', (['CON'], {'commit': '(False)'}), '(CON, commit=False)\n', (2652, 2671), True, 'import database_impl as db\n'), ((2886, 2894), 'PyQt5.QtCore.QTimer', 'QTimer', ([], {}), '()\n', (2892, 2894), False, 'from PyQt5.QtCore import QTimer, QTime\n'), ((3532, 3540), 'PyQt5.QtCore.QTimer', 'QTimer', ([], {}), '()\n', (3538, 3540), False, 'from PyQt5.QtCore import QTimer, QTime\n'), ((5945, 6001), 'database_impl.drop_table', 'db.drop_table', (['CON', '"""live_trade_timestamps"""'], {'commit': '(True)'}), "(CON, 'live_trade_timestamps', commit=True)\n", (5958, 6001), True, 'import database_impl as db\n'), ((6018, 6105), 'database_impl.insert_timestamp_livetrade', 'db.insert_timestamp_livetrade', (['CON'], {'data': "('2000-01-01 00:00:00', '')", 'commit': '(False)'}), "(CON, data=('2000-01-01 00:00:00', ''), commit\n =False)\n", (6047, 6105), True, 'import database_impl as db\n'), ((6117, 6204), 'database_impl.insert_timestamp_livetrade', 'db.insert_timestamp_livetrade', (['CON'], {'data': "('2000-01-01 00:00:00', '')", 'commit': '(False)'}), "(CON, data=('2000-01-01 00:00:00', ''), commit\n =False)\n", (6146, 6204), True, 'import database_impl as db\n'), ((6216, 6302), 'database_impl.insert_timestamp_livetrade', 'db.insert_timestamp_livetrade', (['CON'], {'data': "('2000-01-01 00:00:00', '')", 'commit': '(True)'}), "(CON, data=('2000-01-01 00:00:00', ''), commit\n =True)\n", (6245, 6302), True, 'import database_impl as db\n'), ((4643, 4666), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (4664, 4666), False, 'import datetime\n')]
from abc import ABCMeta, abstractmethod from functools import partial from typing import Tuple, Union import numexpr import numpy as np from scipy import sparse, special from tabmat import MatrixBase, StandardizedMatrix from ._functions import ( binomial_logit_eta_mu_deviance, binomial_logit_rowwise_gradient_hessian, gamma_deviance, gamma_log_eta_mu_deviance, gamma_log_likelihood, gamma_log_rowwise_gradient_hessian, normal_deviance, normal_identity_eta_mu_deviance, normal_identity_rowwise_gradient_hessian, normal_log_likelihood, poisson_deviance, poisson_log_eta_mu_deviance, poisson_log_likelihood, poisson_log_rowwise_gradient_hessian, tweedie_deviance, tweedie_log_eta_mu_deviance, tweedie_log_likelihood, tweedie_log_rowwise_gradient_hessian, ) from ._link import IdentityLink, Link, LogitLink, LogLink from ._util import _safe_lin_pred, _safe_sandwich_dot class ExponentialDispersionModel(metaclass=ABCMeta): r"""Base class for reproductive Exponential Dispersion Models (EDM). The PDF of :math:`Y \sim \mathrm{EDM}(\mu, \phi)` is given by .. math:: p(y \mid \theta, \phi) &= c(y, \phi) \exp((\theta y - A(\theta)_ / \phi) \\ &= \tilde{c}(y, \phi) \exp(-d(y, \mu) / (2\phi)) with mean :math:`\mathrm{E}(Y) = A'(\theta) = \mu`, variance :math:`\mathrm{var}(Y) = \phi \cdot v(\mu)`, unit variance :math:`v(\mu)` and unit deviance :math:`d(y, \mu)`. Properties ---------- lower_bound upper_bound include_lower_bound include_upper_bound Methods ------- in_y_range unit_variance unit_variance_derivative variance variance_derivative unit_deviance unit_deviance_derivative deviance deviance_derivative starting_mu _mu_deviance_derivative eta_mu_deviance gradient_hessian References ---------- https://en.wikipedia.org/wiki/Exponential_dispersion_model. """ @property @abstractmethod def lower_bound(self) -> float: """Get the lower bound of values for the EDM.""" pass @property @abstractmethod def upper_bound(self) -> float: """Get the upper bound of values for the EDM.""" pass @property def include_lower_bound(self) -> bool: """Return whether ``lower_bound`` is allowed as a value of ``y``.""" pass @property def include_upper_bound(self) -> bool: """Return whether ``upper_bound`` is allowed as a value of ``y``.""" pass def in_y_range(self, x) -> np.ndarray: """Return ``True`` if ``x`` is in the valid range of the EDM. Parameters ---------- x : array-like, shape (n_samples,) Target values. Returns ------- np.ndarray """ if self.include_lower_bound: if self.include_upper_bound: return np.logical_and( np.greater_equal(x, self.lower_bound), np.less_equal(x, self.upper_bound), ) else: return np.logical_and( np.greater_equal(x, self.lower_bound), np.less(x, self.upper_bound) ) else: if self.include_upper_bound: return np.logical_and( np.greater(x, self.lower_bound), np.less_equal(x, self.upper_bound) ) else: return np.logical_and( np.greater(x, self.lower_bound), np.less(x, self.upper_bound) ) @abstractmethod def unit_variance(self, mu): r"""Compute the unit variance function. The unit variance :math:`v(\mu)` determines the variance as a function of the mean :math:`\mu` by :math:`\mathrm{var}(y_i) = (\phi / s_i) \times v(\mu_i)`. It can also be derived from the unit deviance :math:`d(y, \mu)` as .. math:: v(\mu) = \frac{2}{\frac{\partial^2 d(y, \mu)}{\partial\mu^2}}\big|_{y=\mu}. See also :func:`variance`. Parameters ---------- mu : array-like, shape (n_samples,) Predicted mean. """ pass @abstractmethod def unit_variance_derivative(self, mu): r"""Compute the derivative of the unit variance with respect to ``mu``. Return :math:`v'(\mu)`. Parameters ---------- mu : array-like, shape (n_samples,) Predicted mean. """ pass def variance(self, mu: np.ndarray, dispersion=1, sample_weight=1) -> np.ndarray: r"""Compute the variance function. The variance of :math:`Y_i \sim \mathrm{EDM}(\mu_i, \phi / s_i)` is :math:`\mathrm{var}(Y_i) = (\phi / s_i) * v(\mu_i)`, with unit variance :math:`v(\mu)` and weights :math:`s_i`. Parameters ---------- mu : array-like, shape (n_samples,) Predicted mean. dispersion : float, optional (default=1) Dispersion parameter :math:`\phi`. sample_weight : array-like, shape (n_samples,), optional (default=1) Weights or exposure to which variance is inverse proportional. Returns ------- array-like, shape (n_samples,) """ return self.unit_variance(mu) * dispersion / sample_weight def variance_derivative(self, mu, dispersion=1, sample_weight=1): r"""Compute the derivative of the variance with respect to ``mu``. The derivative of the variance is equal to :math:`(\phi / s_i) * v'(\mu_i)`, where :math:`v(\mu)` is the unit variance and :math:`s_i` are weights. Parameters ---------- mu : array-like, shape (n_samples,) Predicted mean. dispersion : float, optional (default=1) Dispersion parameter :math:`\phi`. sample_weight : array-like, shape (n_samples,), optional (default=1) Weights or exposure to which variance is inverse proportional. Returns ------- array-like, shape (n_samples,) """ return self.unit_variance_derivative(mu) * dispersion / sample_weight @abstractmethod def unit_deviance(self, y, mu): r"""Compute the unit deviance. In terms of the log likelihood :math:`L`, the unit deviance is :math:`-2\phi\times [L(y, \mu, \phi) - L(y, y, \phi)].` Parameters ---------- y : array-like, shape (n_samples,) Target values. mu : array-like, shape (n_samples,) Predicted mean. """ pass def unit_deviance_derivative(self, y, mu): r"""Compute the derivative of the unit deviance with respect to ``mu``. The derivative of the unit deviance is given by :math:`-2 \times (y - \mu) / v(\mu)`, where :math:`v(\mu)` is the unit variance. Parameters ---------- y : array-like, shape (n_samples,) Target values. mu : array-like, shape (n_samples,) Predicted mean. Returns ------- array-like, shape (n_samples,) """ return -2 * (y - mu) / self.unit_variance(mu) def deviance(self, y, mu, sample_weight=1): r"""Compute the deviance. The deviance is a weighted sum of the unit deviances, :math:`\sum_i s_i \times d(y_i, \mu_i)`, where :math:`d(y, \mu)` is the unit deviance and :math:`s` are weights. In terms of the log likelihood, it is :math:`-2\phi \times [L(y, \mu, \phi / s) - L(y, y, \phi / s)]`. Parameters ---------- y : array-like, shape (n_samples,) Target values. mu : array-like, shape (n_samples,) Predicted mean. sample_weight : array-like, shape (n_samples,), optional (default=1) Weights or exposure to which variance is inversely proportional. Returns ------- float """ if sample_weight is None: return np.sum(self.unit_deviance(y, mu)) else: return np.sum(self.unit_deviance(y, mu) * sample_weight) def deviance_derivative(self, y, mu, sample_weight=1): r"""Compute the derivative of the deviance with respect to ``mu``. Parameters ---------- y : array-like, shape (n_samples,) Target values. mu : array-like, shape (n_samples,) Predicted mean. sample_weight : array-like, shape (n_samples,) (default=1) Weights or exposure to which variance is inverse proportional. Returns ------- array-like, shape (n_samples,) """ return sample_weight * self.unit_deviance_derivative(y, mu) def _mu_deviance_derivative( self, coef: np.ndarray, X, y: np.ndarray, sample_weight: np.ndarray, link: Link, offset: np.ndarray = None, ) -> Tuple[np.ndarray, np.ndarray]: """Compute ``mu`` and the derivative of the deviance \ with respect to coefficients.""" lin_pred = _safe_lin_pred(X, coef, offset) mu = link.inverse(lin_pred) d1 = link.inverse_derivative(lin_pred) temp = d1 * self.deviance_derivative(y, mu, sample_weight) if coef.size == X.shape[1] + 1: devp = np.concatenate(([temp.sum()], temp @ X)) else: devp = temp @ X # same as X.T @ temp return mu, devp def eta_mu_deviance( self, link: Link, factor: float, cur_eta: np.ndarray, X_dot_d: np.ndarray, y: np.ndarray, sample_weight: np.ndarray, ): """ Compute ``eta``, ``mu`` and the deviance. Compute: * the linear predictor, ``eta``, as ``cur_eta + factor * X_dot_d``; * the link-function-transformed prediction, ``mu``; * the deviance. Returns ------- numpy.ndarray, shape (X.shape[0],) The linear predictor, ``eta``. numpy.ndarray, shape (X.shape[0],) The link-function-transformed prediction, ``mu``. float The deviance. """ # eta_out and mu_out are filled inside self._eta_mu_deviance, # avoiding allocating new arrays for every line search loop eta_out = np.empty_like(cur_eta) mu_out = np.empty_like(cur_eta) deviance = self._eta_mu_deviance( link, factor, cur_eta, X_dot_d, y, sample_weight, eta_out, mu_out ) return eta_out, mu_out, deviance def _eta_mu_deviance( self, link: Link, factor: float, cur_eta: np.ndarray, X_dot_d: np.ndarray, y: np.ndarray, sample_weight: np.ndarray, eta_out: np.ndarray, mu_out: np.ndarray, ): """ Update ``eta`` and ``mu`` and compute the deviance. This is a default implementation that should work for all valid distributions and link functions. To implement a custom optimized version for a specific distribution and link function, please override this function in the subclass. Returns ------- float """ eta_out[:] = cur_eta + factor * X_dot_d mu_out[:] = link.inverse(eta_out) return self.deviance(y, mu_out, sample_weight=sample_weight) def rowwise_gradient_hessian( self, link: Link, coef: np.ndarray, dispersion, X: Union[MatrixBase, StandardizedMatrix], y: np.ndarray, sample_weight: np.ndarray, eta: np.ndarray, mu: np.ndarray, offset: np.ndarray = None, ): """ Compute the gradient and negative Hessian of the log likelihood row-wise. Returns ------- numpy.ndarray, shape (X.shape[0],) The gradient of the log likelihood, row-wise. numpy.ndarray, shape (X.shape[0],) The negative Hessian of the log likelihood, row-wise. """ gradient_rows = np.empty_like(mu) hessian_rows = np.empty_like(mu) self._rowwise_gradient_hessian( link, y, sample_weight, eta, mu, gradient_rows, hessian_rows ) # To form the full Hessian matrix from the IRLS sample_weight: # hessian_matrix = _safe_sandwich_dot(X, hessian_rows, intercept=intercept) return gradient_rows, hessian_rows def _rowwise_gradient_hessian( self, link, y, sample_weight, eta, mu, gradient_rows, hessian_rows ): """ Update ``gradient_rows`` and ``hessian_rows`` in place. This is a default implementation that should work for all valid distributions and link functions. To implement a custom optimized version for a specific distribution and link function, please override this function in the subclass. """ # FOR TWEEDIE: sigma_inv = weights / (mu ** p) during optimization bc phi = 1 sigma_inv = get_one_over_variance(self, link, mu, eta, 1.0, sample_weight) d1 = link.inverse_derivative(eta) # = h'(eta) # Alternatively: # h'(eta) = h'(g(mu)) = 1/g'(mu), note that h is inverse of g # d1 = 1./link.derivative(mu) d1_sigma_inv = d1 * sigma_inv gradient_rows[:] = d1_sigma_inv * (y - mu) hessian_rows[:] = d1 * d1_sigma_inv def _fisher_information( self, link, X, y, mu, sample_weight, dispersion, fit_intercept ): """Compute the expected information matrix. Parameters ---------- link : Link A link function (i.e. an instance of :class:`~glum._link.Link`). X : array-like Training data. y : array-like Target values. mu : array-like Predicted mean. sample_weight : array-like Weights or exposure to which variance is inversely proportional. dispersion : float The dispersion parameter. fit_intercept : bool Whether the model has an intercept. """ W = (link.inverse_derivative(link.link(mu)) ** 2) * get_one_over_variance( self, link, mu, link.inverse(mu), dispersion, sample_weight ) return _safe_sandwich_dot(X, W, intercept=fit_intercept) def _observed_information( self, link, X, y, mu, sample_weight, dispersion, fit_intercept ): """Compute the observed information matrix. Parameters ---------- X : array-like Training data. y : array-like Target values. mu : array-like Predicted mean. sample_weight : array-like Weights or exposure to which variance is inversely proportional. dispersion : float The dispersion parameter. fit_intercept : bool Whether the model has an intercept. """ linpred = link.link(mu) W = ( -link.inverse_derivative2(linpred) * (y - mu) + (link.inverse_derivative(linpred) ** 2) * ( 1 + (y - mu) * self.unit_variance_derivative(mu) / self.unit_variance(mu) ) ) * get_one_over_variance(self, link, mu, linpred, dispersion, sample_weight) return _safe_sandwich_dot(X, W, intercept=fit_intercept) def _score_matrix(self, link, X, y, mu, sample_weight, dispersion, fit_intercept): """Compute the score. Parameters ---------- X : array-like Training data. y : array-like Target values. mu : array-like Predicted mean. sample_weight : array-like Weights or exposure to which variance is inversely proportional. dispersion : float The dispersion parameter. fit_intercept : bool Whether the model has an intercept. """ linpred = link.link(mu) W = ( get_one_over_variance(self, link, mu, linpred, dispersion, sample_weight) * link.inverse_derivative(linpred) * (y - mu) ).reshape(-1, 1) if fit_intercept: if sparse.issparse(X): return sparse.hstack((W, X.multiply(W))) else: return np.hstack((W, np.multiply(X, W))) else: if sparse.issparse(X): return X.multiply(W) else: return np.multiply(X, W) def dispersion(self, y, mu, sample_weight=None, ddof=1, method="pearson") -> float: r"""Estimate the dispersion parameter :math:`\phi`. Parameters ---------- y : array-like, shape (n_samples,) Target values. mu : array-like, shape (n_samples,) Predicted mean. sample_weight : array-like, shape (n_samples,), optional (default=1) Weights or exposure to which variance is inversely proportional. ddof : int, optional (default=1) Degrees of freedom consumed by the model for ``mu``. method = {'pearson', 'deviance'}, optional (default='pearson') Whether to base the estimate on the Pearson residuals or the deviance. Returns ------- float """ y, mu, sample_weight = _as_float_arrays(y, mu, sample_weight) if method == "pearson": pearson_residuals = ((y - mu) ** 2) / self.unit_variance(mu) if sample_weight is None: numerator = pearson_residuals.sum() else: numerator = np.dot(pearson_residuals, sample_weight) elif method == "deviance": numerator = self.deviance(y, mu, sample_weight) else: raise NotImplementedError(f"Method {method} hasn't been implemented.") if sample_weight is None: return numerator / (len(y) - ddof) else: return numerator / (sample_weight.sum() - ddof) class TweedieDistribution(ExponentialDispersionModel): r"""A class for the Tweedie distribution. A Tweedie distribution with mean :math:`\mu = \mathrm{E}(Y)` is uniquely defined by its mean-variance relationship :math:`\mathrm{var}(Y) \propto \mu^{\mathrm{power}}`. Special cases are: ====== ================ Power Distribution ====== ================ 0 Normal 1 Poisson (1, 2) Compound Poisson 2 Gamma 3 Inverse Gaussian ====== ================ Parameters ---------- power : float, optional (default=0) The variance power of the `unit_variance` :math:`v(\mu) = \mu^{\mathrm{power}}`. For :math:`0 < \mathrm{power} < 1`, no distribution exists. """ upper_bound = np.Inf include_upper_bound = False def __init__(self, power=0): # validate power and set _upper_bound, _include_upper_bound attrs self.power = power @property def lower_bound(self) -> Union[float, int]: """Return the lowest value of ``y`` allowed.""" if self.power <= 0: return -np.Inf if self.power >= 1: return 0 raise ValueError @property def include_lower_bound(self) -> bool: """Return whether ``lower_bound`` is allowed as a value of ``y``.""" if self.power <= 0: return False if (self.power >= 1) and (self.power < 2): return True if self.power >= 2: return False raise ValueError @property def power(self) -> float: """Return the Tweedie power parameter.""" return self._power @power.setter def power(self, power): if not isinstance(power, (int, float)): raise TypeError(f"power must be an int or float, input was {power}") if (power > 0) and (power < 1): raise ValueError("For 0<power<1, no distribution exists.") # Prevents upcasting when working with 32-bit data self._power = power if isinstance(power, int) else np.float32(power) def unit_variance(self, mu: np.ndarray) -> np.ndarray: """Compute the unit variance of a Tweedie distribution ``v(mu) = mu^power``. Parameters ---------- mu : array-like, shape (n_samples,) Predicted mean. Returns ------- numpy.ndarray, shape (n_samples,) """ p = self.power # noqa: F841 return numexpr.evaluate("mu ** p") def unit_variance_derivative(self, mu: np.ndarray) -> np.ndarray: r"""Compute the derivative of the unit variance of a Tweedie distribution. Equation: :math:`v(\mu) = p \times \mu^{(p-1)}`. Parameters ---------- mu : array-like, shape (n_samples,) Predicted mean. Returns ------- numpy.ndarray, shape (n_samples,) """ p = self.power # noqa: F841 return numexpr.evaluate("p * mu ** (p - 1)") def deviance(self, y, mu, sample_weight=None) -> float: """Compute the deviance. Parameters ---------- y : array-like, shape (n_samples,) Target values. mu : array-like, shape (n_samples,) Predicted mean. sample_weight : array-like, shape (n_samples,), optional (default=1) Sample weights. """ p = self.power y, mu, sample_weight = _as_float_arrays(y, mu, sample_weight) sample_weight = np.ones_like(y) if sample_weight is None else sample_weight # NOTE: the dispersion parameter is only necessary to convey # type information on account of a bug in Cython if p == 0: return normal_deviance(y, sample_weight, mu, dispersion=1.0) if p == 1: return poisson_deviance(y, sample_weight, mu, dispersion=1.0) elif p == 2: return gamma_deviance(y, sample_weight, mu, dispersion=1.0) else: return tweedie_deviance(y, sample_weight, mu, p=float(p)) def unit_deviance(self, y, mu): """Get the deviance of each observation.""" p = self.power if p == 0: # Normal distribution return (y - mu) ** 2 if p == 1: # Poisson distribution return 2 * (special.xlogy(y, y / mu) - y + mu) elif p == 2: # Gamma distribution return 2 * (np.log(mu / y) + y / mu - 1) else: mu1mp = mu ** (1 - p) return 2 * ( (np.maximum(y, 0) ** (2 - p)) / ((1 - p) * (2 - p)) - y * mu1mp / (1 - p) + mu * mu1mp / (2 - p) ) def _rowwise_gradient_hessian( self, link, y, sample_weight, eta, mu, gradient_rows, hessian_rows ): f = None if self.power == 0 and isinstance(link, IdentityLink): f = normal_identity_rowwise_gradient_hessian elif self.power == 1 and isinstance(link, LogLink): f = poisson_log_rowwise_gradient_hessian elif self.power == 2 and isinstance(link, LogLink): f = gamma_log_rowwise_gradient_hessian elif 1 < self.power < 2 and isinstance(link, LogLink): f = partial(tweedie_log_rowwise_gradient_hessian, p=self.power) if f is not None: return f(y, sample_weight, eta, mu, gradient_rows, hessian_rows) return super()._rowwise_gradient_hessian( link, y, sample_weight, eta, mu, gradient_rows, hessian_rows ) def _eta_mu_deviance( self, link: Link, factor: float, cur_eta: np.ndarray, X_dot_d: np.ndarray, y: np.ndarray, sample_weight: np.ndarray, eta_out: np.ndarray, mu_out: np.ndarray, ): f = None if self.power == 0 and isinstance(link, IdentityLink): f = normal_identity_eta_mu_deviance elif self.power == 1 and isinstance(link, LogLink): f = poisson_log_eta_mu_deviance elif self.power == 2 and isinstance(link, LogLink): f = gamma_log_eta_mu_deviance elif 1 < self.power < 2 and isinstance(link, LogLink): f = partial(tweedie_log_eta_mu_deviance, p=self.power) if f is not None: return f(cur_eta, X_dot_d, y, sample_weight, eta_out, mu_out, factor) return super()._eta_mu_deviance( link, factor, cur_eta, X_dot_d, y, sample_weight, eta_out, mu_out ) def log_likelihood(self, y, mu, sample_weight=None, dispersion=None) -> float: r"""Compute the log likelihood. For ``1 < power < 2``, we use the series approximation by Dunn and Smyth (2005) to compute the normalization term. Parameters ---------- y : array-like, shape (n_samples,) Target values. mu : array-like, shape (n_samples,) Predicted mean. sample_weight : array-like, shape (n_samples,), optional (default=1) Sample weights. dispersion : float, optional (default=None) Dispersion parameter :math:`\phi`. Estimated if ``None``. """ p = self.power y, mu, sample_weight = _as_float_arrays(y, mu, sample_weight) sample_weight = np.ones_like(y) if sample_weight is None else sample_weight if (p != 1) and (dispersion is None): dispersion = self.dispersion(y, mu, sample_weight) if p == 0: return normal_log_likelihood(y, sample_weight, mu, float(dispersion)) if p == 1: # NOTE: the dispersion parameter is only necessary to convey # type information on account of a bug in Cython return poisson_log_likelihood(y, sample_weight, mu, 1.0) elif p == 2: return gamma_log_likelihood(y, sample_weight, mu, float(dispersion)) elif p < 2: return tweedie_log_likelihood( y, sample_weight, mu, float(p), float(dispersion) ) else: raise NotImplementedError def dispersion(self, y, mu, sample_weight=None, ddof=1, method="pearson") -> float: r"""Estimate the dispersion parameter :math:`\phi`. Parameters ---------- y : array-like, shape (n_samples,) Target values. mu : array-like, shape (n_samples,) Predicted mean. sample_weight : array-like, shape (n_samples,), optional (default=None) Weights or exposure to which variance is inversely proportional. ddof : int, optional (default=1) Degrees of freedom consumed by the model for ``mu``. method = {'pearson', 'deviance'}, optional (default='pearson') Whether to base the estimate on the Pearson residuals or the deviance. Returns ------- float """ p = self.power # noqa: F841 y, mu, sample_weight = _as_float_arrays(y, mu, sample_weight) if method == "pearson": formula = "((y - mu) ** 2) / (mu ** p)" if sample_weight is None: return numexpr.evaluate(formula).sum() / (len(y) - ddof) else: formula = f"sample_weight * {formula}" return numexpr.evaluate(formula).sum() / (sample_weight.sum() - ddof) return super().dispersion( y, mu, sample_weight=sample_weight, ddof=ddof, method=method ) class NormalDistribution(TweedieDistribution): """Class for the Normal (a.k.a. Gaussian) distribution.""" def __init__(self): super().__init__(power=0) class PoissonDistribution(TweedieDistribution): """Class for the scaled Poisson distribution.""" def __init__(self): super().__init__(power=1) class GammaDistribution(TweedieDistribution): """Class for the Gamma distribution.""" def __init__(self): super().__init__(power=2) class InverseGaussianDistribution(TweedieDistribution): """Class for the scaled Inverse Gaussian distribution.""" def __init__(self): super().__init__(power=3) class GeneralizedHyperbolicSecant(ExponentialDispersionModel): """A class for the Generalized Hyperbolic Secant (GHS) distribution. The GHS distribution is for targets ``y`` in ``(-∞, +∞)``. """ lower_bound = -np.Inf upper_bound = np.Inf include_lower_bound = False include_upper_bound = False def unit_variance(self, mu: np.ndarray) -> np.ndarray: """Get the unit-level expected variance. See superclass documentation. Parameters ---------- mu : array-like or float Returns ------- array-like """ return 1 + mu**2 def unit_variance_derivative(self, mu: np.ndarray) -> np.ndarray: """Get the derivative of the unit variance. See superclass documentation. Parameters ---------- mu : array-like or float Returns ------- array-like """ return 2 * mu def unit_deviance(self, y: np.ndarray, mu: np.ndarray) -> np.ndarray: """Get the unit-level deviance. See superclass documentation. Parameters ---------- y : array-like mu : array-like Returns ------- array-like """ return 2 * y * (np.arctan(y) - np.arctan(mu)) + np.log( (1 + mu**2) / (1 + y**2) ) class BinomialDistribution(ExponentialDispersionModel): """A class for the Binomial distribution. The Binomial distribution is for targets ``y`` in ``[0, 1]``. """ lower_bound = 0 upper_bound = 1 include_lower_bound = True include_upper_bound = True def __init__(self): return def unit_variance(self, mu: np.ndarray) -> np.ndarray: """Get the unit-level expected variance. See superclass documentation. Parameters ---------- mu : array-like Returns ------- array-like """ return mu * (1 - mu) def unit_variance_derivative(self, mu): """Get the derivative of the unit variance. See superclass documentation. Parameters ---------- mu : array-like or float Returns ------- array-like """ return 1 - 2 * mu def unit_deviance(self, y: np.ndarray, mu: np.ndarray) -> np.ndarray: """Get the unit-level deviance. See superclass documentation. Parameters ---------- y : array-like mu : array-like Returns ------- array-like """ # see Wooldridge and Papke (1996) for the fractional case return -2 * (special.xlogy(y, mu) + special.xlogy(1 - y, 1 - mu)) def _rowwise_gradient_hessian( self, link, y, sample_weight, eta, mu, gradient_rows, hessian_rows ): if isinstance(link, LogitLink): return binomial_logit_rowwise_gradient_hessian( y, sample_weight, eta, mu, gradient_rows, hessian_rows ) return super()._rowwise_gradient_hessian( link, y, sample_weight, eta, mu, gradient_rows, hessian_rows ) def _eta_mu_deviance( self, link: Link, factor: float, cur_eta: np.ndarray, X_dot_d: np.ndarray, y: np.ndarray, sample_weight: np.ndarray, eta_out: np.ndarray, mu_out: np.ndarray, ): if isinstance(link, LogitLink): return binomial_logit_eta_mu_deviance( cur_eta, X_dot_d, y, sample_weight, eta_out, mu_out, factor ) return super()._eta_mu_deviance( link, factor, cur_eta, X_dot_d, y, sample_weight, eta_out, mu_out ) def log_likelihood(self, y, mu, sample_weight=None, dispersion=1) -> float: """Compute the log likelihood. Parameters ---------- y : array-like, shape (n_samples,) Target values. mu : array-like, shape (n_samples,) Predicted mean. sample_weight : array-like, shape (n_samples,), optional (default=1) Sample weights. dispersion : float, optional (default=1) Ignored. """ ll = special.xlogy(y, mu) + special.xlogy(1 - y, 1 - mu) return np.sum(ll) if sample_weight is None else np.dot(ll, sample_weight) def dispersion(self, y, mu, sample_weight=None, ddof=1, method="pearson") -> float: r"""Estimate the dispersion parameter :math:`\phi`. Parameters ---------- y : array-like, shape (n_samples,) Target values. mu : array-like, shape (n_samples,) Predicted mean. sample_weight : array-like, shape (n_samples,), optional (default=None) Weights or exposure to which variance is inversely proportional. ddof : int, optional (default=1) Degrees of freedom consumed by the model for ``mu``. method = {'pearson', 'deviance'}, optional (default='pearson') Whether to base the estimate on the Pearson residuals or the deviance. Returns ------- float """ y, mu, sample_weight = _as_float_arrays(y, mu, sample_weight) if method == "pearson": formula = "((y - mu) ** 2) / (mu * (1 - mu))" if sample_weight is None: return numexpr.evaluate(formula).sum() / (len(y) - ddof) else: formula = f"sample_weight * {formula}" return numexpr.evaluate(formula).sum() / (sample_weight.sum() - ddof) return super().dispersion( y, mu, sample_weight=sample_weight, ddof=ddof, method=method ) def guess_intercept( y: np.ndarray, sample_weight: np.ndarray, link: Link, distribution: ExponentialDispersionModel, eta: Union[np.ndarray, float] = None, ): """ Say we want to find the scalar `b` that minimizes ``LL(eta + b)``, with \ ``eta`` fixed. An exact solution exists for Tweedie distributions with a log link and for the normal distribution with identity link. An exact solution also exists for the case of logit with no offset. If the distribution and corresponding link are something else, we use the Tweedie or normal solution, depending on the link function. """ avg_y = np.average(y, weights=sample_weight) if isinstance(link, IdentityLink): # This is only correct for normal. For other distributions, answer is unknown, # but assume that we want sum(y) = sum(mu) if eta is None: return avg_y avg_eta = eta if np.isscalar(eta) else np.average(eta, weights=sample_weight) return avg_y - avg_eta elif isinstance(link, LogLink): # This is only correct for Tweedie log_avg_y = np.log(avg_y) assert np.isfinite(log_avg_y).all() if eta is None: return log_avg_y mu = np.exp(eta) if isinstance(distribution, TweedieDistribution): p = distribution.power else: p = 1 # Like Poisson if np.isscalar(mu): first = np.log(y.dot(sample_weight) * mu ** (1 - p)) second = np.log(sample_weight.sum() * mu ** (2 - p)) else: first = np.log((y * mu ** (1 - p)).dot(sample_weight)) second = np.log((mu ** (2 - p)).dot(sample_weight)) return first - second elif isinstance(link, LogitLink): log_odds = np.log(avg_y) - np.log(np.average(1 - y, weights=sample_weight)) if eta is None: return log_odds avg_eta = eta if np.isscalar(eta) else np.average(eta, weights=sample_weight) return log_odds - avg_eta else: return link.link(y.dot(sample_weight)) def get_one_over_variance( distribution: ExponentialDispersionModel, link: Link, mu: np.ndarray, eta: np.ndarray, dispersion, sample_weight: np.ndarray, ): """ Get one over the variance. For Tweedie: ``sigma_inv = sample_weight / (mu ** p)`` during optimization, because ``phi = 1``. For Binomial with Logit link: Simplifies to ``variance = phi / ( sample_weight * (exp(eta) + 2 + exp(-eta)))``. More numerically accurate. """ if isinstance(distribution, BinomialDistribution) and isinstance(link, LogitLink): max_float_for_exp = np.log(np.finfo(eta.dtype).max / 10) if np.any(np.abs(eta) > max_float_for_exp): eta = np.clip(eta, -max_float_for_exp, max_float_for_exp) # type: ignore return sample_weight * (np.exp(eta) + 2 + np.exp(-eta)) / dispersion return 1.0 / distribution.variance( mu, dispersion=dispersion, sample_weight=sample_weight ) def _as_float_arrays(*args): """Convert to a float array, passing ``None`` through, and broadcast.""" never_broadcast = {} # type: ignore maybe_broadcast = {} always_broadcast = {} for ix, arg in enumerate(args): if isinstance(arg, (int, float)): maybe_broadcast[ix] = np.array([arg], dtype="float") elif arg is None: never_broadcast[ix] = None else: always_broadcast[ix] = np.asanyarray(arg, dtype="float") if always_broadcast and maybe_broadcast: to_broadcast = {**always_broadcast, **maybe_broadcast} _broadcast = np.broadcast_arrays(*to_broadcast.values()) broadcast = dict(zip(to_broadcast.keys(), _broadcast)) elif always_broadcast: _broadcast = np.broadcast_arrays(*always_broadcast.values()) broadcast = dict(zip(always_broadcast.keys(), _broadcast)) else: broadcast = maybe_broadcast # possibly `{}` out = {**never_broadcast, **broadcast} return [out[ix] for ix in range(len(args))]
[ "numpy.clip", "scipy.special.xlogy", "numpy.less_equal", "numpy.log", "numpy.asanyarray", "numpy.array", "numpy.isfinite", "numpy.greater_equal", "numpy.multiply", "numpy.less", "numpy.greater", "numpy.isscalar", "numpy.exp", "numpy.dot", "numpy.maximum", "numpy.arctan", "numpy.abs",...
[((34790, 34826), 'numpy.average', 'np.average', (['y'], {'weights': 'sample_weight'}), '(y, weights=sample_weight)\n', (34800, 34826), True, 'import numpy as np\n'), ((10487, 10509), 'numpy.empty_like', 'np.empty_like', (['cur_eta'], {}), '(cur_eta)\n', (10500, 10509), True, 'import numpy as np\n'), ((10527, 10549), 'numpy.empty_like', 'np.empty_like', (['cur_eta'], {}), '(cur_eta)\n', (10540, 10549), True, 'import numpy as np\n'), ((12227, 12244), 'numpy.empty_like', 'np.empty_like', (['mu'], {}), '(mu)\n', (12240, 12244), True, 'import numpy as np\n'), ((12268, 12285), 'numpy.empty_like', 'np.empty_like', (['mu'], {}), '(mu)\n', (12281, 12285), True, 'import numpy as np\n'), ((20726, 20753), 'numexpr.evaluate', 'numexpr.evaluate', (['"""mu ** p"""'], {}), "('mu ** p')\n", (20742, 20753), False, 'import numexpr\n'), ((21216, 21253), 'numexpr.evaluate', 'numexpr.evaluate', (['"""p * mu ** (p - 1)"""'], {}), "('p * mu ** (p - 1)')\n", (21232, 21253), False, 'import numexpr\n'), ((16425, 16443), 'scipy.sparse.issparse', 'sparse.issparse', (['X'], {}), '(X)\n', (16440, 16443), False, 'from scipy import sparse, special\n'), ((16606, 16624), 'scipy.sparse.issparse', 'sparse.issparse', (['X'], {}), '(X)\n', (16621, 16624), False, 'from scipy import sparse, special\n'), ((20313, 20330), 'numpy.float32', 'np.float32', (['power'], {}), '(power)\n', (20323, 20330), True, 'import numpy as np\n'), ((21765, 21780), 'numpy.ones_like', 'np.ones_like', (['y'], {}), '(y)\n', (21777, 21780), True, 'import numpy as np\n'), ((25551, 25566), 'numpy.ones_like', 'np.ones_like', (['y'], {}), '(y)\n', (25563, 25566), True, 'import numpy as np\n'), ((29711, 29747), 'numpy.log', 'np.log', (['((1 + mu ** 2) / (1 + y ** 2))'], {}), '((1 + mu ** 2) / (1 + y ** 2))\n', (29717, 29747), True, 'import numpy as np\n'), ((32648, 32668), 'scipy.special.xlogy', 'special.xlogy', (['y', 'mu'], {}), '(y, mu)\n', (32661, 32668), False, 'from scipy import sparse, special\n'), ((32671, 32699), 'scipy.special.xlogy', 'special.xlogy', (['(1 - y)', '(1 - mu)'], {}), '(1 - y, 1 - mu)\n', (32684, 32699), False, 'from scipy import sparse, special\n'), ((32715, 32725), 'numpy.sum', 'np.sum', (['ll'], {}), '(ll)\n', (32721, 32725), True, 'import numpy as np\n'), ((32756, 32781), 'numpy.dot', 'np.dot', (['ll', 'sample_weight'], {}), '(ll, sample_weight)\n', (32762, 32781), True, 'import numpy as np\n'), ((35079, 35095), 'numpy.isscalar', 'np.isscalar', (['eta'], {}), '(eta)\n', (35090, 35095), True, 'import numpy as np\n'), ((35101, 35139), 'numpy.average', 'np.average', (['eta'], {'weights': 'sample_weight'}), '(eta, weights=sample_weight)\n', (35111, 35139), True, 'import numpy as np\n'), ((35270, 35283), 'numpy.log', 'np.log', (['avg_y'], {}), '(avg_y)\n', (35276, 35283), True, 'import numpy as np\n'), ((35395, 35406), 'numpy.exp', 'np.exp', (['eta'], {}), '(eta)\n', (35401, 35406), True, 'import numpy as np\n'), ((35559, 35574), 'numpy.isscalar', 'np.isscalar', (['mu'], {}), '(mu)\n', (35570, 35574), True, 'import numpy as np\n'), ((36941, 36992), 'numpy.clip', 'np.clip', (['eta', '(-max_float_for_exp)', 'max_float_for_exp'], {}), '(eta, -max_float_for_exp, max_float_for_exp)\n', (36948, 36992), True, 'import numpy as np\n'), ((37508, 37538), 'numpy.array', 'np.array', (['[arg]'], {'dtype': '"""float"""'}), "([arg], dtype='float')\n", (37516, 37538), True, 'import numpy as np\n'), ((16704, 16721), 'numpy.multiply', 'np.multiply', (['X', 'W'], {}), '(X, W)\n', (16715, 16721), True, 'import numpy as np\n'), ((17841, 17881), 'numpy.dot', 'np.dot', (['pearson_residuals', 'sample_weight'], {}), '(pearson_residuals, sample_weight)\n', (17847, 17881), True, 'import numpy as np\n'), ((31081, 31101), 'scipy.special.xlogy', 'special.xlogy', (['y', 'mu'], {}), '(y, mu)\n', (31094, 31101), False, 'from scipy import sparse, special\n'), ((31104, 31132), 'scipy.special.xlogy', 'special.xlogy', (['(1 - y)', '(1 - mu)'], {}), '(1 - y, 1 - mu)\n', (31117, 31132), False, 'from scipy import sparse, special\n'), ((36889, 36900), 'numpy.abs', 'np.abs', (['eta'], {}), '(eta)\n', (36895, 36900), True, 'import numpy as np\n'), ((37653, 37686), 'numpy.asanyarray', 'np.asanyarray', (['arg'], {'dtype': '"""float"""'}), "(arg, dtype='float')\n", (37666, 37686), True, 'import numpy as np\n'), ((2996, 3033), 'numpy.greater_equal', 'np.greater_equal', (['x', 'self.lower_bound'], {}), '(x, self.lower_bound)\n', (3012, 3033), True, 'import numpy as np\n'), ((3055, 3089), 'numpy.less_equal', 'np.less_equal', (['x', 'self.upper_bound'], {}), '(x, self.upper_bound)\n', (3068, 3089), True, 'import numpy as np\n'), ((3186, 3223), 'numpy.greater_equal', 'np.greater_equal', (['x', 'self.lower_bound'], {}), '(x, self.lower_bound)\n', (3202, 3223), True, 'import numpy as np\n'), ((3225, 3253), 'numpy.less', 'np.less', (['x', 'self.upper_bound'], {}), '(x, self.upper_bound)\n', (3232, 3253), True, 'import numpy as np\n'), ((3386, 3417), 'numpy.greater', 'np.greater', (['x', 'self.lower_bound'], {}), '(x, self.lower_bound)\n', (3396, 3417), True, 'import numpy as np\n'), ((3419, 3453), 'numpy.less_equal', 'np.less_equal', (['x', 'self.upper_bound'], {}), '(x, self.upper_bound)\n', (3432, 3453), True, 'import numpy as np\n'), ((3549, 3580), 'numpy.greater', 'np.greater', (['x', 'self.lower_bound'], {}), '(x, self.lower_bound)\n', (3559, 3580), True, 'import numpy as np\n'), ((3582, 3610), 'numpy.less', 'np.less', (['x', 'self.upper_bound'], {}), '(x, self.upper_bound)\n', (3589, 3610), True, 'import numpy as np\n'), ((29679, 29691), 'numpy.arctan', 'np.arctan', (['y'], {}), '(y)\n', (29688, 29691), True, 'import numpy as np\n'), ((29694, 29707), 'numpy.arctan', 'np.arctan', (['mu'], {}), '(mu)\n', (29703, 29707), True, 'import numpy as np\n'), ((35299, 35321), 'numpy.isfinite', 'np.isfinite', (['log_avg_y'], {}), '(log_avg_y)\n', (35310, 35321), True, 'import numpy as np\n'), ((35938, 35951), 'numpy.log', 'np.log', (['avg_y'], {}), '(avg_y)\n', (35944, 35951), True, 'import numpy as np\n'), ((36080, 36096), 'numpy.isscalar', 'np.isscalar', (['eta'], {}), '(eta)\n', (36091, 36096), True, 'import numpy as np\n'), ((36102, 36140), 'numpy.average', 'np.average', (['eta'], {'weights': 'sample_weight'}), '(eta, weights=sample_weight)\n', (36112, 36140), True, 'import numpy as np\n'), ((36841, 36860), 'numpy.finfo', 'np.finfo', (['eta.dtype'], {}), '(eta.dtype)\n', (36849, 36860), True, 'import numpy as np\n'), ((37059, 37071), 'numpy.exp', 'np.exp', (['(-eta)'], {}), '(-eta)\n', (37065, 37071), True, 'import numpy as np\n'), ((16557, 16574), 'numpy.multiply', 'np.multiply', (['X', 'W'], {}), '(X, W)\n', (16568, 16574), True, 'import numpy as np\n'), ((22569, 22593), 'scipy.special.xlogy', 'special.xlogy', (['y', '(y / mu)'], {}), '(y, y / mu)\n', (22582, 22593), False, 'from scipy import sparse, special\n'), ((23490, 23549), 'functools.partial', 'partial', (['tweedie_log_rowwise_gradient_hessian'], {'p': 'self.power'}), '(tweedie_log_rowwise_gradient_hessian, p=self.power)\n', (23497, 23549), False, 'from functools import partial\n'), ((24465, 24515), 'functools.partial', 'partial', (['tweedie_log_eta_mu_deviance'], {'p': 'self.power'}), '(tweedie_log_eta_mu_deviance, p=self.power)\n', (24472, 24515), False, 'from functools import partial\n'), ((35961, 36001), 'numpy.average', 'np.average', (['(1 - y)'], {'weights': 'sample_weight'}), '(1 - y, weights=sample_weight)\n', (35971, 36001), True, 'import numpy as np\n'), ((37041, 37052), 'numpy.exp', 'np.exp', (['eta'], {}), '(eta)\n', (37047, 37052), True, 'import numpy as np\n'), ((22671, 22685), 'numpy.log', 'np.log', (['(mu / y)'], {}), '(mu / y)\n', (22677, 22685), True, 'import numpy as np\n'), ((27405, 27430), 'numexpr.evaluate', 'numexpr.evaluate', (['formula'], {}), '(formula)\n', (27421, 27430), False, 'import numexpr\n'), ((27551, 27576), 'numexpr.evaluate', 'numexpr.evaluate', (['formula'], {}), '(formula)\n', (27567, 27576), False, 'import numexpr\n'), ((33814, 33839), 'numexpr.evaluate', 'numexpr.evaluate', (['formula'], {}), '(formula)\n', (33830, 33839), False, 'import numexpr\n'), ((33960, 33985), 'numexpr.evaluate', 'numexpr.evaluate', (['formula'], {}), '(formula)\n', (33976, 33985), False, 'import numexpr\n'), ((22790, 22806), 'numpy.maximum', 'np.maximum', (['y', '(0)'], {}), '(y, 0)\n', (22800, 22806), True, 'import numpy as np\n')]
import math import pandas as pd data = pd.read_csv("works.csv").dropna() count_people = 0 for (jobTitle, qualification) in zip(data['jobTitle'], data['qualification']): if jobTitle != qualification: count_people += 1 print(f"У {count_people} человек профессия и должность не совпадают") menegers = data[data['jobTitle'].str.lower().str.contains("менеджер")]['qualification'].value_counts().head() print("Топ 5 образований менеджеров: ") print(menegers) injineers = data[data['qualification'].str.lower().str.contains("инженер")]['jobTitle'].value_counts().head() print("Топ 5 специальностей инженеров: ") print(injineers) # У 1052 человек профессия и должность не совпадают # Топ 5 образований менеджеров: # Бакалавр 9 # менеджер 5 # Специалист 5 # Менеджер 5 # Экономист 4 # Топ 5 специальностей инженеров: # заместитель директора 2 # Инженер лесопользования 2 # главный инженер 2 # Директор 2 # заместитель директора по производству 1
[ "pandas.read_csv" ]
[((43, 67), 'pandas.read_csv', 'pd.read_csv', (['"""works.csv"""'], {}), "('works.csv')\n", (54, 67), True, 'import pandas as pd\n')]
from decimal import Decimal from unittest.mock import patch from django.test import TestCase from django.urls import reverse from django.contrib import auth from main.models import Product, User, Address from main.forms import UserCreationForm class TestPage(TestCase): def test_home_page_works(self): response = self.client.get(reverse('home')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'home.html') self.assertContains(response, 'BookStore') def test_about_us_page_works(self): response = self.client.get(reverse('about_us')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'about_us.html') self.assertContains(response, 'BookStore') def test_products_page_returns_active(self): Product.objects.create( name='The cathedral and the bazaar', slug='cathedral-bazaar', price=Decimal('10.00'), ) Product.objects.create( name='A Tale of Two Cities', slug='tale-two-cities', price=Decimal('2.00'), active=False, ) product_list = Product.objects.active().order_by( 'name' ) response = self.client.get( reverse('products', kwargs={'tag': "all"}) ) self.assertEqual( list(response.context['object_list']), list(product_list), ) self.assertEqual(response.status_code, 200) self.assertContains(response, 'BookStore') def test_products_page_filters_by_tag_and_active(self): cb = Product.objects.create( name='The cathedral and the bazaar', slug='cathedral-bazaar', price=Decimal('10.00'), ) cb.tags.create(name='Open Source', slug='open-source') Product.objects.create( name='A Tale of Two Cities', slug='tale-two-cities', price=Decimal('2.00'), active=False, ) response = self.client.get( reverse('products', kwargs={'tag': 'open-source'}) ) product_list = ( Product.objects.active() .filter(tags__slug='open-source') .order_by('name') ) self.assertEqual( list(response.context['object_list']), list(product_list), ) self.assertEqual(response.status_code, 200) self.assertContains(response, 'BookStore') def test_user_signup_page_loads_correctly(self): response = self.client.get(reverse('signup')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'signup.html') self.assertContains(response, "BookStore") self.assertIsInstance(response.context['form'], UserCreationForm) def test_user_signup_page_submission_works(self): post_data = { 'email': '<EMAIL>', 'password1': '<PASSWORD>', 'password2': '<PASSWORD>', } with patch.object(UserCreationForm, 'send_mail') as mock_send: response = self.client.post(reverse('signup'), post_data) self.assertEqual(response.status_code, 302) self.assertTrue(auth.get_user(self.client).is_authenticated) self.assertTrue(User.objects.filter(email='<EMAIL>').exists()) mock_send.assert_called_once() def test_address_list_page_returns_owned_by_user(self): user1 = User.objects.create_user("user1", "<PASSWORD>") user2 = User.objects.create_user("user2", "<PASSWORD>") Address.objects.create( user=user1, name="<NAME>", address1="1 mende", address2="24 church street", city="kano", country="Nigeria", ) Address.objects.create( user=user2, name="<NAME>", address1="4 mendez", address2="24 boulevard street", city="Abuja", country="Nigeria", ) self.client.force_login(user2) response = self.client.get(reverse("address_list")) self.assertEqual(response.status_code, 200) address_list = Address.objects.filter(user=user2) self.assertEqual( list(response.context["object_list"]), list(address_list), ) def test_address_create_stores_user(self): user1 = User.objects.create_user("user1", "12345pw") post_data = { "name": "<NAME>", "address1": "20 broadstreet", "address2": "", "zip_code": "IKJ20", "city": "Ibadan", "country": "brazil", } self.client.force_login(user1) self.client.post( reverse("address_create"), post_data, ) self.assertEqual(Address.objects.filter(user=user1).exists())
[ "django.contrib.auth.get_user", "main.models.Address.objects.create", "django.urls.reverse", "main.models.User.objects.create_user", "main.models.User.objects.filter", "main.models.Address.objects.filter", "main.models.Product.objects.active", "unittest.mock.patch.object", "decimal.Decimal" ]
[((3529, 3576), 'main.models.User.objects.create_user', 'User.objects.create_user', (['"""user1"""', '"""<PASSWORD>"""'], {}), "('user1', '<PASSWORD>')\n", (3553, 3576), False, 'from main.models import Product, User, Address\n'), ((3593, 3640), 'main.models.User.objects.create_user', 'User.objects.create_user', (['"""user2"""', '"""<PASSWORD>"""'], {}), "('user2', '<PASSWORD>')\n", (3617, 3640), False, 'from main.models import Product, User, Address\n'), ((3650, 3784), 'main.models.Address.objects.create', 'Address.objects.create', ([], {'user': 'user1', 'name': '"""<NAME>"""', 'address1': '"""1 mende"""', 'address2': '"""24 church street"""', 'city': '"""kano"""', 'country': '"""Nigeria"""'}), "(user=user1, name='<NAME>', address1='1 mende',\n address2='24 church street', city='kano', country='Nigeria')\n", (3672, 3784), False, 'from main.models import Product, User, Address\n'), ((3872, 4011), 'main.models.Address.objects.create', 'Address.objects.create', ([], {'user': 'user2', 'name': '"""<NAME>"""', 'address1': '"""4 mendez"""', 'address2': '"""24 boulevard street"""', 'city': '"""Abuja"""', 'country': '"""Nigeria"""'}), "(user=user2, name='<NAME>', address1='4 mendez',\n address2='24 boulevard street', city='Abuja', country='Nigeria')\n", (3894, 4011), False, 'from main.models import Product, User, Address\n'), ((4267, 4301), 'main.models.Address.objects.filter', 'Address.objects.filter', ([], {'user': 'user2'}), '(user=user2)\n', (4289, 4301), False, 'from main.models import Product, User, Address\n'), ((4528, 4572), 'main.models.User.objects.create_user', 'User.objects.create_user', (['"""user1"""', '"""12345pw"""'], {}), "('user1', '12345pw')\n", (4552, 4572), False, 'from main.models import Product, User, Address\n'), ((345, 360), 'django.urls.reverse', 'reverse', (['"""home"""'], {}), "('home')\n", (352, 360), False, 'from django.urls import reverse\n'), ((596, 615), 'django.urls.reverse', 'reverse', (['"""about_us"""'], {}), "('about_us')\n", (603, 615), False, 'from django.urls import reverse\n'), ((1309, 1351), 'django.urls.reverse', 'reverse', (['"""products"""'], {'kwargs': "{'tag': 'all'}"}), "('products', kwargs={'tag': 'all'})\n", (1316, 1351), False, 'from django.urls import reverse\n'), ((2107, 2157), 'django.urls.reverse', 'reverse', (['"""products"""'], {'kwargs': "{'tag': 'open-source'}"}), "('products', kwargs={'tag': 'open-source'})\n", (2114, 2157), False, 'from django.urls import reverse\n'), ((2628, 2645), 'django.urls.reverse', 'reverse', (['"""signup"""'], {}), "('signup')\n", (2635, 2645), False, 'from django.urls import reverse\n'), ((3092, 3135), 'unittest.mock.patch.object', 'patch.object', (['UserCreationForm', '"""send_mail"""'], {}), "(UserCreationForm, 'send_mail')\n", (3104, 3135), False, 'from unittest.mock import patch\n'), ((4166, 4189), 'django.urls.reverse', 'reverse', (['"""address_list"""'], {}), "('address_list')\n", (4173, 4189), False, 'from django.urls import reverse\n'), ((4879, 4904), 'django.urls.reverse', 'reverse', (['"""address_create"""'], {}), "('address_create')\n", (4886, 4904), False, 'from django.urls import reverse\n'), ((965, 981), 'decimal.Decimal', 'Decimal', (['"""10.00"""'], {}), "('10.00')\n", (972, 981), False, 'from decimal import Decimal\n'), ((1120, 1135), 'decimal.Decimal', 'Decimal', (['"""2.00"""'], {}), "('2.00')\n", (1127, 1135), False, 'from decimal import Decimal\n'), ((1197, 1221), 'main.models.Product.objects.active', 'Product.objects.active', ([], {}), '()\n', (1219, 1221), False, 'from main.models import Product, User, Address\n'), ((1787, 1803), 'decimal.Decimal', 'Decimal', (['"""10.00"""'], {}), "('10.00')\n", (1794, 1803), False, 'from decimal import Decimal\n'), ((2005, 2020), 'decimal.Decimal', 'Decimal', (['"""2.00"""'], {}), "('2.00')\n", (2012, 2020), False, 'from decimal import Decimal\n'), ((3190, 3207), 'django.urls.reverse', 'reverse', (['"""signup"""'], {}), "('signup')\n", (3197, 3207), False, 'from django.urls import reverse\n'), ((3297, 3323), 'django.contrib.auth.get_user', 'auth.get_user', (['self.client'], {}), '(self.client)\n', (3310, 3323), False, 'from django.contrib import auth\n'), ((3366, 3402), 'main.models.User.objects.filter', 'User.objects.filter', ([], {'email': '"""<EMAIL>"""'}), "(email='<EMAIL>')\n", (3385, 3402), False, 'from main.models import Product, User, Address\n'), ((4953, 4987), 'main.models.Address.objects.filter', 'Address.objects.filter', ([], {'user': 'user1'}), '(user=user1)\n', (4975, 4987), False, 'from main.models import Product, User, Address\n'), ((2205, 2229), 'main.models.Product.objects.active', 'Product.objects.active', ([], {}), '()\n', (2227, 2229), False, 'from main.models import Product, User, Address\n')]
# coding=utf-8 """ Django settings for reservas project. Generated by 'django-admin startproject' using Django 1.8.5. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import random BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # Establece la clave secreta a partir de la variable de entorno 'DJANGO_SECRET_KEY', o genera una # clave aleatoria si ésta no se encuentra seteada. SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', ''.join([random.SystemRandom() .choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Administradores del proyecto. ADMINS = [] MANAGERS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'djangobower', 'app_facturacion', 'app_reservas.apps.ReservasConfig', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'reservas.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'debug': DEBUG, }, }, ] WSGI_APPLICATION = 'reservas.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Establece el prefijo para el proyecto Django, según la configuración # del servidor web. DJANGO_URL_PREFIX = os.environ.get('DJANGO_URL_PREFIX', '') # Da formato al prefijo URL, para que sea de la forma '<prefijo>/'. # 1. Quita las barras iniciales y finales, por si el prefijo cuenta con más de una. DJANGO_URL_PREFIX = DJANGO_URL_PREFIX.strip('/') # 2. Añade una única barra final, en caso de que el prefijo no haya quedado vacío luego de la # operación anterior. if DJANGO_URL_PREFIX: DJANGO_URL_PREFIX += '/' # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/' + DJANGO_URL_PREFIX + 'static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'djangobower.finders.BowerFinder', ) STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/' + DJANGO_URL_PREFIX + 'media/' EVENTOS_URL = 'media/app_reservas/eventos_recursos/' BOWER_COMPONENTS_ROOT = os.path.join(BASE_DIR, 'components') BOWER_INSTALLED_APPS = ( 'bootstrap-datepicker#1.6.0', 'bootswatch-dist#3.3.6-flatly', 'font-awesome#4.7.0', 'fullcalendar-scheduler', 'handsontable#0.31.2', 'jquery#1.9.1', 'pace#1.0.2', 'qtip2#2.2.1', 'slick-carousel#1.6.0' ) # Token de Google Calendar, utilizado para consultar la información de eventos # de los calendarios de Google Calendar. GOOGLE_CALENDAR_TOKEN = os.environ.get('GOOGLE_CALENDAR_TOKEN', '') BROKER_URL = os.environ.get('BROKER_URL', 'amqp://guest:guest@rabbit//')
[ "os.path.join", "random.SystemRandom", "os.environ.get", "os.path.abspath" ]
[((3227, 3266), 'os.environ.get', 'os.environ.get', (['"""DJANGO_URL_PREFIX"""', '""""""'], {}), "('DJANGO_URL_PREFIX', '')\n", (3241, 3266), False, 'import os\n'), ((3753, 3790), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""staticfiles"""'], {}), "(BASE_DIR, 'staticfiles')\n", (3765, 3790), False, 'import os\n'), ((4179, 4210), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""media"""'], {}), "(BASE_DIR, 'media')\n", (4191, 4210), False, 'import os\n'), ((4338, 4374), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""components"""'], {}), "(BASE_DIR, 'components')\n", (4350, 4374), False, 'import os\n'), ((4785, 4828), 'os.environ.get', 'os.environ.get', (['"""GOOGLE_CALENDAR_TOKEN"""', '""""""'], {}), "('GOOGLE_CALENDAR_TOKEN', '')\n", (4799, 4828), False, 'import os\n'), ((4843, 4902), 'os.environ.get', 'os.environ.get', (['"""BROKER_URL"""', '"""amqp://guest:guest@rabbit//"""'], {}), "('BROKER_URL', 'amqp://guest:guest@rabbit//')\n", (4857, 4902), False, 'import os\n'), ((3867, 3899), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""static"""'], {}), "(BASE_DIR, 'static')\n", (3879, 3899), False, 'import os\n'), ((2897, 2933), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""db.sqlite3"""'], {}), "(BASE_DIR, 'db.sqlite3')\n", (2909, 2933), False, 'import os\n'), ((481, 506), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (496, 506), False, 'import os\n'), ((2236, 2271), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""templates"""'], {}), "(BASE_DIR, 'templates')\n", (2248, 2271), False, 'import os\n'), ((949, 970), 'random.SystemRandom', 'random.SystemRandom', ([], {}), '()\n', (968, 970), False, 'import random\n')]
#!/usr/bin/env python import collections # import itertools import numpy as np # from sklearn import linear_model as linear # for VAR # from .utils import sliding_window as window # from .utils.distance import kmeans, dists_sq # from .utils import distance as dist # from python import compress # ================================================================ shifts lut SHIFT_PAIRS_16 = [ (7, 1), # ~0 - .5 = ~-.5 (3, 1), # .125 - .5 = -.375 (2, 1), # .25 - .5 = -.25 # (4, 2), # .0625 - .25 = -.1875 (3, 2), # .125 - .5 = -.125 (4, 3), # .0625 - .125 = -.0625 (0, 0), # 1 - 1 = 0 (3, 4), # .125 - .0625 = .0625 (2, 3), # .25 - .125 - .125 (2, 4), # .25 - .0625 = .1875 (1, 2), # .5 - .25 = .25 (1, 3), # .5 - .125 = .375 (0, 1), # 1 - .5 = .5 (0, 2), # 1 - .25 = .75 (0, 3), # 1 - .125 = .875 (0, 4), # 1 - .0625 = .9375 (0, 7), # 1 - ~0 = ~1 ] # should be equivalent to `all_shifts(max_shift=5, omit_duplicates=True)` # EDIT: wait, no, not true because we have shifts of 7 at the ends SHIFT_PAIRS_26 = [ (7, 1), # ~0 - .5 = ~-.5 (5, 1), # .0625 - .5 = -.46875 # added (4, 1), # .0625 - .5 = -.4375 # added, max 4 (3, 1), # .125 - .5 = -.375 (2, 1), # .25 - .5 = -.25 (5, 2), # .03125- .25 = -.21875 (4, 2), # .0625 - .25 = -.1875 # added, max 4 (3, 2), # .125 - .25 = -.125 (5, 3), # .03125- .125 = -.09375 # added (4, 3), # .0625 - .125 = -.0625 (5, 4), # .03125- .0625 = -.03125 # added (0, 0), # 1 - 1 = 0 (4, 5), # .0625 - .03125= .03125 (3, 4), # .125 - .0625 = .0625 (3, 5), # .125 - .03125= .09375 # added (2, 3), # .25 - .125 - .125 (2, 4), # .25 - .0625 = .1875 (2, 5), # .25 - .03125= .21875 # added (1, 2), # .5 - .25 = .25 (1, 3), # .5 - .125 = .375 (1, 4), # .5 - .0625 = .4375 # added, max 4 (1, 5), # .5 - .03125= .46875 # added (0, 1), # 1 - .5 = .5 (0, 2), # 1 - .25 = .75 (0, 3), # 1 - .125 = .875 (0, 4), # 1 - .0625 = .9375 (0, 5), # 1 - .03125= .96875 # added (0, 7), # 1 - ~0 = ~1 ] def all_shifts(max_shift=-1, omit_duplicates=True): vals = {} nbits = 8 x = 1 << nbits # reference val; 256 for nbits if max_shift < 0: max_shift = nbits - 1 if omit_duplicates: vals[(0, 0)] = 0 for a in range(max_shift + 1): for b in range(max_shift + 1): if omit_duplicates and a == b: continue vals[(a, b)] = (x >> a) - (x >> b) keys, coeffs = list(zip(*list(vals.items()))) keys = np.array(keys) coeffs = np.array(coeffs) order = np.argsort(coeffs) # print "shift results:" # print keys[order] # print coeffs[order] return keys[order], coeffs[order] # okay, looks like (according to test immediately below) these values are # identical to what's in our existing LUT; this makes sense given that impls # are basically identical def _i16_for_shifts(pos_shift, neg_shift, nbits=8): start_val = 1 << nbits # 256 for nbits = 8 return (start_val >> pos_shift) - (start_val >> neg_shift) # TODO actual unit test def _test_shift_coeffs(nbits=8): shifts, shift_coeffs = all_shifts() for (pos_shift, neg_shift), coeff in zip(shifts, shift_coeffs): assert _i16_for_shifts(pos_shift, neg_shift) == coeff for val in range(-128, 128): two_shifts_val = (val >> pos_shift) - (val >> neg_shift) # ya, this fails; multiply and rshift != using shifts directly # assert (val * coeff) >> nbits == two_shifts_val # this way works; requires two multiplies though... pos_coef = 1 << (nbits - pos_shift) neg_coef = 1 << (nbits - neg_shift) pos = (val * pos_coef) >> nbits neg = (val * neg_coef) >> nbits assert pos - neg == two_shifts_val # this way also fails # pos = val * pos_coef # neg = val * neg_coef # assert (pos - neg) >> nbits == two_shifts_val # def coeff_lut(): # """create lookup table `T` such that `T[coeff]` yields the two indices # whose associated coefficients are immediately above and below `coeff`""" # shifts, shift_coeffs = all_shifts() SHIFTS, SHIFT_COEFFS = all_shifts() # ================================================================ funcs def binary_search(array, val): M = len(array) first = 0 middle = int(M / 2) last = M - 1 while (first <= last): middle_val = array[middle] if middle_val < val: first = middle + 1 elif middle_val == val: return middle else: # middle_val > val last = middle - 1 middle = int((first + last) / 2) return middle class OnlineRegressor(object): def __init__(self, block_sz=8, verbose=0, method='linreg', shifts=SHIFTS, shift_coeffs=SHIFT_COEFFS, numbits=8, ntaps=1): # self.prev0 = 0 # self.prev1 = 0 # self.mod = 1 << nbits # self.shift0 = 0 # self.shift1 = 1 self.block_sz = block_sz self.verbose = verbose self.method = method self.shifts = shifts self.shift_coeffs = shift_coeffs self.numbits = numbits self.ntaps = ntaps self.last_val = 0 self.last_delta = 0 self.coef = 0 self.coef = 256 self.counter = 0 # self.counter = 256 << (1 + self.numbits - 8) # TODO indirect to learning rate, not just 1 # noqa # self.counter = 8 << 1 # equivalent to adding 8 to round to nearest? # self.counter = self.coef self.t = 0 self.grad_counter = 0 self.offset = 0 self.offset_counter = 0 shift_by = (1 + self.numbits - 8) self.coeffs = np.zeros(self.ntaps, dtype=np.int32) + 256 self.counters = np.zeros(self.ntaps, dtype=np.int32) + (256 << shift_by) # self.approx_256_over_x = 1 self.Sxy = 0 self.Sxx = 0 self.errs = [] # print "using shifts, coeffs:" # print shifts # print shift_coeffs # for logging # self.best_idx_offset_counts = np.zeros(3, dtype=np.int64) self.best_idx_counts = np.zeros(len(self.shifts), dtype=np.int64) # counts_len = len(self.shifts) if method == 'linreg' else 512 # self.best_idx_counts = np.zeros(counts_len, dtype=np.int64) self.best_coef_counts = collections.Counter() self.best_offset_counts = collections.Counter() def feed_group(self, group): pass # TODO determine optimal filter here # errhat = a*x0 - b*x0 - a*x1 + b*x1 # = a(x0 - x1) + b(x1 - x0) # = c(x0 - x1), where c = (a - b) # # we should compute c, and find shifts (which correspond to a, b) that # approximate it well; also note that errhat is prediction of the delta # # this is just linear regression between (x0 - x1) and new val, with # some extra logic at the end to get shifts based on regression coeff # deltas; these are our target variable deltas = np.zeros(group.size, dtype=group.dtype) deltas[1:] = group[1:] - group[:-1] deltas[0] = group[0] - self.last_val self.last_val = group[-1] # deltas from previous time step; these are our indep variable diffs = np.zeros(group.size, dtype=group.dtype) diffs[1:] = deltas[:-1] diffs[0] = self.last_delta self.last_delta = deltas[-1] x = diffs y = deltas # linear regression if self.method == 'linreg': Sxy = np.sum(x * y) Sxx = np.sum(x * x) # print "x, y dtypes: ", x.dtype, y.dtype # print "Sxx, Sxy dtypes: ", Sxx.dtype, Sxy.dtype coeff = (Sxy << 8) / Sxx # shift to mirror what we'll need to do in C idx = binary_search(self.shift_coeffs, coeff) def compute_errs(x, y, shifts): predictions = (x >> shifts[0]) - (x >> shifts[1]) return y - predictions # These are commented out because, empirically, they're # *never* chosen # # best_idx_offset = 0 # # def compute_total_cost(errs, block_sz=self.block_sz): # raw_costs = compress.nbits_cost(errs) # block_costs_rows = raw_costs.reshape(-1, block_sz) # block_costs = np.max(block_costs_rows, axis=1) # return np.sum(block_costs) # # cost = compute_total_cost(errs) # if idx > 0: # errs2 = compute_errs(x, y, SHIFTS[idx - 1]) # cost2 = compute_total_cost(errs) # if cost2 < cost: # ret = errs2 # best_idx_offset = -1 # if idx < (len(SHIFTS) - 1): # errs3 = compute_errs(x, y, SHIFTS[idx + 1]) # cost3 = compute_total_cost(errs) # if cost3 < cost: # ret = errs3 # best_idx_offset = 1 # self.best_idx_offset_counts[best_idx_offset] += 1 errs = compute_errs(x, y, self.shifts[idx]) self.best_idx_counts[idx] += 1 # for logging elif self.method == 'gradient': # update coeffs using last entry in each block # learning_rate_shift = 7 # learning rate of 2^(-learning_rate_shift) # learning_rate_shift = 8 # learning rate of 2^(-learning_rate_shift) # learning_rate_shift = 12 # learning rate of 2^(-learning_rate_shift) # learning_rate_shift = 4 # learning rate of 2^(-learning_rate_shift) # learning_rate_shift = 2 # learning rate of 2^(-learning_rate_shift) predictions = (x * self.coef) >> int(min(self.numbits, 8)) for tap_idx in range(1, self.ntaps): predictions[tap_idx:] += (x[:-tap_idx] * self.coeffs[tap_idx]) predictions += self.offset errs = y - predictions for b in range(8): # for each block # only update based on a few values for efficiency which_idxs = 8 * b + np.array([3, 7]) # downsample by 4 # which_idxs = 8 * b + np.array([1, 3, 5, 7]) # downsample by 2 grads = 0 # grads = np.zeros(self.ntaps) # offsets = 0 for idx in which_idxs: xval = x[idx] # xval = x[idx] >> (self.numbits - 8) # grad = int(-errs[idx] * x[idx]) >> 8 # grad = int(-errs[idx] * x[idx]) // 256 # y0 = np.abs(self.approx_256_over_x) * np.sign(xval) # y0 = 1 + (256 - xval) >> 8 # y0 = 3 - ((3 * xval) >> 8) # grad = int(-(errs[idx] << 8) / xval) if xval != 0 else 0 # works great # self.counter -= grad # equivalent to above two lines # if self.t % 100 == 0: # print "grad:", grad # continue # # xabs = self.t # TODO rm # xabs = np.abs(xval) # if xabs == 0: # lzcnt = self.numbits # else: # lzcnt = self.numbits - 1 - int(np.log2(xabs)) # lzcnt = max(0, lzcnt - 1) # round up to nearest power of 2 # # lzcnt = min(15, lzcnt + 1) # round up to nearest power of 2 # # numerator = 1 << self.numbits # # recip = 1 << (lzcnt - 8) if lzcnt >= 8 else # # recip = np.sign(xval) << (8 + lzcnt) # shift_amt = max(0, lzcnt - (self.numbits - 8)) # usually 0, maybe 1 sometimes # recip = (1 << shift_amt) * np.sign(xval) # grad = int(-errs[idx] * recip) # # grad = int(grad / len(which_idxs)) # normal grad descent # grad = int(-errs[idx] * np.sign(xval)) # div by sqrt(hessian) # grad = int(-errs[idx] * xval) >> self.numbits # true gradient # approx newton step for log(nbits) err = errs[idx] # if False: # TODO rm # if self.numbits > 8: # grad = int(-(1 + err)) if err > 0 else int(-(err - 1)) # else: # grad = int(-err) # don't add 1 # self.grad_counter += (grad - (self.grad_counter >> 8)) # wtf this works so well for 16b, despite ignoring sign of x... # (when also only shifting counter by learning rate, not # an additional 8) # grad = -err # grad = -(err + np.sign(err)) * np.sign(xval) # grad = -err * np.sign(xval) # these both seem to work pretty well; prolly need to directly # compare them # grad = -err * np.sign(xval) # grad = -np.sign(err) * xval # significantly better than prev line grad = np.sign(err) * xval # significantly better than prev line # ^ duh; above is minimizer for L1 loss # grad = -np.sign(err) * np.sign(xval) << (self.numbits - 8) # sub_from = ((1 << self.numbits) - 1) * np.sign(xval) # approx_recip_x = sub_from - xval # grad = -np.sign(err) * approx_recip_x grads += int(grad) # grads += grad >> 1 # does this help with overflow? # simulate int8 overflow, adjusted for fact that we do 8 blocks # per group (so 1024, 2048 instead of 128, 256) mod = int(1 << self.numbits) offset = mod // 2 grads = ((grads + offset) % mod) - offset # grads = ((grads + 1024) % 2048) - 1024 # wrecks accuracy # grads = ((grads + 8192) % 16384) - 8192 # no effect self.errs.append(err) # offsets += np.sign(err) # optimize bias for l1 loss # this is the other one we should actually consider doing # # grad = int(-errs[idx] * np.sign(xval)) # # approximation of what we'd end up doing with a LUT # shift_to_just_4b = self.numbits - 4 # # y0 = ((xval >> shift_to_just_4b) + 1) << shift_to_just_4b # shifted_xval = xval >> shift_to_just_4b # if shifted_xval != 0: # y0 = int(256. / shifted_xval) << shift_to_just_4b # else: # y0 = 16*np.sign(xval) << shift_to_just_4b # # y0 = y0 * int(2 - (xval * y0 / 256)) # diverges # y0 = int(256. / xval) if xval else 0 # y0 = (1 << int(8 - np.floor(np.log2(xval)))) * np.sign(xval) # y0 = 4 * np.sign(xval) # self.approx_256_over_x = int( y0*(2 - (int(xval*y0) >> 8)) ) # noqa # doesn't work # grad = int(-errs[idx] * self.approx_256_over_x) # grad = int(-errs[idx] * y0) # grad = int(-errs[idx] * xval) # works # grad = int(-errs[idx] * 2*np.sign(xval)) # this_best_coef = self.coef - grad # self.counter += this_best_coef - self.coef # self.counter -= grad # equivalent to above two lines # self.counter -= grad >> learning_rate_shift # if self.t < 8: # if self.t % 50 == 0: # if (self.t < 5 == 0) and (b == 0): # if (self.t % 50 == 0) and (b == 0): # # print "errs: ", errs[-7], errs[-5], errs[-3], errs[-1] # print "t, b = ", self.t, b # print "errs: ", errs[-10:] # print "xs: ", x[-10:] # # print "sum(|xs|)", np.sum(np.abs(x)) # print "grads: ", grads # print "counter:", self.counter # # print "grad counter:", self.grad_counter # # # print "recip, grad: ", recip, grad # self.coef = self.counter >> min(self.t, learning_rate_shift) # self.coef = self.counter >> learning_rate_shift learning_rate_shift = 1 # learning_rate_shift = 4 # grad_learning_shift = 1 # grad_learning_shift = 4 # offset_learning_shift = 4 # compute average gradient for batch # grad = int(4 * grads / len(which_idxs)) # div by 16 grad = int(grads / len(which_idxs)) # div by 64 # grad = grads # self.grad_counter += grad - (self.grad_counter >> grad_learning_shift) # self.grad_counter += grad # # this is the pair of lines that we know works well for UCR # # self.counter -= grad self.counter += grad self.coef = self.counter >> (learning_rate_shift + (self.numbits - 8)) # self.coef = self.counter >> learning_rate_shift # self.coef -= (self.grad_counter >> grad_learning_shift) >> learning_rate_shift # learn_shift = int(min(learning_rate_shift, np.log2(self.t + 1))) # self.coef = self.counter >> (learn_shift + (self.numbits - 8)) # self.coef = self.counter >> learn_shift # for use with l1 loss # self.coef -= (self.grad_counter >> grad_learning_shift) >> learn_shift # self.coef -= (self.grad_counter >> grad_learning_shift) >> learning_rate_shift # self.coef = 192 # global soln for olive oil # quantize coeff by rounding to nearest 16; this seems to help # quite a bit, at least for stuff that really should be double # delta coded (starlight curves, presumably timestamps) # self.coef = ((self.coef + 8) >> 4) << 4 self.coef = (self.coef >> 4) << 4 # just round towards 0 # self.coef = (self.coef >> 5) << 5 # just round towards 0 # like above, but use sign since shift and unshift round towards 0 # EDIT: no apparent difference, though perhaps cuz almost nothing # actually wants a negative coef # self.coef = ((self.coef + 8 * np.sign(self.coef)) >> 4) << 4 # offset = int(offsets / len(which_idxs)) # div by 64 # self.offset_counter += offset # # self.offset = self.offset_counter >> offset_learning_shift # self.offset = 0 # offset doesn't seem to help at all # self.coef = 0 # why are estimates biased? TODO rm # self.coef = 256 # self.coef = self.counter # self.coef = np.clip(self.coef, -256, 256) # apparently important # self.coef = np.clip(self.coef, -128, 256) # apparently important # if self.t < 8: # if self.t % 100 == 0: # print "----- t = {}".format(self.t) # print "offset, offset counter: ", self.offset, self.offset_counter # # print "grad, grads sum: ", grad, grads # # print "learn shift: ", learn_shift # # print "errs[:10]: ", errs[:16] # # print "-grads[:10]: ", errs[:16] * x[:16] # # print "signed errs[:10]: ", errs[:16] * np.sign(x[:16]) # print "new coeff, grad_counter, counter = ", self.coef, self.grad_counter, self.counter # # print "new coeff, grad counter = ", self.coef, self.grad_counter # self.best_idx_counts[self.coef] += 1 # for logging self.best_coef_counts[self.coef] += 1 self.best_offset_counts[self.offset] += 1 # errs -= self.offset # do this at the end to not mess up training elif self.method == 'exact': # print "using exact method" if self.numbits <= 8: predictions = (x * self.coef) >> self.numbits else: predictions = ((x >> 8) * self.coef) errs = y - predictions learn_shift = 6 # shift = learn_shift + 2*self.numbits - 8 shift = learn_shift # only update based on a few values for efficiency start_idx = 0 if self.t > 0 else 8 for idx in np.arange(start_idx, len(x), 8): # xval = x[idx] # >> (self.numbits - 8) # yval = y[idx] # >> (self.numbits - 8) xval = x[idx] >> (self.numbits - 8) yval = y[idx] >> (self.numbits - 8) # # this way works just like global one, or maybe better # self.Sxx += xval * xval # self.Sxy += xval * yval # moving average way; seemingly works just as well # Exx = self.Sxx >> learn_shift # Exy = self.Sxy >> learn_shift Exy = self.Sxy >> shift Exx = self.Sxx >> shift # adjust_shift = 2 * diff_xx = (xval * xval) - Exx diff_xy = (xval * yval) - Exy self.Sxx += diff_xx self.Sxy += diff_xy # if min(self.Sxy, self.Sxx) >= 1024: # self.Sxx /= 2 # self.Sxy /= 2 Exy = self.Sxy >> shift Exx = self.Sxx >> shift self.coef = int((Exy << 8) / Exx) # works really well # none of this really works # # print "Exy, Exx = ", Exy, Exx # print "xval, yval: ", xval, yval # print "diff_xx, diff_xy, Exy, Exx = ", diff_xx, diff_xy, Exy, Exx # # numerator = 1 << (2 * self.numbits) # numerator = 256 # nbits = int(min(4, np.log2(Exx))) if Exx > 1 else 1 # assert numerator >= np.abs(Exx) # # print "nbits: ", nbits # recip = int((numerator >> nbits) / (Exx >> nbits)) << nbits # # recip = recip >> (2 * self.numbits - 8) # print "numerator, recip: ", numerator, recip # self.coef = int(Exy * recip) self.best_coef_counts[self.coef] += 1 self.t += 1 return errs # while (first <= last) { # if (array[middle] < search) # first = middle + 1; # else if (array[middle] == search) { # printf("%d found at location %d.\n", search, middle+1); # break; # } # else # last = middle - 1; # middle = (first + last)/2; # } def sub_online_regress(blocks, verbose=0, group_sz_blocks=8, max_shift=4, only_16_shifts=True, method='linreg', numbits=8, drop_first_half=False, **sink): # drop_first_half=True, **sink): blocks = blocks.astype(np.int32) if only_16_shifts: shifts = SHIFT_PAIRS_16 shift_coeffs = [_i16_for_shifts(*pair) for pair in shifts] else: shifts, shift_coeffs = all_shifts(max_shift=max_shift) encoder = OnlineRegressor(block_sz=blocks.shape[1], verbose=verbose, shifts=shifts, shift_coeffs=shift_coeffs, method=method, numbits=numbits) # print "using group_sz_blocks: ", group_sz_blocks # print "using method: ", method # print "using nbits: ", numbits out = np.empty(blocks.shape, dtype=np.int32) if group_sz_blocks < 1: group_sz_blocks = len(blocks) # global model ngroups = int(len(blocks) / group_sz_blocks) for g in range(ngroups): # if verbose and (g > 0) and (g % 100 == 0): # print "running on block ", g start_idx = g * group_sz_blocks end_idx = start_idx + group_sz_blocks group = blocks[start_idx:end_idx] errs = encoder.feed_group(group.ravel()) out[start_idx:end_idx] = errs.reshape(group.shape) out[end_idx:] = blocks[end_idx:] if verbose > 1: if method == 'linreg': if group_sz_blocks != len(blocks): import hipsterplot as hp # pip install hipsterplot # hp.plot(x_vals=encoder.shift_coeffs, y_vals=encoder.best_idx_counts, hp.plot(encoder.best_idx_counts, num_x_chars=len(encoder.shift_coeffs), num_y_chars=12) else: coef_idx = np.argmax(encoder.best_idx_counts) coef = encoder.shift_coeffs[coef_idx] print("global linreg coeff: ", coef) else: coeffs_counts = np.array(encoder.best_coef_counts.most_common()) print("min, max coeff: {}, {}".format( coeffs_counts[:, 0].min(), coeffs_counts[:, 0].max())) # print("most common (coeff, counts):\n", coeffs_counts[:16]) # bias_counts = np.array(encoder.best_offset_counts.most_common()) # print "most common (bias, counts):\n", bias_counts[:16] errs = np.array(encoder.errs) print("raw err mean, median, std, >0 frac: {}, {}, {}, {}".format( errs.mean(), np.median(errs), errs.std(), np.mean(errs > 0))) if drop_first_half and method == 'gradient': keep_idx = len(out) // 2 out[:keep_idx] = out[keep_idx:(2*keep_idx)] print("NOTE: duplicating second half of data into first half!!" \ " (blocks {}:)".format(keep_idx)) return out def _test_moving_avg(x0=0): # vals = np.zeros(5, dtype=np.int32) + 100 vals = np.zeros(5, dtype=np.int32) - 100 shft = 3 counter = x0 << shft xhats = [] for v in vals: xhat = counter >> shft xhats.append(xhat) counter += (v - xhat) print("vals: ", vals) print("xhats: ", xhats) # ================================================================ main def main(): np.set_printoptions(formatter={'float': lambda x: '{:.3f}'.format(x)}) # print "all shifts:\n", all_shifts() # _test_shift_coeffs() _test_moving_avg() # print "shifts_16, coeffs" # print SHIFT_PAIRS_16 # print [_i16_for_shifts(*pair) for pair in SHIFT_PAIRS_16] # x = np.array([5], dtype=np.int32) # print "shifting x left: ", x << 5 # blocks = np.arange(8 * 64, dtype=np.int32).reshape(-1, 8) # sub_online_regress(blocks) if __name__ == '__main__': main()
[ "numpy.mean", "numpy.median", "numpy.argmax", "numpy.argsort", "numpy.array", "numpy.zeros", "collections.Counter", "numpy.empty", "numpy.sum", "numpy.sign" ]
[((3011, 3025), 'numpy.array', 'np.array', (['keys'], {}), '(keys)\n', (3019, 3025), True, 'import numpy as np\n'), ((3039, 3055), 'numpy.array', 'np.array', (['coeffs'], {}), '(coeffs)\n', (3047, 3055), True, 'import numpy as np\n'), ((3068, 3086), 'numpy.argsort', 'np.argsort', (['coeffs'], {}), '(coeffs)\n', (3078, 3086), True, 'import numpy as np\n'), ((24700, 24738), 'numpy.empty', 'np.empty', (['blocks.shape'], {'dtype': 'np.int32'}), '(blocks.shape, dtype=np.int32)\n', (24708, 24738), True, 'import numpy as np\n'), ((6931, 6952), 'collections.Counter', 'collections.Counter', ([], {}), '()\n', (6950, 6952), False, 'import collections\n'), ((6987, 7008), 'collections.Counter', 'collections.Counter', ([], {}), '()\n', (7006, 7008), False, 'import collections\n'), ((7622, 7661), 'numpy.zeros', 'np.zeros', (['group.size'], {'dtype': 'group.dtype'}), '(group.size, dtype=group.dtype)\n', (7630, 7661), True, 'import numpy as np\n'), ((7873, 7912), 'numpy.zeros', 'np.zeros', (['group.size'], {'dtype': 'group.dtype'}), '(group.size, dtype=group.dtype)\n', (7881, 7912), True, 'import numpy as np\n'), ((26835, 26862), 'numpy.zeros', 'np.zeros', (['(5)'], {'dtype': 'np.int32'}), '(5, dtype=np.int32)\n', (26843, 26862), True, 'import numpy as np\n'), ((6271, 6307), 'numpy.zeros', 'np.zeros', (['self.ntaps'], {'dtype': 'np.int32'}), '(self.ntaps, dtype=np.int32)\n', (6279, 6307), True, 'import numpy as np\n'), ((6338, 6374), 'numpy.zeros', 'np.zeros', (['self.ntaps'], {'dtype': 'np.int32'}), '(self.ntaps, dtype=np.int32)\n', (6346, 6374), True, 'import numpy as np\n'), ((8139, 8152), 'numpy.sum', 'np.sum', (['(x * y)'], {}), '(x * y)\n', (8145, 8152), True, 'import numpy as np\n'), ((8171, 8184), 'numpy.sum', 'np.sum', (['(x * x)'], {}), '(x * x)\n', (8177, 8184), True, 'import numpy as np\n'), ((26294, 26316), 'numpy.array', 'np.array', (['encoder.errs'], {}), '(encoder.errs)\n', (26302, 26316), True, 'import numpy as np\n'), ((25696, 25730), 'numpy.argmax', 'np.argmax', (['encoder.best_idx_counts'], {}), '(encoder.best_idx_counts)\n', (25705, 25730), True, 'import numpy as np\n'), ((26425, 26440), 'numpy.median', 'np.median', (['errs'], {}), '(errs)\n', (26434, 26440), True, 'import numpy as np\n'), ((26454, 26471), 'numpy.mean', 'np.mean', (['(errs > 0)'], {}), '(errs > 0)\n', (26461, 26471), True, 'import numpy as np\n'), ((10758, 10774), 'numpy.array', 'np.array', (['[3, 7]'], {}), '([3, 7])\n', (10766, 10774), True, 'import numpy as np\n'), ((13866, 13878), 'numpy.sign', 'np.sign', (['err'], {}), '(err)\n', (13873, 13878), True, 'import numpy as np\n')]
from app.factory import create_app, celery_app app = create_app(config_name="DEVELOPMENT") app.app_context().push() if __name__ == "__main__": app.run()
[ "app.factory.create_app" ]
[((54, 91), 'app.factory.create_app', 'create_app', ([], {'config_name': '"""DEVELOPMENT"""'}), "(config_name='DEVELOPMENT')\n", (64, 91), False, 'from app.factory import create_app, celery_app\n')]
''' pyburstlib :author: drownedcoast :date: 4-26-2018 ''' import pytest from pyburstlib.wallet_api.models.mining import * from tests.base import BaseTest from tests.config import PyBurstLibConfig @pytest.mark.api class TestMiningApi(BaseTest): def setup(self): self.TEST_ACCOUNT_NUMERIC = PyBurstLibConfig.get('account_id') self.TEST_ACCOUNT_ADDRESS = PyBurstLibConfig.get('account_address') def test_mining_get_accounts_with_reward_recipient(self, client): accts = client.wallet_mining_api.get_accounts_with_reward_recipient(account_id=self.TEST_ACCOUNT_NUMERIC) assert isinstance(accts, Accounts) assert self.TEST_ACCOUNT_NUMERIC in accts.accounts def test_mining_get_mining_info(self, client): info = client.wallet_mining_api.get_mining_info() assert isinstance(info, MiningInfo) def test_mining_get_reward_recipient(self, client): reward = client.wallet_mining_api.get_reward_recipient(account_id=self.TEST_ACCOUNT_NUMERIC) assert isinstance(reward, RewardRecipient) assert self.TEST_ACCOUNT_NUMERIC == reward.rewardRecipient def test_mining_set_reward_recipient(self, client): reward_req = SetRewardRecipientRequest( recipient=PyBurstLibConfig.get('account_address'), secretPhrase=PyBurstLibConfig.get('account_pw') ) set_reward = client.wallet_mining_api.set_reward_recipient(req=reward_req.as_dict()) assert isinstance(set_reward, SetRewardRecipientResponse) assert isinstance(set_reward.transactionJSON, TransactionJSON) assert set_reward.transactionJSON.feeNQT == SetRewardRecipientRequest.DEFAULT_REWARD_RECIPIENT_FEE def test_mining_submit_nonce(self, client): nonce = client.wallet_mining_api.submit_nonce(secret_pass=PyBurstLibConfig.get('account_pw'), nonce="100000", account_id=PyBurstLibConfig.get('account_id')) assert isinstance(nonce, SubmitNonceResponse) assert nonce.result == SubmitNonceResponse.SUCCESS
[ "tests.config.PyBurstLibConfig.get" ]
[((303, 337), 'tests.config.PyBurstLibConfig.get', 'PyBurstLibConfig.get', (['"""account_id"""'], {}), "('account_id')\n", (323, 337), False, 'from tests.config import PyBurstLibConfig\n'), ((374, 413), 'tests.config.PyBurstLibConfig.get', 'PyBurstLibConfig.get', (['"""account_address"""'], {}), "('account_address')\n", (394, 413), False, 'from tests.config import PyBurstLibConfig\n'), ((1262, 1301), 'tests.config.PyBurstLibConfig.get', 'PyBurstLibConfig.get', (['"""account_address"""'], {}), "('account_address')\n", (1282, 1301), False, 'from tests.config import PyBurstLibConfig\n'), ((1328, 1362), 'tests.config.PyBurstLibConfig.get', 'PyBurstLibConfig.get', (['"""account_pw"""'], {}), "('account_pw')\n", (1348, 1362), False, 'from tests.config import PyBurstLibConfig\n'), ((1825, 1859), 'tests.config.PyBurstLibConfig.get', 'PyBurstLibConfig.get', (['"""account_pw"""'], {}), "('account_pw')\n", (1845, 1859), False, 'from tests.config import PyBurstLibConfig\n'), ((1996, 2030), 'tests.config.PyBurstLibConfig.get', 'PyBurstLibConfig.get', (['"""account_id"""'], {}), "('account_id')\n", (2016, 2030), False, 'from tests.config import PyBurstLibConfig\n')]
# This process handles all the requests in the queue task_queue and updates database import json, pika, sys, time from database_management import manage_database, submission_management class core(): data_changed_flags = '' task_queue = '' channel = '' file_password = '' unicast_exchange = 'connection_manager' broadcast_exchange = 'broadcast_manager' judge_unicast_exchange = 'judge_manager' judge_broadcast_exchange = 'judge_broadcast_manager' def init_core(data_changed_flags, task_queue): core.data_changed_flags = data_changed_flags core.task_queue = task_queue conn, cur = manage_database.initialize_database() print('[ JUDGE ][ CORE PROCESS ] Process started') # Infinite Loop to Poll the task_queue every second try: while True: status = core.poll(task_queue) if status == 1: break # Poll every second time.sleep(2) # If we reach this point, it means the Server Shutdown has been initiated. print('[ CORE ] Shutdown') core.data_changed_flags[6] = 1 except KeyboardInterrupt: core.data_changed_flags[6] = 1 print('[ CORE ] Force Shutdown') finally: manage_database.close_db() sys.exit() def poll(task_queue): # If sys exit is called, the following flag will be 1 if(core.data_changed_flags[5] == 1): return 1 # While there is data to process in the task_queue, try: while task_queue.empty() == False: # Data in the task queue is in JSON format data = task_queue.get() data = json.loads(data) code = data['Code'] # Contest START signal if code == 'JUDGE': run_id = data['Run ID'] client_id = data['Client ID'] verdict = data['Verdict'] language = data['Language'] problem_code = data['Problem Code'] time_stamp = data['Timestamp'] file_with_ext = data['Filename'] count = submission_management.get_count(run_id) if count == 0: # New Submission print('[ CORE ] Insert Record: Run', run_id) status = submission_management.insert_record( run_id, client_id, verdict, language, problem_code, time_stamp, file_with_ext ) if status == 0: print('[ CORE ] Submission Processed') else: print('[ CORE ] Submission Not Processed') core.data_changed_flags[4] = 1 else: print('[ CORE ] Update Record: Run', run_id) submission_management.update_record( run_id, client_id, verdict, language, problem_code, time_stamp, file_with_ext ) print('[ CORE ] Update successful ') core.data_changed_flags[4] = 1 elif code == 'UPDATE': run_id = data['Run ID'] client_id = data['Client ID'] verdict = data['Verdict'] language = data['Language'] problem_code = data['Problem Code'] time_stamp = data['Timestamp'] file_with_ext = data['Filename'] print('[ CORE ] Update: ', run_id) submission_management.update_record( run_id, client_id, verdict, language, problem_code, time_stamp, file_with_ext ) print('[ CORE ] Update successful ') core.data_changed_flags[4] = 1 except Exception as error: exc_type, exc_obj, exc_tb = sys.exc_info() fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] print('[ CORE ][ ERROR ] Data Processing error : ' + str(error) + ' on line ' + str(exc_tb.tb_lineno)) finally: return 0
[ "json.loads", "database_management.manage_database.initialize_database", "time.sleep", "sys.exc_info", "database_management.manage_database.close_db", "sys.exit", "database_management.submission_management.update_record", "database_management.submission_management.get_count", "database_management.su...
[((600, 637), 'database_management.manage_database.initialize_database', 'manage_database.initialize_database', ([], {}), '()\n', (635, 637), False, 'from database_management import manage_database, submission_management\n'), ((1135, 1161), 'database_management.manage_database.close_db', 'manage_database.close_db', ([], {}), '()\n', (1159, 1161), False, 'from database_management import manage_database, submission_management\n'), ((1165, 1175), 'sys.exit', 'sys.exit', ([], {}), '()\n', (1173, 1175), False, 'import json, pika, sys, time\n'), ((862, 875), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (872, 875), False, 'import json, pika, sys, time\n'), ((1495, 1511), 'json.loads', 'json.loads', (['data'], {}), '(data)\n', (1505, 1511), False, 'import json, pika, sys, time\n'), ((3288, 3302), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (3300, 3302), False, 'import json, pika, sys, time\n'), ((1844, 1883), 'database_management.submission_management.get_count', 'submission_management.get_count', (['run_id'], {}), '(run_id)\n', (1875, 1883), False, 'from database_management import manage_database, submission_management\n'), ((1993, 2111), 'database_management.submission_management.insert_record', 'submission_management.insert_record', (['run_id', 'client_id', 'verdict', 'language', 'problem_code', 'time_stamp', 'file_with_ext'], {}), '(run_id, client_id, verdict, language,\n problem_code, time_stamp, file_with_ext)\n', (2028, 2111), False, 'from database_management import manage_database, submission_management\n'), ((2406, 2524), 'database_management.submission_management.update_record', 'submission_management.update_record', (['run_id', 'client_id', 'verdict', 'language', 'problem_code', 'time_stamp', 'file_with_ext'], {}), '(run_id, client_id, verdict, language,\n problem_code, time_stamp, file_with_ext)\n', (2441, 2524), False, 'from database_management import manage_database, submission_management\n'), ((2980, 3098), 'database_management.submission_management.update_record', 'submission_management.update_record', (['run_id', 'client_id', 'verdict', 'language', 'problem_code', 'time_stamp', 'file_with_ext'], {}), '(run_id, client_id, verdict, language,\n problem_code, time_stamp, file_with_ext)\n', (3015, 3098), False, 'from database_management import manage_database, submission_management\n')]
''' buildings and built environment ''' from datetime import datetime import random import tracery from utilities import format_text, get_latin def eatery(name, dish, category, data): ''' a charming stone hut where they serve tea ''' earliest = data['founded'] if data['founded'] > 1700 else 1700 founding = random.randint(earliest - 4, datetime.now().year - 4) materials = { 'brick': ['pottery', 'ceramic'], 'straw': ['woven straw', 'straw'], 'wood': ['wood'], 'stone': ['marble', 'stonework'], 'cloth': ['textile', 'tapestry'], 'glass': ['glass', 'stained glass'], 'metal': ['metal'], 'tile': ['mosaic', 'tile'], } rules = { # structures 'start': [ '''With a gourmet, #cuisine# menu and #vibe_part#, #name# is a #platitude#. It will have you craving perennial favorites like #dish#. The setting, in a #space#, is stunning, a perfect #city# experience.''', '''Owner #chef# has given #cuisine# cuisine a modern edge while still staying true to the regional style. The venue is stunning, a #space# and #vibe_part#. Be sure to try the #dish#.''', '''In this #vibe# #type#, you can settle down in a #space#. The menu features staples of #cuisine# cuisine, and is best known for traditional-style #dish#.''', '''#name# is a #cuisine# restaurant in #city# that's been going strong since #founding#. With a #vibe_part# and attentive service, it offers #cuisine# cuisine in a #space#.''', '''#name# is a #vibe# #type# in a welcoming environment. It offers excellent #cuisine# food. The #dish# is hard to beat.''', '''This #space# gets rave reviews for #positive# and affordable #cuisine# food and ambiance. The #vibe_part# makes it a #platitude#.''', '''#name# is one of #city#'s best #cuisine# restaurants. It's a #platitude# where you can enjoy this #space#. There are a #positive# range of dishes on offer, including #dish#.''', '''This #platitude# opened in #founding# and has set the tone for #city# cuisine ever since. Regulars like to order #dish#, sit back, and enjoy the #vibe_part#.''', '''Something of a social hub in #city#, this #vibe# #type# doesn't exactly advertise itself, but the #dish# is #positive#. Overall a #platitude#.''', '''A popular #vibe# cafe in the heart of #city# serving #dish# and drinks.''', '''Founded in early #founding#, #name# serves arguably the best know #dish# in town and it deserves that distinction. It has a #secondary_material_fancy#-decked interior and a #vibe_part#.''', '''This simple place, popular with the city workers, covers the bases for a #positive# lunch of #dish#.''', '''#name# is a rather dark and seedy place to say the least, but within its #material# walls you'll get a #positive# range of local dishes.''', '''This simple seven-table place offers #positive# breakfasts and gets packed by lunchtime -- and rightly so. The #dish# is a killer (not literally!).''', ], # info 'name': '<em>%s</em>' % name, 'type': category, 'city': '<em>%s</em>' % get_latin(data['city_name'], capitalize=True), 'neighborhood': 'the <em>%s</em> district' % get_latin( random.choice(data['geography']['neighborhoods']), capitalize=True), 'founding': str(founding), 'chef': data['get_person']('chef')['name'], # descriptive componenets 'cuisine': '<em>%s</em>ian-style' % get_latin( data['country'], capitalize=True), 'dish': '"<em>%s</em>" (a %s)' % (get_latin(dish['name']), dish['description']), 'platitude': [ 'enduring favorite', 'first-rate establishment', 'local go-to', 'local favorite', 'popular place', 'much loved #type#', 'prestigious', 'foodie oasis', ], 'vibe_part': '#vibe# #atmosphere#', 'space': [ '#stories# with #color#-painted #material# walls and #accent#', 'stylish #material# and #secondary_material# #stories#', ], 'stories': '#%s#' % data['stories'], 'single': ['building', '#type#'], 'multi': 'spacious #building#', 'many': '%s-floor #building#' % random.choice( ['first', 'second', 'third', 'fourth', 'fifth', 'top']), 'accent': '#secondary_material# #accent_object#', 'accent_object': ['wall-hangings', 'doorways', 'lamps'], 'material': data['primary_material'], 'secondary_material': data['secondary_material'], 'secondary_material_fancy': materials[data['secondary_material']], 'building': ['suite', 'hall', 'room', '#type#'], # wordlists 'atmosphere': ['atmosphere', 'charm'], 'positive': [ 'top notch', 'good', 'great', 'fantastic', 'excellent', 'high caliber', 'wonderful', 'abundant'], 'vibe': [ 'bustling', 'busy', 'relaxing', 'sophisticated', 'quaint', 'cozy', 'elegant', 'world-renowned', 'laid-back', ], 'color': ['red', 'orange', 'yellow', 'green', 'purple', 'white', 'pink'], } grammar = tracery.Grammar(rules) sentence = grammar.flatten('#start#') return format_text(sentence)
[ "utilities.get_latin", "random.choice", "utilities.format_text", "datetime.datetime.now", "tracery.Grammar" ]
[((5854, 5876), 'tracery.Grammar', 'tracery.Grammar', (['rules'], {}), '(rules)\n', (5869, 5876), False, 'import tracery\n'), ((5931, 5952), 'utilities.format_text', 'format_text', (['sentence'], {}), '(sentence)\n', (5942, 5952), False, 'from utilities import format_text, get_latin\n'), ((3606, 3651), 'utilities.get_latin', 'get_latin', (["data['city_name']"], {'capitalize': '(True)'}), "(data['city_name'], capitalize=True)\n", (3615, 3651), False, 'from utilities import format_text, get_latin\n'), ((3964, 4007), 'utilities.get_latin', 'get_latin', (["data['country']"], {'capitalize': '(True)'}), "(data['country'], capitalize=True)\n", (3973, 4007), False, 'from utilities import format_text, get_latin\n'), ((4833, 4902), 'random.choice', 'random.choice', (["['first', 'second', 'third', 'fourth', 'fifth', 'top']"], {}), "(['first', 'second', 'third', 'fourth', 'fifth', 'top'])\n", (4846, 4902), False, 'import random\n'), ((350, 364), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (362, 364), False, 'from datetime import datetime\n'), ((3729, 3778), 'random.choice', 'random.choice', (["data['geography']['neighborhoods']"], {}), "(data['geography']['neighborhoods'])\n", (3742, 3778), False, 'import random\n'), ((4076, 4099), 'utilities.get_latin', 'get_latin', (["dish['name']"], {}), "(dish['name'])\n", (4085, 4099), False, 'from utilities import format_text, get_latin\n')]
import os import tarfile import textwrap from pathlib import Path import setuptools from wheel.wheelfile import WheelFile from setuptools_build_subpackage import Distribution ROOT = Path(__file__).parent.parent def build_dist(folder, command, output, *args): args = [ '--subpackage-folder', folder, 'clean', '--all', command, '--dist-dir', output, *args, ] cur = os.getcwd() os.chdir('example') try: setuptools.setup( distclass=Distribution, script_args=args, ) finally: os.chdir(cur) def test_bdist_wheel(tmp_path): build_dist('example/sub_module_a', 'bdist_wheel', tmp_path) build_dist('example/sub_module_b', 'bdist_wheel', tmp_path) wheel_a_path = tmp_path / 'example_sub_moudle_a-0.0.0-py2.py3-none-any.whl' wheel_b_path = tmp_path / 'example_sub_moudle_b-0.0.0-py2.py3-none-any.whl' assert wheel_a_path.exists(), "sub_module_a wheel file exists" assert wheel_b_path.exists(), "sub_module_b wheel file exists" with WheelFile(wheel_a_path) as wheel_a: assert set(wheel_a.namelist()) == { 'example/sub_module_a/__init__.py', 'example/sub_module_a/where.py', 'example_sub_moudle_a-0.0.0.dist-info/AUTHORS.rst', 'example_sub_moudle_a-0.0.0.dist-info/LICENSE', 'example_sub_moudle_a-0.0.0.dist-info/METADATA', 'example_sub_moudle_a-0.0.0.dist-info/WHEEL', 'example_sub_moudle_a-0.0.0.dist-info/top_level.txt', 'example_sub_moudle_a-0.0.0.dist-info/RECORD', } where = wheel_a.open('example/sub_module_a/where.py').read() assert where == b'a = "module_a"\n' with WheelFile(wheel_b_path) as wheel_b: assert set(wheel_b.namelist()) == { 'example/sub_module_b/__init__.py', 'example/sub_module_b/where.py', 'example_sub_moudle_b-0.0.0.dist-info/AUTHORS.rst', 'example_sub_moudle_b-0.0.0.dist-info/LICENSE', 'example_sub_moudle_b-0.0.0.dist-info/METADATA', 'example_sub_moudle_b-0.0.0.dist-info/WHEEL', 'example_sub_moudle_b-0.0.0.dist-info/top_level.txt', 'example_sub_moudle_b-0.0.0.dist-info/RECORD', } where = wheel_b.open('example/sub_module_b/where.py').read() assert where == b'a = "module_b"\n' def test_sdist(tmp_path): # Build both dists in the same test, so we can check there is no cross-polution build_dist('example/sub_module_a', 'sdist', tmp_path) build_dist('example/sub_module_b', 'sdist', tmp_path) sdist_a_path = tmp_path / 'example_sub_moudle_a-0.0.0.tar.gz' sdist_b_path = tmp_path / 'example_sub_moudle_b-0.0.0.tar.gz' assert sdist_a_path.exists(), "sub_module_a sdist file exists" assert sdist_b_path.exists(), "sub_module_b sdist file exists" with tarfile.open(sdist_a_path) as sdist_a: assert set(sdist_a.getnames()) == { 'example_sub_moudle_a-0.0.0', 'example_sub_moudle_a-0.0.0/AUTHORS.rst', 'example_sub_moudle_a-0.0.0/LICENSE', 'example_sub_moudle_a-0.0.0/PKG-INFO', 'example_sub_moudle_a-0.0.0/example', 'example_sub_moudle_a-0.0.0/example/sub_module_a', 'example_sub_moudle_a-0.0.0/example/sub_module_a/__init__.py', 'example_sub_moudle_a-0.0.0/example/sub_module_a/where.py', 'example_sub_moudle_a-0.0.0/example_sub_moudle_a.egg-info', 'example_sub_moudle_a-0.0.0/example_sub_moudle_a.egg-info/PKG-INFO', 'example_sub_moudle_a-0.0.0/example_sub_moudle_a.egg-info/SOURCES.txt', 'example_sub_moudle_a-0.0.0/example_sub_moudle_a.egg-info/dependency_links.txt', 'example_sub_moudle_a-0.0.0/example_sub_moudle_a.egg-info/not-zip-safe', 'example_sub_moudle_a-0.0.0/example_sub_moudle_a.egg-info/top_level.txt', 'example_sub_moudle_a-0.0.0/setup.cfg', 'example_sub_moudle_a-0.0.0/setup.py', } where = sdist_a.extractfile('example_sub_moudle_a-0.0.0/example/sub_module_a/where.py').read() assert where == b'a = "module_a"\n' setup_cfg = sdist_a.extractfile('example_sub_moudle_a-0.0.0/setup.cfg').read().decode('ascii') assert setup_cfg == (ROOT / 'example' / 'example' / 'sub_module_a' / 'setup.cfg').open(encoding='ascii').read() with tarfile.open(sdist_b_path) as sdist_b: assert set(sdist_b.getnames()) == { 'example_sub_moudle_b-0.0.0', 'example_sub_moudle_b-0.0.0/AUTHORS.rst', 'example_sub_moudle_b-0.0.0/LICENSE', 'example_sub_moudle_b-0.0.0/PKG-INFO', 'example_sub_moudle_b-0.0.0/example', 'example_sub_moudle_b-0.0.0/example/sub_module_b', 'example_sub_moudle_b-0.0.0/example/sub_module_b/__init__.py', 'example_sub_moudle_b-0.0.0/example/sub_module_b/where.py', 'example_sub_moudle_b-0.0.0/example_sub_moudle_b.egg-info', 'example_sub_moudle_b-0.0.0/example_sub_moudle_b.egg-info/PKG-INFO', 'example_sub_moudle_b-0.0.0/example_sub_moudle_b.egg-info/SOURCES.txt', 'example_sub_moudle_b-0.0.0/example_sub_moudle_b.egg-info/dependency_links.txt', 'example_sub_moudle_b-0.0.0/example_sub_moudle_b.egg-info/not-zip-safe', 'example_sub_moudle_b-0.0.0/example_sub_moudle_b.egg-info/top_level.txt', 'example_sub_moudle_b-0.0.0/setup.cfg', 'example_sub_moudle_b-0.0.0/setup.py', } where = sdist_b.extractfile('example_sub_moudle_b-0.0.0/example/sub_module_b/where.py').read() assert where == b'a = "module_b"\n' setup_cfg = sdist_b.extractfile('example_sub_moudle_b-0.0.0/setup.cfg').read().decode('ascii') assert setup_cfg == (ROOT / 'example' / 'example' / 'sub_module_b' / 'setup.cfg').open(encoding='ascii').read() def test_license_template(tmp_path): build_dist('example/sub_module_a', 'sdist', tmp_path, '--license-template', ROOT / 'LICENSE') sdist_a_path = tmp_path / 'example_sub_moudle_a-0.0.0.tar.gz' assert sdist_a_path.exists(), "sub_module_a sdist file exists" with tarfile.open(sdist_a_path) as sdist_a: setup_py = sdist_a.extractfile('example_sub_moudle_a-0.0.0/setup.py').read().decode('ascii') assert setup_py == textwrap.dedent( """\ # Apache Software License 2.0 # # Copyright (c) 2020, <NAME>. # # 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 # # https://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__("setuptools").setup() """ )
[ "textwrap.dedent", "tarfile.open", "pathlib.Path", "setuptools.setup", "os.getcwd", "os.chdir", "wheel.wheelfile.WheelFile" ]
[((444, 455), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (453, 455), False, 'import os\n'), ((460, 479), 'os.chdir', 'os.chdir', (['"""example"""'], {}), "('example')\n", (468, 479), False, 'import os\n'), ((185, 199), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (189, 199), False, 'from pathlib import Path\n'), ((498, 556), 'setuptools.setup', 'setuptools.setup', ([], {'distclass': 'Distribution', 'script_args': 'args'}), '(distclass=Distribution, script_args=args)\n', (514, 556), False, 'import setuptools\n'), ((613, 626), 'os.chdir', 'os.chdir', (['cur'], {}), '(cur)\n', (621, 626), False, 'import os\n'), ((1096, 1119), 'wheel.wheelfile.WheelFile', 'WheelFile', (['wheel_a_path'], {}), '(wheel_a_path)\n', (1105, 1119), False, 'from wheel.wheelfile import WheelFile\n'), ((1771, 1794), 'wheel.wheelfile.WheelFile', 'WheelFile', (['wheel_b_path'], {}), '(wheel_b_path)\n', (1780, 1794), False, 'from wheel.wheelfile import WheelFile\n'), ((2942, 2968), 'tarfile.open', 'tarfile.open', (['sdist_a_path'], {}), '(sdist_a_path)\n', (2954, 2968), False, 'import tarfile\n'), ((4479, 4505), 'tarfile.open', 'tarfile.open', (['sdist_b_path'], {}), '(sdist_b_path)\n', (4491, 4505), False, 'import tarfile\n'), ((6288, 6314), 'tarfile.open', 'tarfile.open', (['sdist_a_path'], {}), '(sdist_a_path)\n', (6300, 6314), False, 'import tarfile\n'), ((6456, 7332), 'textwrap.dedent', 'textwrap.dedent', (['""" # Apache Software License 2.0\n #\n # Copyright (c) 2020, <NAME>.\n #\n # Licensed under the Apache License, Version 2.0 (the "License");\n # you may not use this file except in compliance with the License.\n # You may obtain a copy of the License at\n #\n # https://www.apache.org/licenses/LICENSE-2.0\n #\n # Unless required by applicable law or agreed to in writing, software\n # distributed under the License is distributed on an "AS IS" BASIS,\n # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n # See the License for the specific language governing permissions and\n # limitations under the License.\n\n __import__("setuptools").setup()\n """'], {}), '(\n """ # Apache Software License 2.0\n #\n # Copyright (c) 2020, <NAME>.\n #\n # Licensed under the Apache License, Version 2.0 (the "License");\n # you may not use this file except in compliance with the License.\n # You may obtain a copy of the License at\n #\n # https://www.apache.org/licenses/LICENSE-2.0\n #\n # Unless required by applicable law or agreed to in writing, software\n # distributed under the License is distributed on an "AS IS" BASIS,\n # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n # See the License for the specific language governing permissions and\n # limitations under the License.\n\n __import__("setuptools").setup()\n """\n )\n', (6471, 7332), False, 'import textwrap\n')]
import matplotlib.pyplot as plt import matplotlib.gridspec as gs import numpy as np import pandas as pd import csv from matplotlib.lines import Line2D epsilon = pd.read_pickle('epsilon.pkl') def plots_with_sizes(result_folder, query, attribute): if attribute == 'age': d = 1 if attribute == 'hrs': d = 2 if attribute == 'absences': d = 3 if attribute == 'grade': d = 4 ################# Std of scaled error ###################### diffprivlib_std = pd.read_csv(result_folder + "\\diffprivlib\\{q}\\results_dataset_{d}\\std_scaled_error\\DP_std_scaled_error.csv".format(q=query,d=d), header=None) smartnoise_std = pd.read_csv(result_folder + "\\smartnoise\\{q}\\results_dataset_{d}\\std_scaled_error\\DP_std_scaled_error.csv".format(q=query,d=d), header=None) pydp_std = pd.read_csv(result_folder + "\\pydp\\{q}\\results_dataset_{d}\\std_scaled_error\\DP_std_scaled_error.csv".format(q=query,d=d), header=None) diffpriv_std = pd.read_csv(result_folder + "\\diffpriv_simple\\{q}\\results_dataset_{d}\\std_scaled_error\\std_scaled_error.csv".format(q=query,d=d), header=None) #chorus_std = pd.read_csv(result_folder + "\\chorus_real_dataset_results\\{q}\\results_dataset_{d}\\std_scaled_error\\DP_std_scaled_error.csv".format(q=query,d=d), header=None) ################# Mean relative error ###################### diffprivlib_relative = pd.read_csv(result_folder + "\\diffprivlib\\{q}\\results_dataset_{d}\\mean_relative_error\\DP_mean_relative_error.csv".format(q=query,d=d), header=None) smartnoise_relative = pd.read_csv(result_folder + "\\smartnoise\\{q}\\results_dataset_{d}\\mean_relative_error\\DP_mean_relative_error.csv".format(q=query,d=d), header=None) pydp_relative = pd.read_csv(result_folder + "\\pydp\\{q}\\results_dataset_{d}\\mean_relative_error\\DP_mean_relative_error.csv".format(q=query,d=d), header=None) diffpriv_relative = pd.read_csv(result_folder + "\\diffpriv_simple\\{q}\\results_dataset_{d}\\mean_relative_error\\mean_relative_error.csv".format(q=query,d=d), header=None) #chorus_relative = pd.read_csv(result_folder + "\\chorus_real_dataset_results\\{q}\\results_dataset_{d}\\mean_relative_error\\DP_mean_relative_error.csv".format(q=query,d=d), header=None) ################ labels ###################### x1 = [0.01,0,0,0,0,0,0,0,0, 0.1 ,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0, 0,0, 0,0, 1, 0,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,0,100] x2 = [0.01,0,0,0,0,0,0,0,0, 0.1 ,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0, 0,0, 0,0, 1, 0,0,0,0,0,0,0,0,10,0,0,0,0,0,0,0,0,100] ################ Plotting ###################### gs1 = gs.GridSpec(nrows=1, ncols=2) gs1.update(wspace=0.3, hspace=0.05) # set the spacing between axes. figure = plt.gcf() # get current figure figure.clf() ###### Size plot ####### ax1 = plt.subplot(gs1[0,0]) ax1.plot(x1, diffprivlib_std, "o", markeredgecolor='k', mfc='none') ax1.plot(epsilon, diffprivlib_std, color = 'xkcd:orangish red') ax1.plot(x1, smartnoise_std[1:], "o", markeredgecolor='k', mfc='none') ax1.plot(epsilon, smartnoise_std[1:], color = 'xkcd:moss green') ax1.plot(x1, pydp_std, "o", markeredgecolor='k', mfc='none') ax1.plot(epsilon, pydp_std, color = 'xkcd:soft blue') ax1.plot(x1, diffpriv_std, "o", markeredgecolor='k', mfc='none') ax1.plot(epsilon, diffpriv_std, color = 'xkcd:aquamarine') #ax1.plot(x1, chorus_std, "o", markeredgecolor='k', mfc='none') #ax1.plot(epsilon, chorus_std, color = 'xkcd:purple') ax1.set_xlabel('ε', fontsize = 12) ax1.set_ylabel('Sample Std of the \n Absolute Scaled Error', fontsize = 16) ################# MEAN RELATIVE ERROR ############################ ax2 = plt.subplot(gs1[0,1]) ax2.plot(x2, abs(diffprivlib_relative)*100, "o", markeredgecolor='k', mfc='none') ax2.plot(epsilon, abs(diffprivlib_relative)*100, color = 'xkcd:orangish red', label="diffprivlib, IBM (Python)") ax2.plot(x2, abs(smartnoise_relative[1:])*100, "o", markeredgecolor='k', mfc='none') ax2.plot(epsilon, abs(smartnoise_relative[1:])*100, color = 'xkcd:moss green', label="SmartNoise, Microsoft (Python wrapper over Rust)") ax2.plot(x2, abs(pydp_relative)*100, "o", markeredgecolor='k', mfc='none') ax2.plot(epsilon, abs(pydp_relative)*100, color = 'xkcd:soft blue', label="PyDP (Python wrapper over Google DP C++)") ax2.plot(x2, abs(diffpriv_relative)*100, "o", markeredgecolor='k', mfc='none') ax2.plot(epsilon, abs(diffpriv_relative)*100, color = 'xkcd:aquamarine', label="diffpriv, <NAME>, et al. (R)") #ax2.plot(x2, abs(chorus_relative)*100, "o", markeredgecolor='k', mfc='none') #ax2.plot(epsilon, abs(chorus_relative)*100, color = 'xkcd:purple', label="<NAME>ear et al (Scala)") ax2.set_xlabel('ε', fontsize = 12) ax2.set_ylabel('Sample Mean of the \n Relative Error [%]', fontsize = 16) #ax1.legend(prop={'size': 19}, loc="lower center", bbox_to_anchor=(1.00, -0.02), frameon=False, ncol=4, handletextpad=0.2, handlelength=1, columnspacing=0.5) #ax2.legend(prop={'size': 18}, loc="lower center", bbox_to_anchor=(-0.13, -0.30), frameon=False, ncol=2, handletextpad=0.2, handlelength=1, columnspacing=0.5) figure.subplots_adjust(bottom=0.30) #legend_elements_1 = [Line2D([1], [1], color='xkcd:orangish red', label='diffprivlib, IBM (Python)'), Line2D([1], [1], color='xkcd:soft blue', label='PyDP (Python wrapper over Google DP C++)'), Line2D([1], [1], color='xkcd:moss green', label='SmartNoise, Microsoft (Python wrapper over Rust)')] #figure.legend(prop={'size': 18.5},handles=legend_elements_1, loc="lower center", bbox_to_anchor=(0.33, -0.02), frameon=False, ncol=1, handletextpad=0.2, handlelength=1) #legend_elements_2 = [ Line2D([1], [1], color='xkcd:aquamarine', label='diffpriv, <NAME>, et al. (R)'), Line2D([1], [1], color='xkcd:purple', label='<NAME>ear et al (Scala)')] #legend_elements_2 = [ Line2D([1], [1], color='xkcd:aquamarine', label='diffpriv, <NAME>, et al. (R)')] #figure.legend(prop={'size': 18.5},handles=legend_elements_2, loc="lower center", bbox_to_anchor=(0.77, 0.1), frameon=False, ncol=1, handletextpad=0.2, handlelength=1) if query == 'count': ax1.set_ylim(10**-8, 10**3) figure.suptitle('Count Query', fontsize=19) if query == 'sum': ax1.set_ylim(10**-8, 10**8) figure.suptitle('Sum Query', fontsize=19) if query == 'mean': ax1.set_ylim(10**-12, 10**2) figure.suptitle('Mean Query', fontsize=19) if query == 'var': ax1.set_ylim(10**-8, 10**4) figure.suptitle('Variance Query', fontsize=19) ax1.tick_params(axis='both', which='major', labelsize=16) ax2.tick_params(axis='both', which='major', labelsize=16) ax1.loglog() ax2.set_xscale('log') plt.show() plots_with_sizes(result_folder="E:\\MS_Thesis\\publication_stuff\\results_Jan_2021\\real_dataset_micro\\22April2021", query="var", attribute='grade')
[ "pandas.read_pickle", "matplotlib.pyplot.gcf", "matplotlib.gridspec.GridSpec", "matplotlib.pyplot.subplot", "matplotlib.pyplot.show" ]
[((161, 190), 'pandas.read_pickle', 'pd.read_pickle', (['"""epsilon.pkl"""'], {}), "('epsilon.pkl')\n", (175, 190), True, 'import pandas as pd\n'), ((2777, 2806), 'matplotlib.gridspec.GridSpec', 'gs.GridSpec', ([], {'nrows': '(1)', 'ncols': '(2)'}), '(nrows=1, ncols=2)\n', (2788, 2806), True, 'import matplotlib.gridspec as gs\n'), ((2892, 2901), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (2899, 2901), True, 'import matplotlib.pyplot as plt\n'), ((2985, 3007), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs1[0, 0]'], {}), '(gs1[0, 0])\n', (2996, 3007), True, 'import matplotlib.pyplot as plt\n'), ((3878, 3900), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs1[0, 1]'], {}), '(gs1[0, 1])\n', (3889, 3900), True, 'import matplotlib.pyplot as plt\n'), ((6972, 6982), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6980, 6982), True, 'import matplotlib.pyplot as plt\n')]
from django.db import models from ozpcenter.utils import get_now_utc from .import_task import ImportTask class ImportTaskResultManager(models.Manager): def get_queryset(self): return super().get_queryset() def find_all(self): return self.all() def find_by_id(self, id): return self.get(id=id) def find_all_by_import_task(self, import_task_pk): return self.filter(import_task=import_task_pk) def create_result(self, import_task_id, result, message): result = self.create(import_task_id=import_task_id, result=result, message=message) ImportTask.objects.filter(id=import_task_id).update(last_run_result=result.id) return result class ImportTaskResult(models.Model): """ Import Task Result Represents the results of an import task that has been run previously """ class Meta: db_table = 'import_task_result' objects = ImportTaskResultManager() RESULT_PASS = 'Pass' RESULT_FAIL = 'Fail' RESULT_CHOICES = ( (RESULT_PASS, 'Pass'), (RESULT_FAIL, 'Fail'), ) import_task = models.ForeignKey(ImportTask, related_name="results") run_date = models.DateTimeField(default=get_now_utc) result = models.CharField(max_length=4, choices=RESULT_CHOICES) message = models.CharField(max_length=4000, null=False) def __repr__(self): return '{0!s} | Date: {1!s} | Result: {2!s}'.format(self.import_task, self.run_date, self.result) def __str__(self): return '{0!s} | Date: {1!s} | Result: {2!s}'.format(self.import_task, self.run_date, self.result)
[ "django.db.models.DateTimeField", "django.db.models.CharField", "django.db.models.ForeignKey" ]
[((1123, 1176), 'django.db.models.ForeignKey', 'models.ForeignKey', (['ImportTask'], {'related_name': '"""results"""'}), "(ImportTask, related_name='results')\n", (1140, 1176), False, 'from django.db import models\n'), ((1192, 1233), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'default': 'get_now_utc'}), '(default=get_now_utc)\n', (1212, 1233), False, 'from django.db import models\n'), ((1247, 1301), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(4)', 'choices': 'RESULT_CHOICES'}), '(max_length=4, choices=RESULT_CHOICES)\n', (1263, 1301), False, 'from django.db import models\n'), ((1316, 1361), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(4000)', 'null': '(False)'}), '(max_length=4000, null=False)\n', (1332, 1361), False, 'from django.db import models\n')]
""" Loading utilities for computational experiments. """ import os import pandas as pd DATA_DIR = os.path.dirname(os.path.abspath(__file__)) def load_zT(all_data=False): """ Thermoelectric figures of merit for 165 experimentally measured compounds. Obtained from the Citrination database maintained by Citrine, Inc. Citrine obtained from Review https://doi.org/10.1021/cm400893e which took measurements at 300K from many original publications. All samples are - Measured at 300K (within 0.01 K) - polycrystalline If all_data is loaded, the columns are: - composition: composition as a string - zT: thermoelectric figure of merit - PF (W/m.K2): power factor - k (W/m.K): overall thermal conductivity - S (uV/K): Seebeck coefficient - log rho: Log resistivity, presumably in ohm-meters. Args: all_data (bool): Whether all data will be returned in the df. If False, only the compositions as strings and the zT measurements will be loaded. Returns: (pd.DataFrame): The dataframe containing the zT data. """ path = os.path.join(DATA_DIR, "zT-citrination-165.csv") df = pd.read_csv(path, index_col=None) if not all_data: df = df[["composition", "zT"]] return df def load_e_form(): """ 85,014 DFT-GGA computed formation energies. Ground state formation energies from the Materials Project, adapted from https://github.com/CJBartel/TestStabilityML/blob/master/mlstabilitytest/mp_data/data.py originally gathered from the Materials Project via MAPI on Nov 6, 2019. There is exactly one formation energy per composition. The formation energy was chosen as the ground state energy among all sructures with the desired composition. Returns: (pd.DataFrame): The formation energies and compositions """ path = os.path.join(DATA_DIR, "eform-materialsproject-85014.csv") df = pd.read_csv(path, index_col="mpid") return df def load_expt_gaps(): """ 4,604 experimental band gaps, one per composition. Matbench v0.1 test dataset for predicting experimental band gap from composition alone. Retrieved from Zhuo et al (https:doi.org/10.1021/acs.jpclett.8b00124) supplementary information. Deduplicated according to composition, removing compositions with reported band gaps spanning more than a 0.1eV range; remaining compositions were assigned values based on the closest experimental value to the mean experimental value for that composition among all reports. Returns: (pd.DataFrame): Experimental band gaps and compositions as strings """ path = os.path.join(DATA_DIR, "bandgap-zhuo-4604.csv") df = pd.read_csv(path, index_col=False) return df def load_steels(): """ 312 yeild strengths of various steels. Matbench v0.1 dataset for predicting steel yield strengths from chemical composition alone. Retrieved from Citrine informatics. Deduplicated. Experimentally measured steel yield strengths, in GPa. https://citrination.com/datasets/153092/ Returns: (pd.DataFrame): Dataframe of yield strengths per composition. """ path = os.path.join(DATA_DIR, "yieldstrength-citrination-312.csv") df = pd.read_csv(path, index_col=False) return df if __name__ == "__main__": df = load_steels() print(df)
[ "os.path.abspath", "os.path.join", "pandas.read_csv" ]
[((116, 141), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (131, 141), False, 'import os\n'), ((1137, 1185), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""zT-citrination-165.csv"""'], {}), "(DATA_DIR, 'zT-citrination-165.csv')\n", (1149, 1185), False, 'import os\n'), ((1195, 1228), 'pandas.read_csv', 'pd.read_csv', (['path'], {'index_col': 'None'}), '(path, index_col=None)\n', (1206, 1228), True, 'import pandas as pd\n'), ((1900, 1958), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""eform-materialsproject-85014.csv"""'], {}), "(DATA_DIR, 'eform-materialsproject-85014.csv')\n", (1912, 1958), False, 'import os\n'), ((1968, 2003), 'pandas.read_csv', 'pd.read_csv', (['path'], {'index_col': '"""mpid"""'}), "(path, index_col='mpid')\n", (1979, 2003), True, 'import pandas as pd\n'), ((2702, 2749), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""bandgap-zhuo-4604.csv"""'], {}), "(DATA_DIR, 'bandgap-zhuo-4604.csv')\n", (2714, 2749), False, 'import os\n'), ((2759, 2793), 'pandas.read_csv', 'pd.read_csv', (['path'], {'index_col': '(False)'}), '(path, index_col=False)\n', (2770, 2793), True, 'import pandas as pd\n'), ((3239, 3298), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""yieldstrength-citrination-312.csv"""'], {}), "(DATA_DIR, 'yieldstrength-citrination-312.csv')\n", (3251, 3298), False, 'import os\n'), ((3308, 3342), 'pandas.read_csv', 'pd.read_csv', (['path'], {'index_col': '(False)'}), '(path, index_col=False)\n', (3319, 3342), True, 'import pandas as pd\n')]
import json def get_qtypes(dataset_name, part): """Return list of question-types for a particular TriviaQA-CP dataset""" if dataset_name not in {"location", "person"}: raise ValueError("Unknown dataset %s" % dataset_name) if part not in {"train", "dev", "test"}: raise ValueError("Unknown part %s" % part) is_biased = part in {"train", "dev"} is_location = dataset_name == "location" if is_biased and is_location: return ["person", "other"] elif not is_biased and is_location: return ["location"] elif is_biased and not is_location: return ["location", "other"] elif not is_biased and not is_location: return ["person"] else: raise RuntimeError() def load_triviaqa_cp(filename, dataset_name, part, expected_version=None): """Load a TriviaQA-CP dataset :param filename: The TriviaQA-CP train or dev json file, must be the train file if if `part`=="train" and the dev file otherwise :param dataset_name: dataset to load, must be in ["person", "location"] :param part: which part, must be in ["test", "dev", "train"[ :param expected_version: Optional version to require the data to match :return: List of question in dictionary form """ target_qtypes = get_qtypes(dataset_name, part) with open(filename, "r") as f: data = json.load(f) if expected_version is not None: if expected_version != data["Version"]: raise ValueError("Expected version %s, but data was version %s" % ( expected_version, data["Version"])) if part == "train": if data["Split"] != "Train": raise ValueError("Expected train file, but split is %s" % data["Split"]) else: if data["Split"] != "Dev": raise ValueError("Expected dev file, but split is %s" % data["Split"]) out = [] for question in data["Data"]: if question["QuestionType"] in target_qtypes: out.append(question) return out
[ "json.load" ]
[((1317, 1329), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1326, 1329), False, 'import json\n')]
import datetime import pytz from tws_async import * stocks = [ Stock('TSLA'), Stock('AAPL'), Stock('GOOG'), Stock('INTC', primaryExchange='NASDAQ') ] forexs = [ Forex('EURUSD'), Forex('GBPUSD'), Forex('USDJPY') ] endDate = datetime.date.today() startDate = endDate - datetime.timedelta(days=7) histReqs = [] for date in util.dateRange(startDate, endDate): histReqs += [HistRequest(stock, date) for stock in stocks] histReqs += [HistRequest(forex, date, whatToShow='MIDPOINT', durationStr='30 D', barSizeSetting='1 day') for forex in forexs] timezone = datetime.timezone.utc # timezone = pytz.timezone('Europe/Amsterdam') # timezone = pytz.timezone('US/Eastern') util.logToConsole() tws = HistRequester() tws.connect('127.0.0.1', 7497, clientId=1) task = tws.download(histReqs, rootDir='data', timezone=timezone) tws.run(task)
[ "datetime.date.today", "datetime.timedelta" ]
[((254, 275), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (273, 275), False, 'import datetime\n'), ((298, 324), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(7)'}), '(days=7)\n', (316, 324), False, 'import datetime\n')]
"""cff2Lib_test.py -- unit test for Adobe CFF fonts.""" from fontTools.ttLib import TTFont from io import StringIO import re import os import unittest CURR_DIR = os.path.abspath(os.path.dirname(os.path.realpath(__file__))) DATA_DIR = os.path.join(CURR_DIR, 'data') CFF_TTX = os.path.join(DATA_DIR, "C_F_F__2.ttx") CFF_BIN = os.path.join(DATA_DIR, "C_F_F__2.bin") def strip_VariableItems(string): # ttlib changes with the fontTools version string = re.sub(' ttLibVersion=".*"', '', string) # head table checksum and mod date changes with each save. string = re.sub('<checkSumAdjustment value="[^"]+"/>', '', string) string = re.sub('<modified value="[^"]+"/>', '', string) return string class CFFTableTest(unittest.TestCase): @classmethod def setUpClass(cls): with open(CFF_BIN, 'rb') as f: font = TTFont(file=CFF_BIN) cffTable = font['CFF2'] cls.cff2Data = cffTable.compile(font) with open(CFF_TTX, 'r') as f: cff2XML = f.read() cff2XML = strip_VariableItems(cff2XML) cls.cff2XML = cff2XML.splitlines() def test_toXML(self): font = TTFont(file=CFF_BIN) cffTable = font['CFF2'] cffData = cffTable.compile(font) out = StringIO() font.saveXML(out) cff2XML = out.getvalue() cff2XML = strip_VariableItems(cff2XML) cff2XML = cff2XML.splitlines() self.assertEqual(cff2XML, self.cff2XML) def test_fromXML(self): font = TTFont(sfntVersion='OTTO') font.importXML(CFF_TTX) cffTable = font['CFF2'] cff2Data = cffTable.compile(font) self.assertEqual(cff2Data, self.cff2Data) if __name__ == "__main__": unittest.main()
[ "os.path.join", "os.path.realpath", "unittest.main", "re.sub", "io.StringIO", "fontTools.ttLib.TTFont" ]
[((237, 267), 'os.path.join', 'os.path.join', (['CURR_DIR', '"""data"""'], {}), "(CURR_DIR, 'data')\n", (249, 267), False, 'import os\n'), ((279, 317), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""C_F_F__2.ttx"""'], {}), "(DATA_DIR, 'C_F_F__2.ttx')\n", (291, 317), False, 'import os\n'), ((328, 366), 'os.path.join', 'os.path.join', (['DATA_DIR', '"""C_F_F__2.bin"""'], {}), "(DATA_DIR, 'C_F_F__2.bin')\n", (340, 366), False, 'import os\n'), ((462, 502), 're.sub', 're.sub', (['""" ttLibVersion=".*\\""""', '""""""', 'string'], {}), '(\' ttLibVersion=".*"\', \'\', string)\n', (468, 502), False, 'import re\n'), ((579, 636), 're.sub', 're.sub', (['"""<checkSumAdjustment value="[^"]+"/>"""', '""""""', 'string'], {}), '(\'<checkSumAdjustment value="[^"]+"/>\', \'\', string)\n', (585, 636), False, 'import re\n'), ((650, 697), 're.sub', 're.sub', (['"""<modified value="[^"]+"/>"""', '""""""', 'string'], {}), '(\'<modified value="[^"]+"/>\', \'\', string)\n', (656, 697), False, 'import re\n'), ((1745, 1760), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1758, 1760), False, 'import unittest\n'), ((197, 223), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (213, 223), False, 'import os\n'), ((1173, 1193), 'fontTools.ttLib.TTFont', 'TTFont', ([], {'file': 'CFF_BIN'}), '(file=CFF_BIN)\n', (1179, 1193), False, 'from fontTools.ttLib import TTFont\n'), ((1281, 1291), 'io.StringIO', 'StringIO', ([], {}), '()\n', (1289, 1291), False, 'from io import StringIO\n'), ((1529, 1555), 'fontTools.ttLib.TTFont', 'TTFont', ([], {'sfntVersion': '"""OTTO"""'}), "(sfntVersion='OTTO')\n", (1535, 1555), False, 'from fontTools.ttLib import TTFont\n'), ((857, 877), 'fontTools.ttLib.TTFont', 'TTFont', ([], {'file': 'CFF_BIN'}), '(file=CFF_BIN)\n', (863, 877), False, 'from fontTools.ttLib import TTFont\n')]
import logging import threading import time from pajbot.managers.db import DBManager from pajbot.managers.schedule import ScheduleManager from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo from pajbot.models.user import User log = logging.getLogger("pajbot") WIDGET_ID = 4 class SongrequestManager: def __init__(self, bot): self.bot = bot self.enabled = False self.current_song_id = None self.showVideo = None self.isVideoShowing = None self.youtube = None self.settings = None self.previously_playing_spotify = None self.paused = None self.module_opened = None self.previous_queue = None self.true_volume = None def enable(self, settings, youtube): self.enabled = True self.showVideo = False self.isVideoShowing = True self.youtube = youtube self.settings = settings self.current_song_id = None self.previously_playing_spotify = False self.paused = False self.module_opened = False self.previous_queue = 0 self.true_volume = int(self.settings["volume"]) thread = threading.Thread(target=self.inc_current_song, daemon=True) thread.start() def volume_val(self): return int(self.true_volume * (100 / int(self.settings["volume_multiplier"]))) def to_true_volume(self, multiplied_volume): return int(multiplied_volume * int(self.settings["volume_multiplier"]) / 100) def disable(self): self.enabled = False self.paused = False self.settings = None self.youtube = None self.current_song_id = None self.module_opened = False def open_module_function(self): if not self.enabled: return False if not self.module_opened: self.module_opened = True self.paused = False if not self.current_song_id: self.load_song() return True return False def close_module_function(self): if not self.enabled: return False if self.module_opened: self.module_opened = False self.paused = False return True return False def skip_function(self, skipped_by): with DBManager.create_session_scope() as db_session: skipped_by = User.find_by_user_input(db_session, skipped_by) if not skipped_by: return skipped_by_id = skipped_by.id if not self.enabled and self.current_song_id: return False self.load_song(skipped_by_id) return True def previous_function(self, requested_by): if not self.enabled: return False with DBManager.create_session_scope() as db_session: requested_by = User.find_by_user_input(db_session, requested_by) if not requested_by: return requested_by_id = requested_by.id SongrequestHistory._insert_previous(db_session, requested_by_id, self.previous_queue) db_session.commit() self.previous_queue += 1 self.load_song(requested_by_id) return True def pause_function(self): if not self.enabled or not self.current_song_id: return False if not self.paused: self.paused = True self._pause() return True return False def resume_function(self): if not self.enabled or not self.current_song_id: return False if self.paused: self.paused = False self._resume() if not self.current_song_id and self.module_opened: self.load_song() return True return False def seek_function(self, _time): if not self.enabled: return False if self.current_song_id: with DBManager.create_session_scope() as db_session: current_song = SongrequestQueue._from_id(db_session, self.current_song_id) current_song.current_song_time = _time self._seek(_time) return True return False def volume_function(self, volume): if not self.enabled: return False self.true_volume = self.to_true_volume(volume) self._volume() return True def play_function(self, database_id, skipped_by): if not self.enabled: return False with DBManager.create_session_scope() as db_session: skipped_by = User.find_by_user_input(db_session, skipped_by) if not skipped_by: return skipped_by_id = skipped_by.id song = SongrequestQueue._from_id(db_session, database_id) song._move_song(db_session, 1) db_session.commit() self.load_song(skipped_by_id) SongrequestQueue._update_queue() return True def move_function(self, database_id, to_id): if not self.enabled: return False with DBManager.create_session_scope() as db_session: song = SongrequestQueue._from_id(db_session, database_id) song._move_song(db_session, to_id) db_session.commit() self._playlist() SongrequestQueue._update_queue() return True def request_function(self, video_id, requested_by, queue=None): if not self.enabled: return False with DBManager.create_session_scope() as db_session: requested_by = User.find_by_user_input(db_session, requested_by) if not requested_by: return False requested_by_id = requested_by.id song_info = SongRequestSongInfo._create_or_get(db_session, video_id, self.youtube) if not song_info: log.error("There was an error!") return False skip_after = ( self.settings["max_song_length"] if song_info.duration > self.settings["max_song_length"] else None ) song = SongrequestQueue._create(db_session, video_id, skip_after, requested_by_id) if queue: song._move_song(db_session, queue) db_session.commit() SongrequestQueue._update_queue() return True def replay_function(self, requested_by): if not self.enabled: return False with DBManager.create_session_scope() as db_session: requested_by = User.find_by_user_input(db_session, requested_by) if not requested_by: return False requested_by_id = requested_by.id current_song = SongrequestQueue._from_id(db_session, self.current_song_id) self.request_function(current_song.video_id, current_song.requested_by_id, 1) db_session.commit() self.load_song(requested_by_id) SongrequestQueue._update_queue() return True def requeue_function(self, database_id, requested_by): if not self.enabled: return False with DBManager.create_session_scope() as db_session: requested_by = User.find_by_user_input(db_session, requested_by) if not requested_by: return False requested_by_id = requested_by.id SongrequestHistory._from_id(db_session, database_id).requeue(db_session, requested_by_id) db_session.commit() SongrequestQueue._update_queue() self._playlist() return True def show_function(self): if not self.enabled: return False if not self.showVideo: self.showVideo = True if not self.paused: self._show() return True return False def hide_function(self): if not self.enabled: return False if self.showVideo: self.showVideo = False self._hide() return True return False def remove_function(self, database_id): if not self.enabled: return False with DBManager.create_session_scope() as db_session: song = SongrequestQueue._from_id(db_session, database_id) song._remove(db_session) db_session.commit() SongrequestQueue._update_queue() self._playlist() return True def inc_current_song(self): while True: if not self.enabled: break if self.current_song_id: if not self.paused: try: with DBManager.create_session_scope() as db_session: current_song = SongrequestQueue._from_id(db_session, self.current_song_id) next_song = SongrequestQueue._get_next_song(db_session) if not current_song or ( current_song.skip_after and current_song.skip_after < current_song.current_song_time + 10 ): self.load_song() else: if (not current_song.requested_by) and next_song and next_song.requested_by: self.load_song() current_song.current_song_time += 1 except Exception as e: log.error(e) elif self.module_opened: self.load_song() time.sleep(1) def load_song(self, skipped_by_id=None): if not self.enabled: return False if self.current_song_id: with DBManager.create_session_scope() as db_session: current_song = SongrequestQueue._from_id(db_session, self.current_song_id) if current_song: if current_song.current_song_time > 5: self.previous_queue = 0 histroy = current_song._to_histroy(db_session, skipped_by_id) if not histroy: log.info("History not added because stream is offline!") else: current_song._remove(db_session) self._stop_video() self._hide() db_session.commit() self._playlist_history() SongrequestQueue._update_queue() self.current_song_id = None if not self.module_opened: return False with DBManager.create_session_scope() as db_session: current_song = SongrequestQueue._get_current_song(db_session) if not current_song: current_song = SongrequestQueue._get_next_song(db_session) if current_song: current_song.playing = True current_song.queue = 0 current_song.current_song_time = 0 self.current_song_id = current_song.id song_info = current_song.song_info self._play( current_song.video_id, song_info.title, current_song.requested_by.username_raw if current_song.requested_by else "Backup list", ) if self.settings["use_spotify"]: is_playing, song_name, artistsArr = self.bot.spotify_api.state(self.bot.spotify_token_manager) if is_playing: self.bot.spotify_api.pause(self.bot.spotify_token_manager) self.previously_playing_spotify = True if not current_song.requested_by_id: SongrequestQueue._create( db_session, current_song.video_id, current_song.skip_after, None, SongrequestQueue._get_next_queue(db_session), ) db_session.commit() self._playlist() SongrequestQueue._update_queue() return True if self.settings["use_spotify"]: if self.previously_playing_spotify: self.bot.spotify_api.play(self.bot.spotify_token_manager) self.previously_playing_spotify = False if self.isVideoShowing: self._hide() return False def _play(self, video_id, video_title, requested_by_name): self.bot.songrequest_websocket_manager.emit( "play", {"video_id": video_id, "video_title": video_title, "requested_by": requested_by_name} ) self.bot.websocket_manager.emit("songrequest_play", WIDGET_ID, {"video_id": video_id}) self.paused = True if self.showVideo: self._show() self._playlist() def ready(self): self.resume_function() ScheduleManager.execute_delayed(2, self._volume) def _pause(self): self.bot.songrequest_websocket_manager.emit("pause", {}) self.bot.websocket_manager.emit("songrequest_pause", WIDGET_ID, {}) self._hide() def _resume(self): self.bot.songrequest_websocket_manager.emit("resume", {}) self.bot.websocket_manager.emit("songrequest_resume", WIDGET_ID, {"volume": self.true_volume}) self.paused = False if self.showVideo: self._show() def _volume(self): self.bot.songrequest_websocket_manager.emit("volume", {"volume": self.volume_val()}) self.bot.websocket_manager.emit("songrequest_volume", WIDGET_ID, {"volume": self.true_volume}) def _seek(self, _time): self.bot.songrequest_websocket_manager.emit("seek", {"seek_time": _time}) self.bot.websocket_manager.emit("songrequest_seek", WIDGET_ID, {"seek_time": _time}) self.paused = True def _show(self): self.bot.websocket_manager.emit("songrequest_show", WIDGET_ID, {}) self.isVideoShowing = True def _hide(self): self.bot.websocket_manager.emit("songrequest_hide", WIDGET_ID, {}) self.isVideoShowing = False def _playlist(self): with DBManager.create_session_scope() as db_session: playlist = SongrequestQueue._get_playlist(db_session, 15) self.bot.songrequest_websocket_manager.emit("playlist", {"playlist": playlist}) def _playlist_history(self): with DBManager.create_session_scope() as db_session: self.bot.songrequest_websocket_manager.emit( "history", {"history": SongrequestHistory._get_history(db_session, 15)} ) def _stop_video(self): self.bot.songrequest_websocket_manager.emit("stop", {}) self.bot.websocket_manager.emit("songrequest_stop", WIDGET_ID, {})
[ "logging.getLogger", "pajbot.models.songrequest.SongrequestQueue._get_current_song", "pajbot.models.songrequest.SongrequestHistory._get_history", "pajbot.models.songrequest.SongrequestHistory._insert_previous", "pajbot.models.songrequest.SongrequestQueue._get_next_queue", "pajbot.managers.db.DBManager.cre...
[((279, 306), 'logging.getLogger', 'logging.getLogger', (['"""pajbot"""'], {}), "('pajbot')\n", (296, 306), False, 'import logging\n'), ((1216, 1275), 'threading.Thread', 'threading.Thread', ([], {'target': 'self.inc_current_song', 'daemon': '(True)'}), '(target=self.inc_current_song, daemon=True)\n', (1232, 1275), False, 'import threading\n'), ((5004, 5036), 'pajbot.models.songrequest.SongrequestQueue._update_queue', 'SongrequestQueue._update_queue', ([], {}), '()\n', (5034, 5036), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((5404, 5436), 'pajbot.models.songrequest.SongrequestQueue._update_queue', 'SongrequestQueue._update_queue', ([], {}), '()\n', (5434, 5436), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((6394, 6426), 'pajbot.models.songrequest.SongrequestQueue._update_queue', 'SongrequestQueue._update_queue', ([], {}), '()\n', (6424, 6426), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((7050, 7082), 'pajbot.models.songrequest.SongrequestQueue._update_queue', 'SongrequestQueue._update_queue', ([], {}), '()\n', (7080, 7082), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((7605, 7637), 'pajbot.models.songrequest.SongrequestQueue._update_queue', 'SongrequestQueue._update_queue', ([], {}), '()\n', (7635, 7637), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((8461, 8493), 'pajbot.models.songrequest.SongrequestQueue._update_queue', 'SongrequestQueue._update_queue', ([], {}), '()\n', (8491, 8493), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((10604, 10636), 'pajbot.models.songrequest.SongrequestQueue._update_queue', 'SongrequestQueue._update_queue', ([], {}), '()\n', (10634, 10636), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((13140, 13188), 'pajbot.managers.schedule.ScheduleManager.execute_delayed', 'ScheduleManager.execute_delayed', (['(2)', 'self._volume'], {}), '(2, self._volume)\n', (13171, 13188), False, 'from pajbot.managers.schedule import ScheduleManager\n'), ((2367, 2399), 'pajbot.managers.db.DBManager.create_session_scope', 'DBManager.create_session_scope', ([], {}), '()\n', (2397, 2399), False, 'from pajbot.managers.db import DBManager\n'), ((2440, 2487), 'pajbot.models.user.User.find_by_user_input', 'User.find_by_user_input', (['db_session', 'skipped_by'], {}), '(db_session, skipped_by)\n', (2463, 2487), False, 'from pajbot.models.user import User\n'), ((2836, 2868), 'pajbot.managers.db.DBManager.create_session_scope', 'DBManager.create_session_scope', ([], {}), '()\n', (2866, 2868), False, 'from pajbot.managers.db import DBManager\n'), ((2911, 2960), 'pajbot.models.user.User.find_by_user_input', 'User.find_by_user_input', (['db_session', 'requested_by'], {}), '(db_session, requested_by)\n', (2934, 2960), False, 'from pajbot.models.user import User\n'), ((3075, 3165), 'pajbot.models.songrequest.SongrequestHistory._insert_previous', 'SongrequestHistory._insert_previous', (['db_session', 'requested_by_id', 'self.previous_queue'], {}), '(db_session, requested_by_id, self.\n previous_queue)\n', (3110, 3165), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((4596, 4628), 'pajbot.managers.db.DBManager.create_session_scope', 'DBManager.create_session_scope', ([], {}), '()\n', (4626, 4628), False, 'from pajbot.managers.db import DBManager\n'), ((4669, 4716), 'pajbot.models.user.User.find_by_user_input', 'User.find_by_user_input', (['db_session', 'skipped_by'], {}), '(db_session, skipped_by)\n', (4692, 4716), False, 'from pajbot.models.user import User\n'), ((4832, 4882), 'pajbot.models.songrequest.SongrequestQueue._from_id', 'SongrequestQueue._from_id', (['db_session', 'database_id'], {}), '(db_session, database_id)\n', (4857, 4882), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((5174, 5206), 'pajbot.managers.db.DBManager.create_session_scope', 'DBManager.create_session_scope', ([], {}), '()\n', (5204, 5206), False, 'from pajbot.managers.db import DBManager\n'), ((5241, 5291), 'pajbot.models.songrequest.SongrequestQueue._from_id', 'SongrequestQueue._from_id', (['db_session', 'database_id'], {}), '(db_session, database_id)\n', (5266, 5291), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((5593, 5625), 'pajbot.managers.db.DBManager.create_session_scope', 'DBManager.create_session_scope', ([], {}), '()\n', (5623, 5625), False, 'from pajbot.managers.db import DBManager\n'), ((5668, 5717), 'pajbot.models.user.User.find_by_user_input', 'User.find_by_user_input', (['db_session', 'requested_by'], {}), '(db_session, requested_by)\n', (5691, 5717), False, 'from pajbot.models.user import User\n'), ((5850, 5920), 'pajbot.models.songrequest.SongRequestSongInfo._create_or_get', 'SongRequestSongInfo._create_or_get', (['db_session', 'video_id', 'self.youtube'], {}), '(db_session, video_id, self.youtube)\n', (5884, 5920), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((6205, 6280), 'pajbot.models.songrequest.SongrequestQueue._create', 'SongrequestQueue._create', (['db_session', 'video_id', 'skip_after', 'requested_by_id'], {}), '(db_session, video_id, skip_after, requested_by_id)\n', (6229, 6280), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((6560, 6592), 'pajbot.managers.db.DBManager.create_session_scope', 'DBManager.create_session_scope', ([], {}), '()\n', (6590, 6592), False, 'from pajbot.managers.db import DBManager\n'), ((6635, 6684), 'pajbot.models.user.User.find_by_user_input', 'User.find_by_user_input', (['db_session', 'requested_by'], {}), '(db_session, requested_by)\n', (6658, 6684), False, 'from pajbot.models.user import User\n'), ((6820, 6879), 'pajbot.models.songrequest.SongrequestQueue._from_id', 'SongrequestQueue._from_id', (['db_session', 'self.current_song_id'], {}), '(db_session, self.current_song_id)\n', (6845, 6879), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((7230, 7262), 'pajbot.managers.db.DBManager.create_session_scope', 'DBManager.create_session_scope', ([], {}), '()\n', (7260, 7262), False, 'from pajbot.managers.db import DBManager\n'), ((7305, 7354), 'pajbot.models.user.User.find_by_user_input', 'User.find_by_user_input', (['db_session', 'requested_by'], {}), '(db_session, requested_by)\n', (7328, 7354), False, 'from pajbot.models.user import User\n'), ((8266, 8298), 'pajbot.managers.db.DBManager.create_session_scope', 'DBManager.create_session_scope', ([], {}), '()\n', (8296, 8298), False, 'from pajbot.managers.db import DBManager\n'), ((8333, 8383), 'pajbot.models.songrequest.SongrequestQueue._from_id', 'SongrequestQueue._from_id', (['db_session', 'database_id'], {}), '(db_session, database_id)\n', (8358, 8383), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((9722, 9735), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (9732, 9735), False, 'import time\n'), ((10749, 10781), 'pajbot.managers.db.DBManager.create_session_scope', 'DBManager.create_session_scope', ([], {}), '()\n', (10779, 10781), False, 'from pajbot.managers.db import DBManager\n'), ((10824, 10870), 'pajbot.models.songrequest.SongrequestQueue._get_current_song', 'SongrequestQueue._get_current_song', (['db_session'], {}), '(db_session)\n', (10858, 10870), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((14402, 14434), 'pajbot.managers.db.DBManager.create_session_scope', 'DBManager.create_session_scope', ([], {}), '()\n', (14432, 14434), False, 'from pajbot.managers.db import DBManager\n'), ((14473, 14519), 'pajbot.models.songrequest.SongrequestQueue._get_playlist', 'SongrequestQueue._get_playlist', (['db_session', '(15)'], {}), '(db_session, 15)\n', (14503, 14519), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((14659, 14691), 'pajbot.managers.db.DBManager.create_session_scope', 'DBManager.create_session_scope', ([], {}), '()\n', (14689, 14691), False, 'from pajbot.managers.db import DBManager\n'), ((4009, 4041), 'pajbot.managers.db.DBManager.create_session_scope', 'DBManager.create_session_scope', ([], {}), '()\n', (4039, 4041), False, 'from pajbot.managers.db import DBManager\n'), ((4088, 4147), 'pajbot.models.songrequest.SongrequestQueue._from_id', 'SongrequestQueue._from_id', (['db_session', 'self.current_song_id'], {}), '(db_session, self.current_song_id)\n', (4113, 4147), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((9886, 9918), 'pajbot.managers.db.DBManager.create_session_scope', 'DBManager.create_session_scope', ([], {}), '()\n', (9916, 9918), False, 'from pajbot.managers.db import DBManager\n'), ((9965, 10024), 'pajbot.models.songrequest.SongrequestQueue._from_id', 'SongrequestQueue._from_id', (['db_session', 'self.current_song_id'], {}), '(db_session, self.current_song_id)\n', (9990, 10024), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((10935, 10978), 'pajbot.models.songrequest.SongrequestQueue._get_next_song', 'SongrequestQueue._get_next_song', (['db_session'], {}), '(db_session)\n', (10966, 10978), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((12265, 12297), 'pajbot.models.songrequest.SongrequestQueue._update_queue', 'SongrequestQueue._update_queue', ([], {}), '()\n', (12295, 12297), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((7475, 7527), 'pajbot.models.songrequest.SongrequestHistory._from_id', 'SongrequestHistory._from_id', (['db_session', 'database_id'], {}), '(db_session, database_id)\n', (7502, 7527), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((14803, 14850), 'pajbot.models.songrequest.SongrequestHistory._get_history', 'SongrequestHistory._get_history', (['db_session', '(15)'], {}), '(db_session, 15)\n', (14834, 14850), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((12112, 12156), 'pajbot.models.songrequest.SongrequestQueue._get_next_queue', 'SongrequestQueue._get_next_queue', (['db_session'], {}), '(db_session)\n', (12144, 12156), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((8774, 8806), 'pajbot.managers.db.DBManager.create_session_scope', 'DBManager.create_session_scope', ([], {}), '()\n', (8804, 8806), False, 'from pajbot.managers.db import DBManager\n'), ((8865, 8924), 'pajbot.models.songrequest.SongrequestQueue._from_id', 'SongrequestQueue._from_id', (['db_session', 'self.current_song_id'], {}), '(db_session, self.current_song_id)\n', (8890, 8924), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n'), ((8965, 9008), 'pajbot.models.songrequest.SongrequestQueue._get_next_song', 'SongrequestQueue._get_next_song', (['db_session'], {}), '(db_session)\n', (8996, 9008), False, 'from pajbot.models.songrequest import SongrequestQueue, SongrequestHistory, SongRequestSongInfo\n')]
import numpy as np def mean_or_nan(xs): """Return its mean a non-empty sequence, numpy.nan for a empty one.""" return np.mean(xs) if xs else np.nan
[ "numpy.mean" ]
[((128, 139), 'numpy.mean', 'np.mean', (['xs'], {}), '(xs)\n', (135, 139), True, 'import numpy as np\n')]
import time import unittest import unittest.mock from smac.configspace import ConfigurationSpace from smac.runhistory.runhistory import RunInfo, RunValue from smac.scenario.scenario import Scenario from smac.stats.stats import Stats from smac.tae import StatusType from smac.tae.execute_func import ExecuteTAFuncDict from smac.tae.serial_runner import SerialRunner def target(x, seed, instance): return x ** 2, {'key': seed, 'instance': instance} def target_delayed(x, seed, instance): time.sleep(1) return x ** 2, {'key': seed, 'instance': instance} class TestSerialRunner(unittest.TestCase): def setUp(self): self.cs = ConfigurationSpace() self.scenario = Scenario({'cs': self.cs, 'run_obj': 'quality', 'output_dir': ''}) self.stats = Stats(scenario=self.scenario) def test_run(self): """Makes sure that we are able to run a configuration and return the expected values/types""" # We use the funcdict as a mechanism to test SerialRunner runner = ExecuteTAFuncDict(ta=target, stats=self.stats, run_obj='quality') self.assertIsInstance(runner, SerialRunner) run_info = RunInfo(config=2, instance='test', instance_specific="0", seed=0, cutoff=None, capped=False, budget=0.0) # submit runs! then get the value runner.submit_run(run_info) run_values = runner.get_finished_runs() self.assertEqual(len(run_values), 1) self.assertIsInstance(run_values, list) self.assertIsInstance(run_values[0][0], RunInfo) self.assertIsInstance(run_values[0][1], RunValue) self.assertEqual(run_values[0][1].cost, 4) self.assertEqual(run_values[0][1].status, StatusType.SUCCESS) def test_serial_runs(self): # We use the funcdict as a mechanism to test SerialRunner runner = ExecuteTAFuncDict(ta=target_delayed, stats=self.stats, run_obj='quality') self.assertIsInstance(runner, SerialRunner) run_info = RunInfo(config=2, instance='test', instance_specific="0", seed=0, cutoff=None, capped=False, budget=0.0) runner.submit_run(run_info) run_info = RunInfo(config=3, instance='test', instance_specific="0", seed=0, cutoff=None, capped=False, budget=0.0) runner.submit_run(run_info) run_values = runner.get_finished_runs() self.assertEqual(len(run_values), 2) # To make sure runs launched serially, we just make sure that the end time of # a run is later than the other # Results are returned in left to right self.assertLessEqual(int(run_values[1][1].endtime), int(run_values[0][1].starttime)) # No wait time in serial runs! start = time.time() runner.wait() # The run takes a second, so 0.5 is sufficient self.assertLess(time.time() - start, 0.5) pass if __name__ == "__main__": unittest.main()
[ "smac.stats.stats.Stats", "smac.configspace.ConfigurationSpace", "smac.runhistory.runhistory.RunInfo", "smac.tae.execute_func.ExecuteTAFuncDict", "time.sleep", "smac.scenario.scenario.Scenario", "unittest.main", "time.time" ]
[((499, 512), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (509, 512), False, 'import time\n'), ((3049, 3064), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3062, 3064), False, 'import unittest\n'), ((653, 673), 'smac.configspace.ConfigurationSpace', 'ConfigurationSpace', ([], {}), '()\n', (671, 673), False, 'from smac.configspace import ConfigurationSpace\n'), ((698, 763), 'smac.scenario.scenario.Scenario', 'Scenario', (["{'cs': self.cs, 'run_obj': 'quality', 'output_dir': ''}"], {}), "({'cs': self.cs, 'run_obj': 'quality', 'output_dir': ''})\n", (706, 763), False, 'from smac.scenario.scenario import Scenario\n'), ((853, 882), 'smac.stats.stats.Stats', 'Stats', ([], {'scenario': 'self.scenario'}), '(scenario=self.scenario)\n', (858, 882), False, 'from smac.stats.stats import Stats\n'), ((1102, 1167), 'smac.tae.execute_func.ExecuteTAFuncDict', 'ExecuteTAFuncDict', ([], {'ta': 'target', 'stats': 'self.stats', 'run_obj': '"""quality"""'}), "(ta=target, stats=self.stats, run_obj='quality')\n", (1119, 1167), False, 'from smac.tae.execute_func import ExecuteTAFuncDict\n'), ((1240, 1349), 'smac.runhistory.runhistory.RunInfo', 'RunInfo', ([], {'config': '(2)', 'instance': '"""test"""', 'instance_specific': '"""0"""', 'seed': '(0)', 'cutoff': 'None', 'capped': '(False)', 'budget': '(0.0)'}), "(config=2, instance='test', instance_specific='0', seed=0, cutoff=\n None, capped=False, budget=0.0)\n", (1247, 1349), False, 'from smac.runhistory.runhistory import RunInfo, RunValue\n'), ((1945, 2018), 'smac.tae.execute_func.ExecuteTAFuncDict', 'ExecuteTAFuncDict', ([], {'ta': 'target_delayed', 'stats': 'self.stats', 'run_obj': '"""quality"""'}), "(ta=target_delayed, stats=self.stats, run_obj='quality')\n", (1962, 2018), False, 'from smac.tae.execute_func import ExecuteTAFuncDict\n'), ((2091, 2200), 'smac.runhistory.runhistory.RunInfo', 'RunInfo', ([], {'config': '(2)', 'instance': '"""test"""', 'instance_specific': '"""0"""', 'seed': '(0)', 'cutoff': 'None', 'capped': '(False)', 'budget': '(0.0)'}), "(config=2, instance='test', instance_specific='0', seed=0, cutoff=\n None, capped=False, budget=0.0)\n", (2098, 2200), False, 'from smac.runhistory.runhistory import RunInfo, RunValue\n'), ((2278, 2387), 'smac.runhistory.runhistory.RunInfo', 'RunInfo', ([], {'config': '(3)', 'instance': '"""test"""', 'instance_specific': '"""0"""', 'seed': '(0)', 'cutoff': 'None', 'capped': '(False)', 'budget': '(0.0)'}), "(config=3, instance='test', instance_specific='0', seed=0, cutoff=\n None, capped=False, budget=0.0)\n", (2285, 2387), False, 'from smac.runhistory.runhistory import RunInfo, RunValue\n'), ((2863, 2874), 'time.time', 'time.time', ([], {}), '()\n', (2872, 2874), False, 'import time\n'), ((2977, 2988), 'time.time', 'time.time', ([], {}), '()\n', (2986, 2988), False, 'import time\n')]
"""Tests rest of functions in manubot.cite, not covered by test_citekey_api.py.""" import pytest from manubot.cite.citekey import ( citekey_pattern, shorten_citekey, infer_citekey_prefix, inspect_citekey, ) @pytest.mark.parametrize("citation_string", [ ('@doi:10.5061/dryad.q447c/1'), ('@arxiv:1407.3561v1'), ('@doi:10.1007/978-94-015-6859-3_4'), ('@tag:tag_with_underscores'), ('@tag:tag-with-hyphens'), ('@url:https://greenelab.github.io/manubot-rootstock/'), ('@tag:abc123'), ('@tag:123abc'), ]) def test_citekey_pattern_match(citation_string): match = citekey_pattern.fullmatch(citation_string) assert match @pytest.mark.parametrize("citation_string", [ ('doi:10.5061/dryad.q447c/1'), ('@tag:abc123-'), ('@tag:abc123_'), ('@-tag:abc123'), ('@_tag:abc123'), ]) def test_citekey_pattern_no_match(citation_string): match = citekey_pattern.fullmatch(citation_string) assert match is None @pytest.mark.parametrize("standard_citekey,expected", [ ('doi:10.5061/dryad.q447c/1', 'kQFQ8EaO'), ('arxiv:1407.3561v1', '16kozZ9Ys'), ('pmid:24159271', '11sli93ov'), ('url:http://blog.dhimmel.com/irreproducible-timestamps/', 'QBWMEuxW'), ]) def test_shorten_citekey(standard_citekey, expected): short_citekey = shorten_citekey(standard_citekey) assert short_citekey == expected @pytest.mark.parametrize('citekey', [ 'doi:10.7717/peerj.705', 'doi:10/b6vnmd', 'pmcid:PMC4304851', 'pmid:25648772', 'arxiv:1407.3561', 'isbn:978-1-339-91988-1', 'isbn:1-339-91988-5', 'wikidata:Q1', 'wikidata:Q50051684', 'url:https://peerj.com/articles/705/', ]) def test_inspect_citekey_passes(citekey): """ These citekeys should pass inspection by inspect_citekey. """ assert inspect_citekey(citekey) is None @pytest.mark.parametrize(['citekey', 'contains'], [ ('doi:10.771/peerj.705', 'Double check the DOI'), ('doi:10/b6v_nmd', 'Double check the shortDOI'), ('doi:7717/peerj.705', "must start with '10.'"), ('doi:b6vnmd', "must start with '10.'"), ('pmcid:25648772', "must start with 'PMC'"), ('pmid:PMC4304851', "Should 'pmid:PMC4304851' switch the citation source to 'pmcid'?"), ('isbn:1-339-91988-X', 'identifier violates the ISBN syntax'), ('wikidata:P212', "item IDs must start with 'Q'"), ('wikidata:QABCD', 'does not conform to the Wikidata regex'), ]) def test_inspect_citekey_fails(citekey, contains): """ These citekeys should fail inspection by inspect_citekey. """ report = inspect_citekey(citekey) assert report is not None assert isinstance(report, str) assert contains in report @pytest.mark.parametrize(['citation', 'expect'], [ ('doi:not-a-real-doi', 'doi:not-a-real-doi'), ('DOI:not-a-real-doi', 'doi:not-a-real-doi'), ('uRl:mixed-case-prefix', 'url:mixed-case-prefix'), ('raw:raw-citation', 'raw:raw-citation'), ('no-prefix', 'raw:no-prefix'), ('no-prefix:but-colon', 'raw:no-prefix:but-colon'), ]) def test_infer_citekey_prefix(citation, expect): assert infer_citekey_prefix(citation) == expect
[ "manubot.cite.citekey.infer_citekey_prefix", "manubot.cite.citekey.citekey_pattern.fullmatch", "pytest.mark.parametrize", "manubot.cite.citekey.inspect_citekey", "manubot.cite.citekey.shorten_citekey" ]
[((228, 515), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""citation_string"""', "['@doi:10.5061/dryad.q447c/1', '@arxiv:1407.3561v1',\n '@doi:10.1007/978-94-015-6859-3_4', '@tag:tag_with_underscores',\n '@tag:tag-with-hyphens',\n '@url:https://greenelab.github.io/manubot-rootstock/', '@tag:abc123',\n '@tag:123abc']"], {}), "('citation_string', ['@doi:10.5061/dryad.q447c/1',\n '@arxiv:1407.3561v1', '@doi:10.1007/978-94-015-6859-3_4',\n '@tag:tag_with_underscores', '@tag:tag-with-hyphens',\n '@url:https://greenelab.github.io/manubot-rootstock/', '@tag:abc123',\n '@tag:123abc'])\n", (251, 515), False, 'import pytest\n'), ((675, 816), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""citation_string"""', "['doi:10.5061/dryad.q447c/1', '@tag:abc123-', '@tag:abc123_',\n '@-tag:abc123', '@_tag:abc123']"], {}), "('citation_string', ['doi:10.5061/dryad.q447c/1',\n '@tag:abc123-', '@tag:abc123_', '@-tag:abc123', '@_tag:abc123'])\n", (698, 816), False, 'import pytest\n'), ((981, 1232), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""standard_citekey,expected"""', "[('doi:10.5061/dryad.q447c/1', 'kQFQ8EaO'), ('arxiv:1407.3561v1',\n '16kozZ9Ys'), ('pmid:24159271', '11sli93ov'), (\n 'url:http://blog.dhimmel.com/irreproducible-timestamps/', 'QBWMEuxW')]"], {}), "('standard_citekey,expected', [(\n 'doi:10.5061/dryad.q447c/1', 'kQFQ8EaO'), ('arxiv:1407.3561v1',\n '16kozZ9Ys'), ('pmid:24159271', '11sli93ov'), (\n 'url:http://blog.dhimmel.com/irreproducible-timestamps/', 'QBWMEuxW')])\n", (1004, 1232), False, 'import pytest\n'), ((1386, 1656), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""citekey"""', "['doi:10.7717/peerj.705', 'doi:10/b6vnmd', 'pmcid:PMC4304851',\n 'pmid:25648772', 'arxiv:1407.3561', 'isbn:978-1-339-91988-1',\n 'isbn:1-339-91988-5', 'wikidata:Q1', 'wikidata:Q50051684',\n 'url:https://peerj.com/articles/705/']"], {}), "('citekey', ['doi:10.7717/peerj.705',\n 'doi:10/b6vnmd', 'pmcid:PMC4304851', 'pmid:25648772', 'arxiv:1407.3561',\n 'isbn:978-1-339-91988-1', 'isbn:1-339-91988-5', 'wikidata:Q1',\n 'wikidata:Q50051684', 'url:https://peerj.com/articles/705/'])\n", (1409, 1656), False, 'import pytest\n'), ((1855, 2438), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["['citekey', 'contains']", '[(\'doi:10.771/peerj.705\', \'Double check the DOI\'), (\'doi:10/b6v_nmd\',\n \'Double check the shortDOI\'), (\'doi:7717/peerj.705\',\n "must start with \'10.\'"), (\'doi:b6vnmd\', "must start with \'10.\'"), (\n \'pmcid:25648772\', "must start with \'PMC\'"), (\'pmid:PMC4304851\',\n "Should \'pmid:PMC4304851\' switch the citation source to \'pmcid\'?"), (\n \'isbn:1-339-91988-X\', \'identifier violates the ISBN syntax\'), (\n \'wikidata:P212\', "item IDs must start with \'Q\'"), (\'wikidata:QABCD\',\n \'does not conform to the Wikidata regex\')]'], {}), '([\'citekey\', \'contains\'], [(\'doi:10.771/peerj.705\',\n \'Double check the DOI\'), (\'doi:10/b6v_nmd\', \'Double check the shortDOI\'\n ), (\'doi:7717/peerj.705\', "must start with \'10.\'"), (\'doi:b6vnmd\',\n "must start with \'10.\'"), (\'pmcid:25648772\', "must start with \'PMC\'"),\n (\'pmid:PMC4304851\',\n "Should \'pmid:PMC4304851\' switch the citation source to \'pmcid\'?"), (\n \'isbn:1-339-91988-X\', \'identifier violates the ISBN syntax\'), (\n \'wikidata:P212\', "item IDs must start with \'Q\'"), (\'wikidata:QABCD\',\n \'does not conform to the Wikidata regex\')])\n', (1878, 2438), False, 'import pytest\n'), ((2708, 3045), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["['citation', 'expect']", "[('doi:not-a-real-doi', 'doi:not-a-real-doi'), ('DOI:not-a-real-doi',\n 'doi:not-a-real-doi'), ('uRl:mixed-case-prefix',\n 'url:mixed-case-prefix'), ('raw:raw-citation', 'raw:raw-citation'), (\n 'no-prefix', 'raw:no-prefix'), ('no-prefix:but-colon',\n 'raw:no-prefix:but-colon')]"], {}), "(['citation', 'expect'], [('doi:not-a-real-doi',\n 'doi:not-a-real-doi'), ('DOI:not-a-real-doi', 'doi:not-a-real-doi'), (\n 'uRl:mixed-case-prefix', 'url:mixed-case-prefix'), ('raw:raw-citation',\n 'raw:raw-citation'), ('no-prefix', 'raw:no-prefix'), (\n 'no-prefix:but-colon', 'raw:no-prefix:but-colon')])\n", (2731, 3045), False, 'import pytest\n'), ((612, 654), 'manubot.cite.citekey.citekey_pattern.fullmatch', 'citekey_pattern.fullmatch', (['citation_string'], {}), '(citation_string)\n', (637, 654), False, 'from manubot.cite.citekey import citekey_pattern, shorten_citekey, infer_citekey_prefix, inspect_citekey\n'), ((910, 952), 'manubot.cite.citekey.citekey_pattern.fullmatch', 'citekey_pattern.fullmatch', (['citation_string'], {}), '(citation_string)\n', (935, 952), False, 'from manubot.cite.citekey import citekey_pattern, shorten_citekey, infer_citekey_prefix, inspect_citekey\n'), ((1312, 1345), 'manubot.cite.citekey.shorten_citekey', 'shorten_citekey', (['standard_citekey'], {}), '(standard_citekey)\n', (1327, 1345), False, 'from manubot.cite.citekey import citekey_pattern, shorten_citekey, infer_citekey_prefix, inspect_citekey\n'), ((2585, 2609), 'manubot.cite.citekey.inspect_citekey', 'inspect_citekey', (['citekey'], {}), '(citekey)\n', (2600, 2609), False, 'from manubot.cite.citekey import citekey_pattern, shorten_citekey, infer_citekey_prefix, inspect_citekey\n'), ((1819, 1843), 'manubot.cite.citekey.inspect_citekey', 'inspect_citekey', (['citekey'], {}), '(citekey)\n', (1834, 1843), False, 'from manubot.cite.citekey import citekey_pattern, shorten_citekey, infer_citekey_prefix, inspect_citekey\n'), ((3115, 3145), 'manubot.cite.citekey.infer_citekey_prefix', 'infer_citekey_prefix', (['citation'], {}), '(citation)\n', (3135, 3145), False, 'from manubot.cite.citekey import citekey_pattern, shorten_citekey, infer_citekey_prefix, inspect_citekey\n')]
import pytest from playwright.sync_api import Page from pages.main_page.main_page import MainPage from test.test_base import * import logging import re logger = logging.getLogger("test") @pytest.mark.only_browser("chromium") def test_find_element_list(page: Page): main_page = MainPage(base_url, page) main_page.delete_cookies() main_page.open() # Wait articles and page to be loaded main_page.loader().should_be_visible() main_page.loader().should_be_hidden() assert main_page.register_button().is_visible() pattern = re.compile(".*") # Check articles assert main_page.articles().size() == 10 assert main_page.articles().get(1).is_visible() assert pattern.match(main_page.articles().get(1).title().inner_text()) assert pattern.match(main_page.articles().get(1).body().inner_text()) logger.info(main_page.articles().get(2).title().inner_text()) # Check nav panel assert main_page.nav_bar().is_visible() assert main_page.nav_bar().login_button().is_visible() logger.info(main_page.nav_bar().login_button().inner_text()) logger.info(main_page.nav_bar().register_button().inner_text()) # articles = page.querySelectorAll(".article-preview") # assert len(articles) == 10 # texts = page.evalOnSelectorAll(".article-preview h1", ''' # (elems, min) => { # return elems.map(function(el) { # return el.textContent //.toUpperCase() # }); //.join(", "); # }''') # assert len(texts) == 10 # assert not texts == [] # assert articles[0].querySelector("h1").innerText() == "Python Playwright Demo" # assert articles[0].querySelector("p").innerText() == "Playwright Demo"
[ "logging.getLogger", "pytest.mark.only_browser", "pages.main_page.main_page.MainPage", "re.compile" ]
[((162, 187), 'logging.getLogger', 'logging.getLogger', (['"""test"""'], {}), "('test')\n", (179, 187), False, 'import logging\n'), ((191, 227), 'pytest.mark.only_browser', 'pytest.mark.only_browser', (['"""chromium"""'], {}), "('chromium')\n", (215, 227), False, 'import pytest\n'), ((284, 308), 'pages.main_page.main_page.MainPage', 'MainPage', (['base_url', 'page'], {}), '(base_url, page)\n', (292, 308), False, 'from pages.main_page.main_page import MainPage\n'), ((554, 570), 're.compile', 're.compile', (['""".*"""'], {}), "('.*')\n", (564, 570), False, 'import re\n')]
### based on https://github.com/kylemcdonald/Parametric-t-SNE/blob/master/Parametric%20t-SNE%20(Keras).ipynb import numpy as np from tensorflow.keras import backend as K from tensorflow.keras.losses import categorical_crossentropy from tqdm.autonotebook import tqdm import tensorflow as tf def Hbeta(D, beta): """Computes the Gaussian kernel values given a vector of squared Euclidean distances, and the precision of the Gaussian kernel. The function also computes the perplexity (P) of the distribution.""" P = np.exp(-D * beta) sumP = np.sum(P) H = np.log(sumP) + beta * np.sum(np.multiply(D, P)) / sumP P = P / sumP return H, P def x2p(X, u=15, tol=1e-4, print_iter=500, max_tries=50, verbose=0): """ % X2P Identifies appropriate sigma's to get kk NNs up to some tolerance % % [P, beta] = x2p(xx, kk, tol) % % Identifies the required precision (= 1 / variance^2) to obtain a Gaussian % kernel with a certain uncertainty for every datapoint. The desired % uncertainty can be specified through the perplexity u (default = 15). The % desired perplexity is obtained up to some tolerance that can be specified % by tol (default = 1e-4). % The function returns the final Gaussian kernel in P, as well as the % employed precisions per instance in beta. % """ # Initialize some variables n = X.shape[0] # number of instances P = np.zeros((n, n)) # empty probability matrix beta = np.ones(n) # empty precision vector logU = np.log(u) # log of perplexity (= entropy) # Compute pairwise distances if verbose > 0: print("Computing pairwise distances...") sum_X = np.sum(np.square(X), axis=1) # note: translating sum_X' from matlab to numpy means using reshape to add a dimension D = sum_X + sum_X[:, None] + -2 * X.dot(X.T) # Run over all datapoints if verbose > 0: print("Computing P-values...") for i in range(n): if verbose > 1 and print_iter and i % print_iter == 0: print("Computed P-values {} of {} datapoints...".format(i, n)) # Set minimum and maximum values for precision betamin = float("-inf") betamax = float("+inf") # Compute the Gaussian kernel and entropy for the current precision indices = np.concatenate((np.arange(0, i), np.arange(i + 1, n))) Di = D[i, indices] H, thisP = Hbeta(Di, beta[i]) # Evaluate whether the perplexity is within tolerance Hdiff = H - logU tries = 0 while abs(Hdiff) > tol and tries < max_tries: # If not, increase or decrease precision if Hdiff > 0: betamin = beta[i] if np.isinf(betamax): beta[i] *= 2 else: beta[i] = (beta[i] + betamax) / 2 else: betamax = beta[i] if np.isinf(betamin): beta[i] /= 2 else: beta[i] = (beta[i] + betamin) / 2 # Recompute the values H, thisP = Hbeta(Di, beta[i]) Hdiff = H - logU tries += 1 # Set the final row of P P[i, indices] = thisP if verbose > 0: print("Mean value of sigma: {}".format(np.mean(np.sqrt(1 / beta)))) print("Minimum value of sigma: {}".format(np.min(np.sqrt(1 / beta)))) print("Maximum value of sigma: {}".format(np.max(np.sqrt(1 / beta)))) return P, beta def compute_joint_probabilities( samples, batch_size=5000, d=2, perplexity=30, tol=1e-5, verbose=0 ): """ This function computes the probababilities in X, split up into batches % Gaussians employed in the high-dimensional space have the specified % perplexity (default = 30). The number of degrees of freedom of the % Student-t distribution may be specified through v (default = d - 1). """ v = d - 1 # Initialize some variables n = samples.shape[0] batch_size = min(batch_size, n) # Precompute joint probabilities for all batches if verbose > 0: print("Precomputing P-values...") batch_count = int(n / batch_size) P = np.zeros((batch_count, batch_size, batch_size)) # for each batch of data for i, start in enumerate(tqdm(range(0, n - batch_size + 1, batch_size))): # select batch curX = samples[start : start + batch_size] # compute affinities using fixed perplexity P[i], _ = x2p(curX, perplexity, tol, verbose=verbose) # make sure we don't have NaN's P[i][np.isnan(P[i])] = 0 # make symmetric P[i] = P[i] + P[i].T # / 2 # obtain estimation of joint probabilities P[i] = P[i] / P[i].sum() P[i] = np.maximum(P[i], np.finfo(P[i].dtype).eps) return P def z2p(z, d, n, eps=10e-15): """ Computes the low dimensional probability """ v = d - 1 sum_act = tf.math.reduce_sum(tf.math.square(z), axis=1) Q = K.reshape(sum_act, [-1, 1]) + -2 * tf.keras.backend.dot(z, tf.transpose(z)) Q = (sum_act + Q) / v Q = tf.math.pow(1 + Q, -(v + 1) / 2) Q *= 1 - np.eye(n) Q /= tf.math.reduce_sum(Q) Q = tf.math.maximum(Q, eps) return Q def tsne_loss(d, batch_size, eps=10e-15): # v = d - 1.0 def loss(P, Z): """ KL divergence P is the joint probabilities for this batch (Keras loss functions call this y_true) Z is the low-dimensional output (Keras loss functions call this y_pred) """ Q = z2p(Z, d, n=batch_size, eps=eps) return tf.math.reduce_sum(P * tf.math.log((P + eps) / (Q + eps))) return loss
[ "tensorflow.math.pow", "numpy.sqrt", "tensorflow.transpose", "tensorflow.math.log", "numpy.log", "numpy.arange", "numpy.multiply", "numpy.exp", "numpy.isinf", "numpy.eye", "numpy.ones", "tensorflow.keras.backend.reshape", "numpy.square", "tensorflow.math.maximum", "numpy.isnan", "numpy...
[((532, 549), 'numpy.exp', 'np.exp', (['(-D * beta)'], {}), '(-D * beta)\n', (538, 549), True, 'import numpy as np\n'), ((561, 570), 'numpy.sum', 'np.sum', (['P'], {}), '(P)\n', (567, 570), True, 'import numpy as np\n'), ((1437, 1453), 'numpy.zeros', 'np.zeros', (['(n, n)'], {}), '((n, n))\n', (1445, 1453), True, 'import numpy as np\n'), ((1493, 1503), 'numpy.ones', 'np.ones', (['n'], {}), '(n)\n', (1500, 1503), True, 'import numpy as np\n'), ((1541, 1550), 'numpy.log', 'np.log', (['u'], {}), '(u)\n', (1547, 1550), True, 'import numpy as np\n'), ((4228, 4275), 'numpy.zeros', 'np.zeros', (['(batch_count, batch_size, batch_size)'], {}), '((batch_count, batch_size, batch_size))\n', (4236, 4275), True, 'import numpy as np\n'), ((5143, 5175), 'tensorflow.math.pow', 'tf.math.pow', (['(1 + Q)', '(-(v + 1) / 2)'], {}), '(1 + Q, -(v + 1) / 2)\n', (5154, 5175), True, 'import tensorflow as tf\n'), ((5208, 5229), 'tensorflow.math.reduce_sum', 'tf.math.reduce_sum', (['Q'], {}), '(Q)\n', (5226, 5229), True, 'import tensorflow as tf\n'), ((5238, 5261), 'tensorflow.math.maximum', 'tf.math.maximum', (['Q', 'eps'], {}), '(Q, eps)\n', (5253, 5261), True, 'import tensorflow as tf\n'), ((579, 591), 'numpy.log', 'np.log', (['sumP'], {}), '(sumP)\n', (585, 591), True, 'import numpy as np\n'), ((1706, 1718), 'numpy.square', 'np.square', (['X'], {}), '(X)\n', (1715, 1718), True, 'import numpy as np\n'), ((4998, 5015), 'tensorflow.math.square', 'tf.math.square', (['z'], {}), '(z)\n', (5012, 5015), True, 'import tensorflow as tf\n'), ((5033, 5060), 'tensorflow.keras.backend.reshape', 'K.reshape', (['sum_act', '[-1, 1]'], {}), '(sum_act, [-1, 1])\n', (5042, 5060), True, 'from tensorflow.keras import backend as K\n'), ((5189, 5198), 'numpy.eye', 'np.eye', (['n'], {}), '(n)\n', (5195, 5198), True, 'import numpy as np\n'), ((4625, 4639), 'numpy.isnan', 'np.isnan', (['P[i]'], {}), '(P[i])\n', (4633, 4639), True, 'import numpy as np\n'), ((2350, 2365), 'numpy.arange', 'np.arange', (['(0)', 'i'], {}), '(0, i)\n', (2359, 2365), True, 'import numpy as np\n'), ((2367, 2386), 'numpy.arange', 'np.arange', (['(i + 1)', 'n'], {}), '(i + 1, n)\n', (2376, 2386), True, 'import numpy as np\n'), ((2747, 2764), 'numpy.isinf', 'np.isinf', (['betamax'], {}), '(betamax)\n', (2755, 2764), True, 'import numpy as np\n'), ((2946, 2963), 'numpy.isinf', 'np.isinf', (['betamin'], {}), '(betamin)\n', (2954, 2963), True, 'import numpy as np\n'), ((4822, 4842), 'numpy.finfo', 'np.finfo', (['P[i].dtype'], {}), '(P[i].dtype)\n', (4830, 4842), True, 'import numpy as np\n'), ((5092, 5107), 'tensorflow.transpose', 'tf.transpose', (['z'], {}), '(z)\n', (5104, 5107), True, 'import tensorflow as tf\n'), ((5650, 5684), 'tensorflow.math.log', 'tf.math.log', (['((P + eps) / (Q + eps))'], {}), '((P + eps) / (Q + eps))\n', (5661, 5684), True, 'import tensorflow as tf\n'), ((608, 625), 'numpy.multiply', 'np.multiply', (['D', 'P'], {}), '(D, P)\n', (619, 625), True, 'import numpy as np\n'), ((3344, 3361), 'numpy.sqrt', 'np.sqrt', (['(1 / beta)'], {}), '(1 / beta)\n', (3351, 3361), True, 'import numpy as np\n'), ((3422, 3439), 'numpy.sqrt', 'np.sqrt', (['(1 / beta)'], {}), '(1 / beta)\n', (3429, 3439), True, 'import numpy as np\n'), ((3500, 3517), 'numpy.sqrt', 'np.sqrt', (['(1 / beta)'], {}), '(1 / beta)\n', (3507, 3517), True, 'import numpy as np\n')]
import random import string def test_append(lst): ret_val = [] for w in lst: ret_val.append(w.lower( )) return ret_val def test_map(lst): ret_val = map(str.lower, lst) return ret_val def run_tests(n): for i in range(n): tst = ''.join(random.choices(string.ascii_uppercase + string.digits, k=1000)) lst_tst = list(tst) test_append(lst_tst) test_map(lst_tst) def main( ): run_tests(100000) if __name__ == "__main__": main( )
[ "random.choices" ]
[((277, 339), 'random.choices', 'random.choices', (['(string.ascii_uppercase + string.digits)'], {'k': '(1000)'}), '(string.ascii_uppercase + string.digits, k=1000)\n', (291, 339), False, 'import random\n')]
# -*- coding: utf-8 -*- """ Created on Wed Mar 26 20:17:06 2014 @author: stuart """ import os import tempfile import datetime import astropy.table import astropy.time import astropy.units as u import pytest from sunpy.time import parse_time from sunpy.net.jsoc import JSOCClient, JSOCResponse from sunpy.net.vso.vso import Results import sunpy.net.jsoc.attrs as attrs client = JSOCClient() def test_jsocresponse_double(): j1 = JSOCResponse(table=astropy.table.Table(data=[[1,2,3,4]])) j1.append(astropy.table.Table(data=[[1,2,3,4]])) assert isinstance(j1, JSOCResponse) assert all(j1.table == astropy.table.vstack([astropy.table.Table(data=[[1,2,3,4]]), astropy.table.Table(data=[[1,2,3,4]])])) def test_jsocresponse_single(): j1 = JSOCResponse(table=None) assert len(j1) == 0 j1.append(astropy.table.Table(data=[[1,2,3,4]])) assert all(j1.table == astropy.table.Table(data=[[1,2,3,4]])) assert len(j1) == 4 def test_payload(): start = parse_time('2012/1/1T00:00:00') end = parse_time('2012/1/1T00:00:45') payload = client._make_query_payload(start, end, 'hmi.M_42s', notify='@') payload_expected = { 'ds': '{0}[{1}-{2}]'.format('hmi.M_42s', start.strftime("%Y.%m.%d_%H:%M:%S_TAI"), end.strftime("%Y.%m.%d_%H:%M:%S_TAI")), 'format': 'json', 'method': 'url', 'notify': '@', 'op': 'exp_request', 'process': 'n=0|no_op', 'protocol': 'FITS,compress Rice', 'requestor': 'none', 'filenamefmt': '{0}.{{T_REC:A}}.{{CAMERA}}.{{segment}}'.format('hmi.M_42s') } assert payload == payload_expected def test_payload_nocompression(): start = parse_time('2012/1/1T00:00:00') end = parse_time('2012/1/1T00:00:45') payload = client._make_query_payload(start, end, 'hmi.M_42s', compression=None, notify='<EMAIL>') payload_expected = { 'ds':'{0}[{1}-{2}]'.format('hmi.M_42s', start.strftime("%Y.%m.%d_%H:%M:%S_TAI"), end.strftime("%Y.%m.%d_%H:%M:%S_TAI")), 'format':'json', 'method':'url', 'notify':'<EMAIL>', 'op':'exp_request', 'process':'n=0|no_op', 'protocol':'FITS, **NONE**', 'requestor':'none', 'filenamefmt':'{0}.{{T_REC:A}}.{{CAMERA}}.{{segment}}'.format('hmi.M_42s') } assert payload == payload_expected def test_payload_protocol(): start = parse_time('2012/1/1T00:00:00') end = parse_time('2012/1/1T00:00:45') payload = client._make_query_payload(start, end, 'hmi.M_42s', protocol='as-is', notify='<EMAIL>') payload_expected = { 'ds':'{0}[{1}-{2}]'.format('hmi.M_42s', start.strftime("%Y.%m.%d_%H:%M:%S_TAI"), end.strftime("%Y.%m.%d_%H:%M:%S_TAI")), 'format':'json', 'method':'url', 'notify':'<EMAIL>', 'op':'exp_request', 'process':'n=0|no_op', 'protocol':'as-is', 'requestor':'none', 'filenamefmt':'{0}.{{T_REC:A}}.{{CAMERA}}.{{segment}}'.format('hmi.M_42s') } assert payload == payload_expected def test_process_time_string(): start = client._process_time('2012/1/1T00:00:00') assert start == datetime.datetime(year=2012, month=1, day=1, second=34) def test_process_time_datetime(): start = client._process_time(datetime.datetime(year=2012, month=1, day=1)) assert start == datetime.datetime(year=2012, month=1, day=1, second=34) def test_process_time_astropy(): start = client._process_time(astropy.time.Time('2012-01-01T00:00:00', format='isot', scale='utc')) assert start == datetime.datetime(year=2012, month=1, day=1, second=34) def test_process_time_astropy_tai(): start = client._process_time(astropy.time.Time('2012-01-01T00:00:00', format='isot', scale='tai')) assert start == datetime.datetime(year=2012, month=1, day=1, second=0) @pytest.mark.online def test_status_request(): r = client._request_status('none') assert r.json() == {u'error': u'requestid none is not an acceptable ID for the external export system (acceptable format is JSOC_YYYYMMDD_NNN_X_IN or JSOC_YYYYMMDD_NNN).', u'status': 4} def test_empty_jsoc_response(): Jresp = JSOCResponse() assert Jresp.table is None assert Jresp.query_args is None assert Jresp.requestIDs is None assert str(Jresp) == 'None' assert repr(Jresp) == 'None' assert len(Jresp) == 0 @pytest.mark.online def test_query(): Jresp = client.query(attrs.Time('2012/1/1T00:00:00', '2012/1/1T00:01:30'), attrs.Series('hmi.M_45s'),attrs.Sample(90*u.second)) assert isinstance(Jresp, JSOCResponse) assert len(Jresp) == 2 @pytest.mark.online def test_post_pass(): responses = client.query(attrs.Time('2012/1/1T00:00:00', '2012/1/1T00:00:45'), attrs.Series('hmi.M_45s'), attrs.Notify('<EMAIL>')) aa = client.request_data(responses, return_resp=True) tmpresp = aa[0].json() assert tmpresp['status'] == 2 assert tmpresp['protocol'] == 'FITS,compress Rice' assert tmpresp['method'] == 'url' @pytest.mark.online def test_post_wavelength(): responses = client.query(attrs.Time('2010/07/30T13:30:00','2010/07/30T14:00:00'),attrs.Series('aia.lev1_euv_12s'), attrs.Wavelength(193*u.AA)|attrs.Wavelength(335*u.AA), attrs.Notify('<EMAIL>')) aa = client.request_data(responses, return_resp=True) tmpresp = aa[0].json() assert tmpresp['status'] == 2 assert tmpresp['protocol'] == 'FITS,compress Rice' assert tmpresp['method'] == 'url' assert tmpresp['rcount'] == 302 @pytest.mark.online() def test_post_wave_series(): with pytest.raises(TypeError): client.query(attrs.Time('2012/1/1T00:00:00', '2012/1/1T00:00:45'), attrs.Series('hmi.M_45s')|attrs.Series('aia.lev1_euv_12s'), attrs.Wavelength(193*u.AA)|attrs.Wavelength(335*u.AA)) @pytest.mark.online def test_post_fail(recwarn): res = client.query(attrs.Time('2012/1/1T00:00:00', '2012/1/1T00:00:45'), attrs.Series('none'), attrs.Notify('<EMAIL>')) client.request_data(res, return_resp=True) w = recwarn.pop(Warning) assert issubclass(w.category, Warning) assert "Query 0 returned status 4 with error Series none is not a valid series accessible from hmidb2." == str(w.message) assert w.filename assert w.lineno @pytest.mark.online def test_request_status_fail(): resp = client._request_status('none') assert resp.json() == {u'status': 4, u'error': u"requestid none is not an acceptable ID for the external export system (acceptable format is JSOC_YYYYMMDD_NNN_X_IN or JSOC_YYYYMMDD_NNN)."} resp = client._request_status(['none']) assert resp.json() == {u'status': 4, u'error': u"requestid none is not an acceptable ID for the external export system (acceptable format is JSOC_YYYYMMDD_NNN_X_IN or JSOC_YYYYMMDD_NNN)."} @pytest.mark.online #@<EMAIL>.xfail def test_wait_get(): responses = client.query(attrs.Time('2012/1/1T1:00:36', '2012/1/1T01:00:38'), attrs.Series( 'hmi.M_45s'), attrs.Notify('<EMAIL>')) path = tempfile.mkdtemp() res = client.get(responses, path=path) assert isinstance(res, Results) assert res.total == 1 @pytest.mark.online def test_get_request(): responses = client.query(attrs.Time('2012/1/1T1:00:36', '2012/1/1T01:00:38'), attrs.Series('hmi.M_45s'), attrs.Notify('<EMAIL>')) bb = client.request_data(responses) path = tempfile.mkdtemp() aa = client.get_request(bb, path=path) assert isinstance(aa, Results) @pytest.mark.online def test_results_filenames(): responses = client.query(attrs.Time('2014/1/1T1:00:36', '2014/1/1T01:01:38'), attrs.Series('hmi.M_45s'), attrs.Notify('<EMAIL>')) path = tempfile.mkdtemp() aa = client.get(responses, path=path) assert isinstance(aa, Results) files = aa.wait() assert len(files) == len(responses) for hmiurl in aa.map_: assert os.path.basename(hmiurl) == os.path.basename(aa.map_[hmiurl]['path']) @pytest.mark.online def test_invalid_query(): with pytest.raises(ValueError): resp = client.query(attrs.Time('2012/1/1T01:00:00', '2012/1/1T01:00:45'))
[ "datetime.datetime", "sunpy.net.jsoc.attrs.Series", "sunpy.net.jsoc.attrs.Notify", "pytest.mark.online", "sunpy.net.jsoc.attrs.Sample", "tempfile.mkdtemp", "pytest.raises", "os.path.basename", "sunpy.time.parse_time", "sunpy.net.jsoc.attrs.Wavelength", "sunpy.net.jsoc.JSOCClient", "sunpy.net.j...
[((380, 392), 'sunpy.net.jsoc.JSOCClient', 'JSOCClient', ([], {}), '()\n', (390, 392), False, 'from sunpy.net.jsoc import JSOCClient, JSOCResponse\n'), ((5848, 5868), 'pytest.mark.online', 'pytest.mark.online', ([], {}), '()\n', (5866, 5868), False, 'import pytest\n'), ((807, 831), 'sunpy.net.jsoc.JSOCResponse', 'JSOCResponse', ([], {'table': 'None'}), '(table=None)\n', (819, 831), False, 'from sunpy.net.jsoc import JSOCClient, JSOCResponse\n'), ((1033, 1064), 'sunpy.time.parse_time', 'parse_time', (['"""2012/1/1T00:00:00"""'], {}), "('2012/1/1T00:00:00')\n", (1043, 1064), False, 'from sunpy.time import parse_time\n'), ((1075, 1106), 'sunpy.time.parse_time', 'parse_time', (['"""2012/1/1T00:00:45"""'], {}), "('2012/1/1T00:00:45')\n", (1085, 1106), False, 'from sunpy.time import parse_time\n'), ((1789, 1820), 'sunpy.time.parse_time', 'parse_time', (['"""2012/1/1T00:00:00"""'], {}), "('2012/1/1T00:00:00')\n", (1799, 1820), False, 'from sunpy.time import parse_time\n'), ((1831, 1862), 'sunpy.time.parse_time', 'parse_time', (['"""2012/1/1T00:00:45"""'], {}), "('2012/1/1T00:00:45')\n", (1841, 1862), False, 'from sunpy.time import parse_time\n'), ((2567, 2598), 'sunpy.time.parse_time', 'parse_time', (['"""2012/1/1T00:00:00"""'], {}), "('2012/1/1T00:00:00')\n", (2577, 2598), False, 'from sunpy.time import parse_time\n'), ((2609, 2640), 'sunpy.time.parse_time', 'parse_time', (['"""2012/1/1T00:00:45"""'], {}), "('2012/1/1T00:00:45')\n", (2619, 2640), False, 'from sunpy.time import parse_time\n'), ((4424, 4438), 'sunpy.net.jsoc.JSOCResponse', 'JSOCResponse', ([], {}), '()\n', (4436, 4438), False, 'from sunpy.net.jsoc import JSOCClient, JSOCResponse\n'), ((7409, 7427), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (7425, 7427), False, 'import tempfile\n'), ((7794, 7812), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (7810, 7812), False, 'import tempfile\n'), ((8116, 8134), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (8132, 8134), False, 'import tempfile\n'), ((3401, 3456), 'datetime.datetime', 'datetime.datetime', ([], {'year': '(2012)', 'month': '(1)', 'day': '(1)', 'second': '(34)'}), '(year=2012, month=1, day=1, second=34)\n', (3418, 3456), False, 'import datetime\n'), ((3525, 3569), 'datetime.datetime', 'datetime.datetime', ([], {'year': '(2012)', 'month': '(1)', 'day': '(1)'}), '(year=2012, month=1, day=1)\n', (3542, 3569), False, 'import datetime\n'), ((3591, 3646), 'datetime.datetime', 'datetime.datetime', ([], {'year': '(2012)', 'month': '(1)', 'day': '(1)', 'second': '(34)'}), '(year=2012, month=1, day=1, second=34)\n', (3608, 3646), False, 'import datetime\n'), ((3804, 3859), 'datetime.datetime', 'datetime.datetime', ([], {'year': '(2012)', 'month': '(1)', 'day': '(1)', 'second': '(34)'}), '(year=2012, month=1, day=1, second=34)\n', (3821, 3859), False, 'import datetime\n'), ((4021, 4075), 'datetime.datetime', 'datetime.datetime', ([], {'year': '(2012)', 'month': '(1)', 'day': '(1)', 'second': '(0)'}), '(year=2012, month=1, day=1, second=0)\n', (4038, 4075), False, 'import datetime\n'), ((4698, 4750), 'sunpy.net.jsoc.attrs.Time', 'attrs.Time', (['"""2012/1/1T00:00:00"""', '"""2012/1/1T00:01:30"""'], {}), "('2012/1/1T00:00:00', '2012/1/1T00:01:30')\n", (4708, 4750), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((4777, 4802), 'sunpy.net.jsoc.attrs.Series', 'attrs.Series', (['"""hmi.M_45s"""'], {}), "('hmi.M_45s')\n", (4789, 4802), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((4803, 4830), 'sunpy.net.jsoc.attrs.Sample', 'attrs.Sample', (['(90 * u.second)'], {}), '(90 * u.second)\n', (4815, 4830), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((4973, 5025), 'sunpy.net.jsoc.attrs.Time', 'attrs.Time', (['"""2012/1/1T00:00:00"""', '"""2012/1/1T00:00:45"""'], {}), "('2012/1/1T00:00:00', '2012/1/1T00:00:45')\n", (4983, 5025), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((5056, 5081), 'sunpy.net.jsoc.attrs.Series', 'attrs.Series', (['"""hmi.M_45s"""'], {}), "('hmi.M_45s')\n", (5068, 5081), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((5083, 5106), 'sunpy.net.jsoc.attrs.Notify', 'attrs.Notify', (['"""<EMAIL>"""'], {}), "('<EMAIL>')\n", (5095, 5106), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((5399, 5455), 'sunpy.net.jsoc.attrs.Time', 'attrs.Time', (['"""2010/07/30T13:30:00"""', '"""2010/07/30T14:00:00"""'], {}), "('2010/07/30T13:30:00', '2010/07/30T14:00:00')\n", (5409, 5455), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((5455, 5487), 'sunpy.net.jsoc.attrs.Series', 'attrs.Series', (['"""aia.lev1_euv_12s"""'], {}), "('aia.lev1_euv_12s')\n", (5467, 5487), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((5573, 5596), 'sunpy.net.jsoc.attrs.Notify', 'attrs.Notify', (['"""<EMAIL>"""'], {}), "('<EMAIL>')\n", (5585, 5596), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((5907, 5931), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (5920, 5931), False, 'import pytest\n'), ((6239, 6291), 'sunpy.net.jsoc.attrs.Time', 'attrs.Time', (['"""2012/1/1T00:00:00"""', '"""2012/1/1T00:00:45"""'], {}), "('2012/1/1T00:00:00', '2012/1/1T00:00:45')\n", (6249, 6291), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((6316, 6336), 'sunpy.net.jsoc.attrs.Series', 'attrs.Series', (['"""none"""'], {}), "('none')\n", (6328, 6336), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((6338, 6361), 'sunpy.net.jsoc.attrs.Notify', 'attrs.Notify', (['"""<EMAIL>"""'], {}), "('<EMAIL>')\n", (6350, 6361), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((7263, 7314), 'sunpy.net.jsoc.attrs.Time', 'attrs.Time', (['"""2012/1/1T1:00:36"""', '"""2012/1/1T01:00:38"""'], {}), "('2012/1/1T1:00:36', '2012/1/1T01:00:38')\n", (7273, 7314), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((7345, 7370), 'sunpy.net.jsoc.attrs.Series', 'attrs.Series', (['"""hmi.M_45s"""'], {}), "('hmi.M_45s')\n", (7357, 7370), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((7373, 7396), 'sunpy.net.jsoc.attrs.Notify', 'attrs.Notify', (['"""<EMAIL>"""'], {}), "('<EMAIL>')\n", (7385, 7396), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((7608, 7659), 'sunpy.net.jsoc.attrs.Time', 'attrs.Time', (['"""2012/1/1T1:00:36"""', '"""2012/1/1T01:00:38"""'], {}), "('2012/1/1T1:00:36', '2012/1/1T01:00:38')\n", (7618, 7659), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((7690, 7715), 'sunpy.net.jsoc.attrs.Series', 'attrs.Series', (['"""hmi.M_45s"""'], {}), "('hmi.M_45s')\n", (7702, 7715), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((7717, 7740), 'sunpy.net.jsoc.attrs.Notify', 'attrs.Notify', (['"""<EMAIL>"""'], {}), "('<EMAIL>')\n", (7729, 7740), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((7971, 8022), 'sunpy.net.jsoc.attrs.Time', 'attrs.Time', (['"""2014/1/1T1:00:36"""', '"""2014/1/1T01:01:38"""'], {}), "('2014/1/1T1:00:36', '2014/1/1T01:01:38')\n", (7981, 8022), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((8053, 8078), 'sunpy.net.jsoc.attrs.Series', 'attrs.Series', (['"""hmi.M_45s"""'], {}), "('hmi.M_45s')\n", (8065, 8078), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((8080, 8103), 'sunpy.net.jsoc.attrs.Notify', 'attrs.Notify', (['"""<EMAIL>"""'], {}), "('<EMAIL>')\n", (8092, 8103), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((8442, 8467), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (8455, 8467), False, 'import pytest\n'), ((5518, 5546), 'sunpy.net.jsoc.attrs.Wavelength', 'attrs.Wavelength', (['(193 * u.AA)'], {}), '(193 * u.AA)\n', (5534, 5546), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((5545, 5573), 'sunpy.net.jsoc.attrs.Wavelength', 'attrs.Wavelength', (['(335 * u.AA)'], {}), '(335 * u.AA)\n', (5561, 5573), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((5954, 6006), 'sunpy.net.jsoc.attrs.Time', 'attrs.Time', (['"""2012/1/1T00:00:00"""', '"""2012/1/1T00:00:45"""'], {}), "('2012/1/1T00:00:00', '2012/1/1T00:00:45')\n", (5964, 6006), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((8316, 8340), 'os.path.basename', 'os.path.basename', (['hmiurl'], {}), '(hmiurl)\n', (8332, 8340), False, 'import os\n'), ((8344, 8385), 'os.path.basename', 'os.path.basename', (["aa.map_[hmiurl]['path']"], {}), "(aa.map_[hmiurl]['path'])\n", (8360, 8385), False, 'import os\n'), ((8497, 8549), 'sunpy.net.jsoc.attrs.Time', 'attrs.Time', (['"""2012/1/1T01:00:00"""', '"""2012/1/1T01:00:45"""'], {}), "('2012/1/1T01:00:00', '2012/1/1T01:00:45')\n", (8507, 8549), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((6029, 6054), 'sunpy.net.jsoc.attrs.Series', 'attrs.Series', (['"""hmi.M_45s"""'], {}), "('hmi.M_45s')\n", (6041, 6054), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((6055, 6087), 'sunpy.net.jsoc.attrs.Series', 'attrs.Series', (['"""aia.lev1_euv_12s"""'], {}), "('aia.lev1_euv_12s')\n", (6067, 6087), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((6110, 6138), 'sunpy.net.jsoc.attrs.Wavelength', 'attrs.Wavelength', (['(193 * u.AA)'], {}), '(193 * u.AA)\n', (6126, 6138), True, 'import sunpy.net.jsoc.attrs as attrs\n'), ((6137, 6165), 'sunpy.net.jsoc.attrs.Wavelength', 'attrs.Wavelength', (['(335 * u.AA)'], {}), '(335 * u.AA)\n', (6153, 6165), True, 'import sunpy.net.jsoc.attrs as attrs\n')]
#!/usr/bin/python # -*- coding: utf-8 -*- """Compare to numpy data""" import sys import numpy as np import multipletau from test_correlate import get_sample_arrays_cplx def test_corresponds_ac(): myframe = sys._getframe() myname = myframe.f_code.co_name print("running ", myname) a = np.concatenate(get_sample_arrays_cplx()).real m = 16 restau = multipletau.autocorrelate(a=1*a, m=m, copy=True, normalize=True, dtype=np.float_) reslin = multipletau.correlate_numpy(a=1*a, v=1*a, copy=True, normalize=True, dtype=np.float_) idx = np.array(restau[:, 0].real, dtype=int)[:m] assert np.allclose(reslin[idx, 1], restau[:m, 1]) def test_corresponds_ac_first_loop(): """ numpy correlation: G_m = sum_i(a_i*a_{i+m}) multipletau correlation 2nd order: b_j = (a_{2i} + a_{2i+1} / 2) G_m = sum_j(b_j*b_{j+1}) = 1/4*sum_i(a_{2i} * a_{2i+m} + a_{2i} * a_{2i+m+1} + a_{2i+1} * a_{2i+m} + a_{2i+1} * a_{2i+m+1} ) The values after the first m+1 lag times in the multipletau correlation differ from the normal correlation, because the traces are averaged over two consecutive items, effectively halving the size of the trace. The multiple-tau correlation can be compared to the regular correlation by using an even sized sequence (here 222) in which the elements 2i and 2i+1 are equal, as is done in this test. """ myframe = sys._getframe() myname = myframe.f_code.co_name print("running ", myname) a = [arr / np.average(arr) for arr in get_sample_arrays_cplx()] a = np.concatenate(a)[:222] # two consecutive elements are the same, so the multiple-tau method # corresponds to the numpy correlation for the first loop. a[::2] = a[1::2] for m in [2, 4, 6, 8, 10, 12, 14, 16]: restau = multipletau.correlate(a=a, v=a.imag+1j*a.real, m=m, copy=True, normalize=False, dtype=np.complex_) reslin = multipletau.correlate_numpy(a=a, v=a.imag+1j*a.real, copy=True, normalize=False, dtype=np.complex_) idtau = np.where(restau[:, 0] == m+2)[0][0] tau3 = restau[idtau, 1] # m+1 initial bins idref = np.where(reslin[:, 0] == m+2)[0][0] tau3ref = reslin[idref, 1] assert np.allclose(tau3, tau3ref) def test_corresponds_ac_nonormalize(): myframe = sys._getframe() myname = myframe.f_code.co_name print("running ", myname) a = np.concatenate(get_sample_arrays_cplx()).real m = 16 restau = multipletau.autocorrelate(a=1*a, m=m, copy=True, normalize=False, dtype=np.float_) reslin = multipletau.correlate_numpy(a=1*a, v=1*a, copy=True, normalize=False, dtype=np.float_) idx = np.array(restau[:, 0].real, dtype=int)[:m+1] assert np.allclose(reslin[idx, 1], restau[:m+1, 1]) def test_corresponds_cc(): myframe = sys._getframe() myname = myframe.f_code.co_name print("running ", myname) a = np.concatenate(get_sample_arrays_cplx()) m = 16 restau = multipletau.correlate(a=a, v=a.imag+1j*a.real, m=m, copy=True, normalize=True, dtype=np.complex_) reslin = multipletau.correlate_numpy(a=a, v=a.imag+1j*a.real, copy=True, normalize=True, dtype=np.complex_) idx = np.array(restau[:, 0].real, dtype=int)[:m+1] assert np.allclose(reslin[idx, 1], restau[:m+1, 1]) def test_corresponds_cc_nonormalize(): myframe = sys._getframe() myname = myframe.f_code.co_name print("running ", myname) a = np.concatenate(get_sample_arrays_cplx()) m = 16 restau = multipletau.correlate(a=a, v=a.imag+1j*a.real, m=m, copy=True, normalize=False, dtype=np.complex_) reslin = multipletau.correlate_numpy(a=a, v=a.imag+1j*a.real, copy=True, normalize=False, dtype=np.complex_) idx = np.array(restau[:, 0].real, dtype=int)[:m+1] assert np.allclose(reslin[idx, 1], restau[:m+1, 1]) if __name__ == "__main__": # Run all tests loc = locals() for key in list(loc.keys()): if key.startswith("test_") and hasattr(loc[key], "__call__"): loc[key]()
[ "multipletau.correlate_numpy", "numpy.allclose", "numpy.average", "numpy.where", "sys._getframe", "numpy.array", "multipletau.correlate", "numpy.concatenate", "test_correlate.get_sample_arrays_cplx", "multipletau.autocorrelate" ]
[((215, 230), 'sys._getframe', 'sys._getframe', ([], {}), '()\n', (228, 230), False, 'import sys\n'), ((377, 465), 'multipletau.autocorrelate', 'multipletau.autocorrelate', ([], {'a': '(1 * a)', 'm': 'm', 'copy': '(True)', 'normalize': '(True)', 'dtype': 'np.float_'}), '(a=1 * a, m=m, copy=True, normalize=True, dtype=np\n .float_)\n', (402, 465), False, 'import multipletau\n'), ((629, 722), 'multipletau.correlate_numpy', 'multipletau.correlate_numpy', ([], {'a': '(1 * a)', 'v': '(1 * a)', 'copy': '(True)', 'normalize': '(True)', 'dtype': 'np.float_'}), '(a=1 * a, v=1 * a, copy=True, normalize=True,\n dtype=np.float_)\n', (656, 722), False, 'import multipletau\n'), ((945, 987), 'numpy.allclose', 'np.allclose', (['reslin[idx, 1]', 'restau[:m, 1]'], {}), '(reslin[idx, 1], restau[:m, 1])\n', (956, 987), True, 'import numpy as np\n'), ((1834, 1849), 'sys._getframe', 'sys._getframe', ([], {}), '()\n', (1847, 1849), False, 'import sys\n'), ((3117, 3132), 'sys._getframe', 'sys._getframe', ([], {}), '()\n', (3130, 3132), False, 'import sys\n'), ((3279, 3368), 'multipletau.autocorrelate', 'multipletau.autocorrelate', ([], {'a': '(1 * a)', 'm': 'm', 'copy': '(True)', 'normalize': '(False)', 'dtype': 'np.float_'}), '(a=1 * a, m=m, copy=True, normalize=False, dtype=\n np.float_)\n', (3304, 3368), False, 'import multipletau\n'), ((3532, 3626), 'multipletau.correlate_numpy', 'multipletau.correlate_numpy', ([], {'a': '(1 * a)', 'v': '(1 * a)', 'copy': '(True)', 'normalize': '(False)', 'dtype': 'np.float_'}), '(a=1 * a, v=1 * a, copy=True, normalize=False,\n dtype=np.float_)\n', (3559, 3626), False, 'import multipletau\n'), ((3851, 3897), 'numpy.allclose', 'np.allclose', (['reslin[idx, 1]', 'restau[:m + 1, 1]'], {}), '(reslin[idx, 1], restau[:m + 1, 1])\n', (3862, 3897), True, 'import numpy as np\n'), ((3939, 3954), 'sys._getframe', 'sys._getframe', ([], {}), '()\n', (3952, 3954), False, 'import sys\n'), ((4096, 4203), 'multipletau.correlate', 'multipletau.correlate', ([], {'a': 'a', 'v': '(a.imag + 1.0j * a.real)', 'm': 'm', 'copy': '(True)', 'normalize': '(True)', 'dtype': 'np.complex_'}), '(a=a, v=a.imag + 1.0j * a.real, m=m, copy=True,\n normalize=True, dtype=np.complex_)\n', (4117, 4203), False, 'import multipletau\n'), ((4383, 4491), 'multipletau.correlate_numpy', 'multipletau.correlate_numpy', ([], {'a': 'a', 'v': '(a.imag + 1.0j * a.real)', 'copy': '(True)', 'normalize': '(True)', 'dtype': 'np.complex_'}), '(a=a, v=a.imag + 1.0j * a.real, copy=True,\n normalize=True, dtype=np.complex_)\n', (4410, 4491), False, 'import multipletau\n'), ((4714, 4760), 'numpy.allclose', 'np.allclose', (['reslin[idx, 1]', 'restau[:m + 1, 1]'], {}), '(reslin[idx, 1], restau[:m + 1, 1])\n', (4725, 4760), True, 'import numpy as np\n'), ((4814, 4829), 'sys._getframe', 'sys._getframe', ([], {}), '()\n', (4827, 4829), False, 'import sys\n'), ((4971, 5079), 'multipletau.correlate', 'multipletau.correlate', ([], {'a': 'a', 'v': '(a.imag + 1.0j * a.real)', 'm': 'm', 'copy': '(True)', 'normalize': '(False)', 'dtype': 'np.complex_'}), '(a=a, v=a.imag + 1.0j * a.real, m=m, copy=True,\n normalize=False, dtype=np.complex_)\n', (4992, 5079), False, 'import multipletau\n'), ((5259, 5368), 'multipletau.correlate_numpy', 'multipletau.correlate_numpy', ([], {'a': 'a', 'v': '(a.imag + 1.0j * a.real)', 'copy': '(True)', 'normalize': '(False)', 'dtype': 'np.complex_'}), '(a=a, v=a.imag + 1.0j * a.real, copy=True,\n normalize=False, dtype=np.complex_)\n', (5286, 5368), False, 'import multipletau\n'), ((5591, 5637), 'numpy.allclose', 'np.allclose', (['reslin[idx, 1]', 'restau[:m + 1, 1]'], {}), '(reslin[idx, 1], restau[:m + 1, 1])\n', (5602, 5637), True, 'import numpy as np\n'), ((890, 928), 'numpy.array', 'np.array', (['restau[:, 0].real'], {'dtype': 'int'}), '(restau[:, 0].real, dtype=int)\n', (898, 928), True, 'import numpy as np\n'), ((1993, 2010), 'numpy.concatenate', 'np.concatenate', (['a'], {}), '(a)\n', (2007, 2010), True, 'import numpy as np\n'), ((2234, 2342), 'multipletau.correlate', 'multipletau.correlate', ([], {'a': 'a', 'v': '(a.imag + 1.0j * a.real)', 'm': 'm', 'copy': '(True)', 'normalize': '(False)', 'dtype': 'np.complex_'}), '(a=a, v=a.imag + 1.0j * a.real, m=m, copy=True,\n normalize=False, dtype=np.complex_)\n', (2255, 2342), False, 'import multipletau\n'), ((2546, 2655), 'multipletau.correlate_numpy', 'multipletau.correlate_numpy', ([], {'a': 'a', 'v': '(a.imag + 1.0j * a.real)', 'copy': '(True)', 'normalize': '(False)', 'dtype': 'np.complex_'}), '(a=a, v=a.imag + 1.0j * a.real, copy=True,\n normalize=False, dtype=np.complex_)\n', (2573, 2655), False, 'import multipletau\n'), ((3035, 3061), 'numpy.allclose', 'np.allclose', (['tau3', 'tau3ref'], {}), '(tau3, tau3ref)\n', (3046, 3061), True, 'import numpy as np\n'), ((3794, 3832), 'numpy.array', 'np.array', (['restau[:, 0].real'], {'dtype': 'int'}), '(restau[:, 0].real, dtype=int)\n', (3802, 3832), True, 'import numpy as np\n'), ((4045, 4069), 'test_correlate.get_sample_arrays_cplx', 'get_sample_arrays_cplx', ([], {}), '()\n', (4067, 4069), False, 'from test_correlate import get_sample_arrays_cplx\n'), ((4657, 4695), 'numpy.array', 'np.array', (['restau[:, 0].real'], {'dtype': 'int'}), '(restau[:, 0].real, dtype=int)\n', (4665, 4695), True, 'import numpy as np\n'), ((4920, 4944), 'test_correlate.get_sample_arrays_cplx', 'get_sample_arrays_cplx', ([], {}), '()\n', (4942, 4944), False, 'from test_correlate import get_sample_arrays_cplx\n'), ((5534, 5572), 'numpy.array', 'np.array', (['restau[:, 0].real'], {'dtype': 'int'}), '(restau[:, 0].real, dtype=int)\n', (5542, 5572), True, 'import numpy as np\n'), ((321, 345), 'test_correlate.get_sample_arrays_cplx', 'get_sample_arrays_cplx', ([], {}), '()\n', (343, 345), False, 'from test_correlate import get_sample_arrays_cplx\n'), ((1932, 1947), 'numpy.average', 'np.average', (['arr'], {}), '(arr)\n', (1942, 1947), True, 'import numpy as np\n'), ((1959, 1983), 'test_correlate.get_sample_arrays_cplx', 'get_sample_arrays_cplx', ([], {}), '()\n', (1981, 1983), False, 'from test_correlate import get_sample_arrays_cplx\n'), ((3223, 3247), 'test_correlate.get_sample_arrays_cplx', 'get_sample_arrays_cplx', ([], {}), '()\n', (3245, 3247), False, 'from test_correlate import get_sample_arrays_cplx\n'), ((2843, 2874), 'numpy.where', 'np.where', (['(restau[:, 0] == m + 2)'], {}), '(restau[:, 0] == m + 2)\n', (2851, 2874), True, 'import numpy as np\n'), ((2948, 2979), 'numpy.where', 'np.where', (['(reslin[:, 0] == m + 2)'], {}), '(reslin[:, 0] == m + 2)\n', (2956, 2979), True, 'import numpy as np\n')]
# Copyright 2020 The FedLearner Authors. 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 argparse import logging from trainer_master import TrainerMaster from data.data_block_queue import DataBlockQueue from data.data_source_reader import DataSourceReader class LeaderTrainerMaster(TrainerMaster): def __init__(self, application_id, data_source_reader_): super(LeaderTrainerMaster, self).__init__(application_id) self._data_block_queue = DataBlockQueue() self._data_source_reader = data_source_reader_ def _load_data(self): checkpoint = self._get_checkpoint() for data_block in self._data_source_reader.list_data_block(): if data_block.block_id not in checkpoint: self._data_block_queue.put(data_block) def _alloc_data_block(self, block_id=None): # block_id is unused in leader role data_blocks_resp = None if not self._data_block_queue.empty(): data_blocks_resp = self._data_block_queue.get() return data_blocks_resp if __name__ == '__main__': logging.getLogger().setLevel(logging.DEBUG) parser = argparse.ArgumentParser('leader trainer master cmd.') parser.add_argument('-p', '--port', type=int, default=50001, help='Listen port of leader trainer master') parser.add_argument('-app_id', '--application_id', required=True, help='application_id') parser.add_argument('-data_path', '--data_path', required=True, help='training example data path') parser.add_argument('-start_date', '--start_date', default=None, help='training data start date') parser.add_argument('-end_date', '--end_date', default=None, help='training data end date') FLAGS = parser.parse_args() data_source_reader = DataSourceReader( FLAGS.data_path, FLAGS.start_date, FLAGS.end_date) leader_tm = LeaderTrainerMaster(FLAGS.application_id, data_source_reader) leader_tm.run(listen_port=FLAGS.port)
[ "logging.getLogger", "data.data_block_queue.DataBlockQueue", "argparse.ArgumentParser", "data.data_source_reader.DataSourceReader" ]
[((1680, 1733), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""leader trainer master cmd."""'], {}), "('leader trainer master cmd.')\n", (1703, 1733), False, 'import argparse\n'), ((2416, 2483), 'data.data_source_reader.DataSourceReader', 'DataSourceReader', (['FLAGS.data_path', 'FLAGS.start_date', 'FLAGS.end_date'], {}), '(FLAGS.data_path, FLAGS.start_date, FLAGS.end_date)\n', (2432, 2483), False, 'from data.data_source_reader import DataSourceReader\n'), ((1004, 1020), 'data.data_block_queue.DataBlockQueue', 'DataBlockQueue', ([], {}), '()\n', (1018, 1020), False, 'from data.data_block_queue import DataBlockQueue\n'), ((1623, 1642), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (1640, 1642), False, 'import logging\n')]
from pathlib import Path from typing import Optional import numpy as np import pandas as pd from nilearn.datasets.utils import _fetch_files from scipy import sparse class StudyID(str): pass class TfIDf(float): pass NS_DATA_URL = "https://github.com/neurosynth/neurosynth-data/raw/master/" def fetch_study_metadata( data_dir: Path, version: int = 7, verbose: int = 1 ) -> pd.DataFrame: """ Download if needed the `metadata.tsv.gz` file from Neurosynth and load it into a pandas DataFrame. The metadata table contains the metadata for each study. Each study (ID) is stored on its own line. These IDs are in the same order as the id column of the associated `coordinates.tsv.gz` file, but the rows will differ because the coordinates file will contain multiple rows per study. They are also in the same order as the rows in the `features.npz` files for the same version. The metadata will therefore have N rows, N being the number of studies in the Neurosynth dataset. The columns (for version 7) are: - id - doi - space - title - authors - year - journal Parameters ---------- data_dir : Path the path for the directory where downloaded data should be saved. version : int, optional the neurosynth data version, by default 7 verbose : int, optional verbose param for nilearn's `_fetch_files`, by default 1 Returns ------- pd.DataFrame the study metadata dataframe """ metadata_filename = f"data-neurosynth_version-{version}_metadata.tsv.gz" metadata_file = _fetch_files( data_dir, [ ( metadata_filename, NS_DATA_URL + metadata_filename, {}, ), ], verbose=verbose, )[0] metadata = pd.read_table(metadata_file) return metadata def fetch_feature_data( data_dir: Path, version: int = 7, verbose: int = 1, convert_study_ids: bool = False, ) -> pd.DataFrame: """ Download if needed the `tfidf_features.npz` file from Neurosynth and load it into a pandas Dataframe. The `tfidf_features` contains feature values for different types of "vocabularies". The features dataframe is stored as a compressed, sparse matrix. Once loaded and reconstructed into a dense matrix, it contains one row per study and one column per label. The associated labels are loaded, as well as the study ids, to reconstruct a dataframe of size N x P, where N is the number of studies in the Neurosynth dataset, and P is the number of words in the vocabulary. Parameters ---------- data_dir : Path the path for the directory where downloaded data should be saved. version : int, optional the neurosynth data version, by default 7 verbose : int, optional verbose param for nilearn's `_fetch_files`, by default 1 convert_study_ids : bool, optional if True, cast study ids as `StudyID`, by default False Returns ------- pd.DataFrame the features dataframe """ file_names = [ f"data-neurosynth_version-{version}_vocab-terms_source-abstract_type-tfidf_features.npz", f"data-neurosynth_version-{version}_vocab-terms_vocabulary.txt", ] files = _fetch_files( data_dir, [ ( fn, NS_DATA_URL + fn, {}, ) for fn in file_names ], verbose=verbose, ) feature_data_sparse = sparse.load_npz(files[0]) feature_data = feature_data_sparse.todense() metadata_df = fetch_study_metadata(data_dir, version, verbose) ids = metadata_df["id"] if convert_study_ids: ids = ids.apply(StudyID) feature_names = np.genfromtxt( files[1], dtype=str, delimiter="\t", ).tolist() feature_df = pd.DataFrame( index=ids.tolist(), columns=feature_names, data=feature_data ) return feature_df def fetch_neurosynth_peak_data( data_dir: Path, version: int = 7, verbose: int = 1, convert_study_ids: bool = False, ) -> pd.DataFrame: """ Download if needed the `coordinates.tsv.gz` file from Neurosynth and load it into a pandas DataFrame. The `coordinates.tsv.gz` contains the coordinates for the peaks reported by studies in the Neurosynth dataset. It contains one row per coordinate reported. The metadata for each study is also loaded to include the space in which the coordinates are reported. The peak_data dataframe therefore has PR rows, PR being the number of reported peaks in the Neurosynth dataset. The columns (for version 7) are: - id - table_id - table_num - peak_id - space - x - y - z Parameters ---------- data_dir : Path the path for the directory where downloaded data should be saved. version : int, optional the neurosynth data version, by default 7 verbose : int, optional verbose param for nilearn's `_fetch_files`, by default 1 convert_study_ids : bool, optional if True, cast study ids as `StudyID`, by default False Returns ------- pd.DataFrame the peak dataframe """ coordinates_filename = ( f"data-neurosynth_version-{version}_coordinates.tsv.gz" ) coordinates_file = _fetch_files( data_dir, [ ( coordinates_filename, NS_DATA_URL + coordinates_filename, {}, ), ], verbose=verbose, )[0] activations = pd.read_table(coordinates_file) metadata = fetch_study_metadata(data_dir, version, verbose) activations = activations.join( metadata[["id", "space"]].set_index("id"), on="id" ) if convert_study_ids: activations["id"] = activations["id"].apply(StudyID) return activations def get_ns_term_study_associations( data_dir: Path, version: int = 7, verbose: int = 1, convert_study_ids: bool = False, tfidf_threshold: Optional[float] = None, ) -> pd.DataFrame: """ Load a dataframe containing associations between term and studies. The dataframe contains one row for each term and study pair from the features table in the Neurosynth dataset. With each (term, study) pair comes the tfidf value for the term in the study. If a tfidf threshold value is passed, only (term, study) associations with a tfidf value > tfidf_threshold will be kept. Parameters ---------- data_dir : Path the path for the directory where downloaded data should be saved. version : int, optional the neurosynth data version, by default 7 verbose : int, optional verbose param for nilearn's `_fetch_files`, by default 1 convert_study_ids : bool, optional if True, cast study ids as `StudyID`, by default False tfidf_threshold : Optional[float], optional the minimum tfidf value for the (term, study) associations, by default None Returns ------- pd.DataFrame the term association dataframe """ features = fetch_feature_data( data_dir, version, verbose, convert_study_ids ) features.index.name = "id" term_data = pd.melt( features.reset_index(), var_name="term", id_vars="id", value_name="tfidf", ) if tfidf_threshold is not None: term_data = term_data.query(f"tfidf > {tfidf_threshold}") else: term_data = term_data.query("tfidf > 0") return term_data def get_ns_mni_peaks_reported( data_dir: Path, version: int = 7, verbose: int = 1, convert_study_ids: bool = False, ) -> pd.DataFrame: """ Load a dataframe containing the coordinates for the peaks reported by studies in the Neurosynth dataset. Coordinates for the peaks are in MNI space, with coordinates that are reported in Talaraich space converted. The resulting dataframe contains one row for each peak reported. Each row has 4 columns: - id - x - y - z Parameters ---------- data_dir : Path the path for the directory where downloaded data should be saved. version : int, optional the neurosynth data version, by default 7 verbose : int, optional verbose param for nilearn's `_fetch_files`, by default 1 convert_study_ids : bool, optional if True, cast study ids as `StudyID`, by default False Returns ------- pd.DataFrame the peak dataframe """ activations = fetch_neurosynth_peak_data( data_dir, version, verbose, convert_study_ids ) mni_peaks = activations.loc[activations.space == "MNI"][ ["x", "y", "z", "id"] ] non_mni_peaks = activations.loc[activations.space == "TAL"][ ["x", "y", "z", "id"] ] proj_mat = np.linalg.pinv( np.array( [ [0.9254, 0.0024, -0.0118, -1.0207], [-0.0048, 0.9316, -0.0871, -1.7667], [0.0152, 0.0883, 0.8924, 4.0926], [0.0, 0.0, 0.0, 1.0], ] ).T ) projected = np.round( np.dot( np.hstack( ( non_mni_peaks[["x", "y", "z"]].values, np.ones((len(non_mni_peaks), 1)), ) ), proj_mat, )[:, 0:3] ) projected_df = pd.DataFrame( np.hstack([projected, non_mni_peaks[["id"]].values]), columns=["x", "y", "z", "id"], ) peak_data = pd.concat([projected_df, mni_peaks]).astype( {"x": int, "y": int, "z": int} ) return peak_data
[ "numpy.hstack", "scipy.sparse.load_npz", "numpy.array", "pandas.concat", "nilearn.datasets.utils._fetch_files", "pandas.read_table", "numpy.genfromtxt" ]
[((1891, 1919), 'pandas.read_table', 'pd.read_table', (['metadata_file'], {}), '(metadata_file)\n', (1904, 1919), True, 'import pandas as pd\n'), ((3386, 3480), 'nilearn.datasets.utils._fetch_files', '_fetch_files', (['data_dir', '[(fn, NS_DATA_URL + fn, {}) for fn in file_names]'], {'verbose': 'verbose'}), '(data_dir, [(fn, NS_DATA_URL + fn, {}) for fn in file_names],\n verbose=verbose)\n', (3398, 3480), False, 'from nilearn.datasets.utils import _fetch_files\n'), ((3631, 3656), 'scipy.sparse.load_npz', 'sparse.load_npz', (['files[0]'], {}), '(files[0])\n', (3646, 3656), False, 'from scipy import sparse\n'), ((5773, 5804), 'pandas.read_table', 'pd.read_table', (['coordinates_file'], {}), '(coordinates_file)\n', (5786, 5804), True, 'import pandas as pd\n'), ((1656, 1759), 'nilearn.datasets.utils._fetch_files', '_fetch_files', (['data_dir', '[(metadata_filename, NS_DATA_URL + metadata_filename, {})]'], {'verbose': 'verbose'}), '(data_dir, [(metadata_filename, NS_DATA_URL + metadata_filename,\n {})], verbose=verbose)\n', (1668, 1759), False, 'from nilearn.datasets.utils import _fetch_files\n'), ((5529, 5638), 'nilearn.datasets.utils._fetch_files', '_fetch_files', (['data_dir', '[(coordinates_filename, NS_DATA_URL + coordinates_filename, {})]'], {'verbose': 'verbose'}), '(data_dir, [(coordinates_filename, NS_DATA_URL +\n coordinates_filename, {})], verbose=verbose)\n', (5541, 5638), False, 'from nilearn.datasets.utils import _fetch_files\n'), ((9686, 9738), 'numpy.hstack', 'np.hstack', (["[projected, non_mni_peaks[['id']].values]"], {}), "([projected, non_mni_peaks[['id']].values])\n", (9695, 9738), True, 'import numpy as np\n'), ((3880, 3930), 'numpy.genfromtxt', 'np.genfromtxt', (['files[1]'], {'dtype': 'str', 'delimiter': '"""\t"""'}), "(files[1], dtype=str, delimiter='\\t')\n", (3893, 3930), True, 'import numpy as np\n'), ((9121, 9265), 'numpy.array', 'np.array', (['[[0.9254, 0.0024, -0.0118, -1.0207], [-0.0048, 0.9316, -0.0871, -1.7667], [\n 0.0152, 0.0883, 0.8924, 4.0926], [0.0, 0.0, 0.0, 1.0]]'], {}), '([[0.9254, 0.0024, -0.0118, -1.0207], [-0.0048, 0.9316, -0.0871, -\n 1.7667], [0.0152, 0.0883, 0.8924, 4.0926], [0.0, 0.0, 0.0, 1.0]])\n', (9129, 9265), True, 'import numpy as np\n'), ((9801, 9837), 'pandas.concat', 'pd.concat', (['[projected_df, mni_peaks]'], {}), '([projected_df, mni_peaks])\n', (9810, 9837), True, 'import pandas as pd\n')]
from typing import Any from typing import Generic from typing import overload from typing import Type from typing import TypeVar from . import compat if compat.py38: from typing import Literal from typing import Protocol from typing import TypedDict else: from typing_extensions import Literal # noqa from typing_extensions import Protocol # noqa from typing_extensions import TypedDict # noqa if compat.py311: from typing import NotRequired # noqa else: from typing_extensions import NotRequired # noqa _T = TypeVar("_T") class _TypeToInstance(Generic[_T]): @overload def __get__(self, instance: None, owner: Any) -> Type[_T]: ... @overload def __get__(self, instance: object, owner: Any) -> _T: ... @overload def __set__(self, instance: None, value: Type[_T]) -> None: ... @overload def __set__(self, instance: object, value: _T) -> None: ...
[ "typing.TypeVar" ]
[((552, 565), 'typing.TypeVar', 'TypeVar', (['"""_T"""'], {}), "('_T')\n", (559, 565), False, 'from typing import TypeVar\n')]
# Created by <NAME>. import sys import numpy as np sys.path.append('../') from envs import GridWorld from itertools import product from utils import print_episode, eps_greedy_policy, test_policy ''' n-step Tree Backup used to estimate the optimal policy for the gridworld environment defined on page 48 of "Reinforcement Learning: An Introduction." Algorithm available on page 125. Book reference: <NAME>. and <NAME>., 2014. Reinforcement Learning: An Introduction. 1st ed. London: The MIT Press. ''' def policy_proba(policy, s, a, epsilon): '''Return the probability of the given epsilon-greedy policy taking the specified action in the specified state.''' if policy[s] == a: return (epsilon/4) + (1-epsilon) else: return epsilon/4 def n_step_tree_backup(env, n, alpha, gamma, epsilon, n_episodes): # Initialize policy and state-action value function. sa_pairs = product(range(env.observation_space_size),\ range(env.action_space_size)) Q = dict.fromkeys(sa_pairs, 0.0) policy = dict.fromkeys(range(env.observation_space_size), 0) states = np.zeros(n) actions = np.zeros(n) Qs = np.zeros(n) deltas = np.zeros(n) pis = np.zeros(n) decay = lambda x: x-2/n_episodes if x-2/n_episodes > 0.1 else 0.1 for episode in range(n_episodes): done = False obs = env.reset() action = eps_greedy_policy(Q, obs, epsilon, env.action_space_size) states[0] = obs actions[0] = action Qs[0] = Q[obs, action] t = -1 tau = -1 T = np.inf while not done or t != T-1: t += 1 if t < T: obs_prime, reward, done = env.step(action) states[(t+1)%n] = obs_prime if done: T = t+1 deltas[t%n] = reward - Qs[t%n] else: deltas[t%n] = reward + gamma * \ np.sum([policy_proba(policy, obs_prime, i, epsilon) * \ Q[obs_prime, i] for i in range(4)]) - Qs[t%n] action = eps_greedy_policy(Q, obs_prime, epsilon, \ env.action_space_size) Qs[(t+1)%n] = Q[obs_prime, action] pis[(t+1)%n] = policy_proba(policy, obs_prime, action, epsilon) tau = t-n+1 if tau > -1: Z = 1 G = Qs[tau%n] for k in range(tau,min(tau+n-1, T-1)): G += Z*deltas[k%n] Z *= gamma * Z * pis[(k+1)%n] s = states[tau%n] a = actions[tau%n] # Update state-action value function. Q[s,a] += alpha * (G - Q[s,a]) # Make policy greedy w.r.t. Q. action_values = [Q[s,i] for i in range(4)] policy[s] = np.argmax(action_values) epsilon = decay(epsilon) if episode % 100 == 0: print_episode(episode,n_episodes) print_episode(n_episodes, n_episodes) return policy if __name__ == '__main__': n = 4 alpha = 0.01 gamma = 1 epsilon = 1 n_episodes = 1000 env = GridWorld() policy = n_step_tree_backup(env, n , alpha, gamma, epsilon, n_episodes) test_policy(env, policy, 10)
[ "utils.test_policy", "utils.print_episode", "numpy.argmax", "envs.GridWorld", "numpy.zeros", "sys.path.append", "utils.eps_greedy_policy" ]
[((51, 73), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (66, 73), False, 'import sys\n'), ((1122, 1133), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (1130, 1133), True, 'import numpy as np\n'), ((1148, 1159), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (1156, 1159), True, 'import numpy as np\n'), ((1169, 1180), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (1177, 1180), True, 'import numpy as np\n'), ((1194, 1205), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (1202, 1205), True, 'import numpy as np\n'), ((1216, 1227), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (1224, 1227), True, 'import numpy as np\n'), ((3065, 3102), 'utils.print_episode', 'print_episode', (['n_episodes', 'n_episodes'], {}), '(n_episodes, n_episodes)\n', (3078, 3102), False, 'from utils import print_episode, eps_greedy_policy, test_policy\n'), ((3239, 3250), 'envs.GridWorld', 'GridWorld', ([], {}), '()\n', (3248, 3250), False, 'from envs import GridWorld\n'), ((3331, 3359), 'utils.test_policy', 'test_policy', (['env', 'policy', '(10)'], {}), '(env, policy, 10)\n', (3342, 3359), False, 'from utils import print_episode, eps_greedy_policy, test_policy\n'), ((1402, 1459), 'utils.eps_greedy_policy', 'eps_greedy_policy', (['Q', 'obs', 'epsilon', 'env.action_space_size'], {}), '(Q, obs, epsilon, env.action_space_size)\n', (1419, 1459), False, 'from utils import print_episode, eps_greedy_policy, test_policy\n'), ((3027, 3061), 'utils.print_episode', 'print_episode', (['episode', 'n_episodes'], {}), '(episode, n_episodes)\n', (3040, 3061), False, 'from utils import print_episode, eps_greedy_policy, test_policy\n'), ((2926, 2950), 'numpy.argmax', 'np.argmax', (['action_values'], {}), '(action_values)\n', (2935, 2950), True, 'import numpy as np\n'), ((2125, 2188), 'utils.eps_greedy_policy', 'eps_greedy_policy', (['Q', 'obs_prime', 'epsilon', 'env.action_space_size'], {}), '(Q, obs_prime, epsilon, env.action_space_size)\n', (2142, 2188), False, 'from utils import print_episode, eps_greedy_policy, test_policy\n')]
#!/usr/bin/env python3 import functools #https://stackoverflow.com/questions/3888158 def optional_arg_decorator(fn): @functools.wraps(fn) def wrapped_decorator(*args, **kwargs): # is_bound_method = hasattr(args[0], fn.__name__) if args else False # if is_bound_method: # klass = args[0] # args = args[1:] # If no arguments were passed... if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): # if is_bound_method: # return fn(klass, args[0]) # else: return fn(args[0]) else: def real_decorator(decoratee): # if is_bound_method: # return fn(klass, decoratee, *args, **kwargs) # else: return fn(decoratee, *args, **kwargs) return real_decorator return wrapped_decorator @optional_arg_decorator def __noop(func, *args, **kwargs): return(func) autojit = __noop generated_jit = __noop guvectorize = __noop jit = __noop jitclass = __noop njit = __noop vectorize = __noop b1 = None bool_ = None boolean = None byte = None c16 = None c8 = None char = None complex128 = None complex64 = None double = None f4 = None f8 = None ffi = None ffi_forced_object = None float32 = None float64 = None float_ = None i1 = None i2 = None i4 = None i8 = None int16 = None int32 = None int64 = None int8 = None int_ = None intc = None intp = None long_ = None longlong = None none = None short = None u1 = None u2 = None u4 = None u8 = None uchar = None uint = None uint16 = None uint32 = None uint64 = None uint8 = None uintc = None uintp = None ulong = None ulonglong = None ushort = None void = None
[ "functools.wraps" ]
[((124, 143), 'functools.wraps', 'functools.wraps', (['fn'], {}), '(fn)\n', (139, 143), False, 'import functools\n')]
from setuptools import setup from homeassistant_api import __version__ with open("README.md", "r") as f: read = f.read() setup( name="HomeAssistant API", url="https://github.com/GrandMoff100/HomeassistantAPI", description="Python Wrapper for Homeassistant's REST API", version=__version__, keywords=['homeassistant', 'api', 'wrapper', 'client'], author="GrandMoff100", author_email="<EMAIL>", packages=[ "homeassistant_api", "homeassistant_api.models", "homeassistant_api._async", "homeassistant_api._async.models" ], long_description=read, long_description_content_type="text/markdown", install_requires=["requests", "simplejson"], extras_require={ "async": ["aiohttp"] }, python_requires=">=3.6", provides=["homeassistant_api"], classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Software Development :: Version Control :: Git" ] )
[ "setuptools.setup" ]
[((127, 1396), 'setuptools.setup', 'setup', ([], {'name': '"""HomeAssistant API"""', 'url': '"""https://github.com/GrandMoff100/HomeassistantAPI"""', 'description': '"""Python Wrapper for Homeassistant\'s REST API"""', 'version': '__version__', 'keywords': "['homeassistant', 'api', 'wrapper', 'client']", 'author': '"""GrandMoff100"""', 'author_email': '"""<EMAIL>"""', 'packages': "['homeassistant_api', 'homeassistant_api.models',\n 'homeassistant_api._async', 'homeassistant_api._async.models']", 'long_description': 'read', 'long_description_content_type': '"""text/markdown"""', 'install_requires': "['requests', 'simplejson']", 'extras_require': "{'async': ['aiohttp']}", 'python_requires': '""">=3.6"""', 'provides': "['homeassistant_api']", 'classifiers': "['Development Status :: 5 - Production/Stable',\n 'Intended Audience :: Developers', 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n 'Programming Language :: Python :: 3.10',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'Topic :: Software Development :: Version Control :: Git']"}), '(name=\'HomeAssistant API\', url=\n \'https://github.com/GrandMoff100/HomeassistantAPI\', description=\n "Python Wrapper for Homeassistant\'s REST API", version=__version__,\n keywords=[\'homeassistant\', \'api\', \'wrapper\', \'client\'], author=\n \'GrandMoff100\', author_email=\'<EMAIL>\', packages=[\'homeassistant_api\',\n \'homeassistant_api.models\', \'homeassistant_api._async\',\n \'homeassistant_api._async.models\'], long_description=read,\n long_description_content_type=\'text/markdown\', install_requires=[\n \'requests\', \'simplejson\'], extras_require={\'async\': [\'aiohttp\']},\n python_requires=\'>=3.6\', provides=[\'homeassistant_api\'], classifiers=[\n \'Development Status :: 5 - Production/Stable\',\n \'Intended Audience :: Developers\', \'Natural Language :: English\',\n \'Operating System :: OS Independent\',\n \'Programming Language :: Python :: 2.7\',\n \'Programming Language :: Python :: 3.5\',\n \'Programming Language :: Python :: 3.6\',\n \'Programming Language :: Python :: 3.7\',\n \'Programming Language :: Python :: 3.8\',\n \'Programming Language :: Python :: 3.9\',\n \'Programming Language :: Python :: 3.10\',\n \'Topic :: Software Development :: Libraries :: Python Modules\',\n \'Topic :: Software Development :: Version Control :: Git\'])\n', (132, 1396), False, 'from setuptools import setup\n')]
# -*- coding: utf-8 -*- """ Created on Tue Apr 14 13:33:17 2020 @Author: <NAME>, <NAME> @Institution: CBDD Group, Xiangya School of Pharmaceutical Science, CSU, China @Homepage: http://www.scbdd.com @Mail: <EMAIL>; <EMAIL> @Blog: https://blog.iamkotori.com ♥I love Princess Zelda forever♥ """ from multiprocessing import Pool import xml.etree.ElementTree as ET from lxml import etree from requests import Session import json import os os.chdir(r'') class MolFromProtein(object): """ """ def __init__(self, UniprotID): """ """ self.UniprotID = UniprotID self.session = Session() self.headers = { "Connection": "keep-alive", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", "Cookie": "_ga=GA1.3.757562829.1572445921; csrftoken=<KEY>; chembl-website-v0.2-data-protection-accepted=true; _gid=GA1.3.302613681.1586835743", "Host": "www.ebi.ac.uk", "Origin": "https://www.ebi.ac.uk", "Referer": "https://www.ebi.ac.uk/chembl/g/", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36" } def GetInfoFromUniprot(self): """ """ request_url = 'https://www.uniprot.org/uniprot/{}.xml'.format(self.UniprotID) try: r = self.session.get(request_url,timeout=30) if r.status_code == 200: tree = ET.fromstring(r.text) entry = tree[0] dbReference = entry.findall('{http://uniprot.org/uniprot}dbReference[@type="ChEMBL"]') res = [i.attrib['id'] for i in dbReference] # print(res) else: res = [None] except: res = [None] return ''.join(res) def GetDownloadID(self): """ """ ChEMBLID = self.GetInfoFromUniprot() url = 'https://www.ebi.ac.uk/chembl/g/#browse/activities/filter/target_chembl_id%3A{}%20AND%20standard_type%3A(IC50%20OR%20Ki%20OR%20EC50%20OR%20Kd)%20AND%20_exists_%3Astandard_value%20AND%20_exists_%3Aligand_efficiency'.format(ChEMBLID) # print(url) html = self.session.get(url, headers=self.headers).text tree = etree.HTML(html) token = tree.xpath('//*[@class="GLaDOS-top-s3cre7"]//@value')[0] # token = token.encode('utf-8').decode('utf-8') # print(token) data = { "csrfmiddlewaretoken": token, "index_name": "chembl_26_activity", "query": '{"bool":{"must":[{"query_string":{"analyze_wildcard":true,"query":"target_chembl_id:%s AND standard_type:(IC50 OR Ki OR EC50 OR Kd) AND _exists_:standard_value AND _exists_:ligand_efficiency"}}],"filter":[]}}'%(ChEMBLID), # "query": '{"bool":{"must":[{"query_string":{"analyze_wildcard": true,"query":"_metadata.related_targets.all_chembl_ids:%s"}}],"filter":[]}}'%(self.GetInfoFromUniprot()), "format": "CSV", "context_id": "undefined", "download_columns_group": "undefined", } # print(data['csrfmiddlewaretoken']) url = 'https://www.ebi.ac.uk/chembl/glados_api/shared/downloads/queue_download/' response = self.session.post(url, headers=self.headers, data=data) html = response.text # return html # print(json.loads(html)['download_id']) # print(html) return json.loads(html)['download_id'] def Download(self): url = 'https://www.ebi.ac.uk/chembl/dynamic-downloads/%s.gz'%(self.GetDownloadID()) # print(url) r = self.session.get(url, headers=self.headers) assert r.status_code == 200 with open('./data/{}.csv.gz'.format(self.UniprotID), 'wb') as f_obj: for chunk in r.iter_content(chunk_size=512): f_obj.write(chunk) f_obj.close() print('{} Finished'.format(self.UniprotID)) def main(UniprotID): """ """ try: download = MolFromProtein(UniprotID) download.Download() except: with open('Error.log', 'a') as f_obj: f_obj.write(UniprotID) f_obj.write('\n') f_obj.close() if '__main__' == __name__: import pandas as pd data = pd.read_csv(r'pro_info.csv') unis = data.uni.tolist() ps = Pool() for UniprotID in unis: ps.apply_async(main, args=(UniprotID, )) ps.close() ps.join()
[ "json.loads", "requests.Session", "pandas.read_csv", "os.chdir", "lxml.etree.HTML", "multiprocessing.Pool", "xml.etree.ElementTree.fromstring" ]
[((439, 451), 'os.chdir', 'os.chdir', (['""""""'], {}), "('')\n", (447, 451), False, 'import os\n'), ((4520, 4547), 'pandas.read_csv', 'pd.read_csv', (['"""pro_info.csv"""'], {}), "('pro_info.csv')\n", (4531, 4547), True, 'import pandas as pd\n'), ((4592, 4598), 'multiprocessing.Pool', 'Pool', ([], {}), '()\n', (4596, 4598), False, 'from multiprocessing import Pool\n'), ((617, 626), 'requests.Session', 'Session', ([], {}), '()\n', (624, 626), False, 'from requests import Session\n'), ((2441, 2457), 'lxml.etree.HTML', 'etree.HTML', (['html'], {}), '(html)\n', (2451, 2457), False, 'from lxml import etree\n'), ((3652, 3668), 'json.loads', 'json.loads', (['html'], {}), '(html)\n', (3662, 3668), False, 'import json\n'), ((1596, 1617), 'xml.etree.ElementTree.fromstring', 'ET.fromstring', (['r.text'], {}), '(r.text)\n', (1609, 1617), True, 'import xml.etree.ElementTree as ET\n')]
# !/usr/bin/env python # -*- coding: utf-8 -*- # It's written by https://github.com/yumatsuoka from __future__ import print_function import math from torch.optim.lr_scheduler import _LRScheduler class FlatplusAnneal(_LRScheduler): def __init__(self, optimizer, max_iter, step_size=0.7, eta_min=0, last_epoch=-1): self.flat_range = int(max_iter * step_size) self.T_max = max_iter - self.flat_range self.eta_min = 0 super(FlatplusAnneal, self).__init__(optimizer, last_epoch) def get_lr(self): if self.last_epoch < self.flat_range: return [base_lr for base_lr in self.base_lrs] else: cr_epoch = self.last_epoch - self.flat_range return [ self.eta_min + (base_lr - self.eta_min) * (1 + math.cos(math.pi * (cr_epoch / self.T_max))) / 2 for base_lr in self.base_lrs ] if __name__ == "__main__": import torch # import matplotlib.pyplot as plt def check_scheduler(optimizer, scheduler, epochs): lr_list = [] for epoch in range(epochs): now_lr = scheduler.get_lr() lr_list.append(now_lr) optimizer.step() scheduler.step() return lr_list # def show_graph(lr_lists, epochs): # plt.clf() # plt.rcParams["figure.figsize"] = [20, 5] # x = list(range(epochs)) # plt.plot(x, lr_lists, label="line L") # plt.plot() # plt.xlabel("iterations") # plt.ylabel("learning rate") # plt.title("Check Flat plus cosine annealing lr") # plt.show() lr = 0.1 epochs = 100 model = torch.nn.Linear(10, 2) optimizer = torch.optim.SGD(model.parameters(), lr=lr) scheduler = FlatplusAnneal(optimizer, max_iter=epochs, step_size=0.7) lrs = check_scheduler(optimizer, scheduler, epochs) # show_graph(lrs, epochs)
[ "math.cos", "torch.nn.Linear" ]
[((1711, 1733), 'torch.nn.Linear', 'torch.nn.Linear', (['(10)', '(2)'], {}), '(10, 2)\n', (1726, 1733), False, 'import torch\n'), ((828, 871), 'math.cos', 'math.cos', (['(math.pi * (cr_epoch / self.T_max))'], {}), '(math.pi * (cr_epoch / self.T_max))\n', (836, 871), False, 'import math\n')]
"""Git helper functions. Everything in here should be project agnostic, shouldn't rely on project's structure, and make any assumptions about the passed arguments or calls outcomes. """ import subprocess def apply(repo, patch_path, reverse=False): args = ['git', 'apply', '--directory', repo, '--ignore-space-change', '--ignore-whitespace', '--whitespace', 'fix' ] if reverse: args += ['--reverse'] args += ['--', patch_path] return_code = subprocess.call(args) applied_successfully = (return_code == 0) return applied_successfully
[ "subprocess.call" ]
[((507, 528), 'subprocess.call', 'subprocess.call', (['args'], {}), '(args)\n', (522, 528), False, 'import subprocess\n')]
import sys import os import timeit # use local python package rather than the system install sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../python")) from bitboost import BitBoostRegressor import numpy as np import sklearn.metrics nfeatures = 5 nexamples = 10000 data = np.random.choice(np.array([0.0, 1.0, 2.0], dtype=BitBoostRegressor.numt), size=(nexamples * 2, nfeatures)) target = (1.22 * (data[:, 0] > 1.0) + 0.65 * (data[:, 1] > 1.0) + 0.94 * (data[:, 2] != 2.0) + 0.13 * (data[:, 3] == 1.0)).astype(BitBoostRegressor.numt) dtrain, ytrain = data[0:nexamples, :], target[0:nexamples] dtest, ytest = data[nexamples:, :], target[nexamples:] bit = BitBoostRegressor() bit.objective = "l2" bit.discr_nbits = 4 bit.max_tree_depth = 5 bit.learning_rate = 0.5 bit.niterations = 50 bit.categorical_features = list(range(nfeatures)) bit.fit(dtrain, ytrain) train_pred = bit.predict(dtrain) test_pred = bit.predict(dtest) train_acc = sklearn.metrics.mean_absolute_error(ytrain, train_pred) test_acc = sklearn.metrics.mean_absolute_error(ytest, test_pred) print(f"bit train accuracy: {train_acc}") print(f"bit test accuracy: {test_acc}")
[ "os.path.dirname", "numpy.array", "bitboost.BitBoostRegressor" ]
[((719, 738), 'bitboost.BitBoostRegressor', 'BitBoostRegressor', ([], {}), '()\n', (736, 738), False, 'from bitboost import BitBoostRegressor\n'), ((306, 361), 'numpy.array', 'np.array', (['[0.0, 1.0, 2.0]'], {'dtype': 'BitBoostRegressor.numt'}), '([0.0, 1.0, 2.0], dtype=BitBoostRegressor.numt)\n', (314, 361), True, 'import numpy as np\n'), ((126, 151), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (141, 151), False, 'import os\n')]
import unittest import os import logging import time import re import splunklib.client as client import splunklib.results as results from splunklib.binding import HTTPError from . import dltk_api from . import splunk_api from . import dltk_environment level_prog = re.compile(r'level=\"([^\"]*)\"') msg_prog = re.compile(r'msg=\"((?:\n|.)*)\"') def run_job(algorithm_name): environment_name = dltk_environment.get_name() # raise Exception("| savedsearch job:deploy:%s:%s | %s" % ( # algorithm_name, # environment_name, # 'rex field=_raw "level=\\"(?<level>[^\\"]*)\\", msg=\\"(?<msg>[^[\\"|\\\\"]*)\\"" | table level msg', # )) for event in splunk_api.search("| savedsearch job:deploy:%s:%s | %s" % ( algorithm_name, environment_name, #'rex field=_raw "level=\\"(?<level>[^\\"]*)\\", msg=\\"(?<msg>.*)\\"" | table _raw level msg', #'rex field=_raw "level=\\"(?<level>[^\\"]*)\\", msg=\\"(?<msg>(?:\\n|.)*)\\"" | table _raw level msg', 'table _raw', )): raw = event["_raw"] if "level" not in event: m = level_prog.search(raw) if m: event["level"] = m.group(1) if "msg" not in event: m = msg_prog.search(raw) if m: event["msg"] = m.group(1) if "level" in event: level = event["level"] else: #logging.error("missing 'level' field in deploy result: %s" % (event)) raise Exception("missing 'level' field in deploy result: %s" % raw) # continue msg = event["msg"] if level == "DEBUG": log = logging.debug elif level == "WARNING": log = logging.warning elif level == "ERROR": log = logging.error elif level == "INFO": log = logging.info else: log = logging.warning msg = "UNEXPECTED LEVEL (%s): %s" % (level, msg) log(" %s" % msg) def list_deployments(algorithm_name): return dltk_api.call( "GET", "deployments", data={ "algorithm": algorithm_name, } ) def get_deployment(algorithm_name, environment_name, raise_if_not_exists=True): deployments = dltk_api.call( "GET", "deployments", data={ "algorithm": algorithm_name, "environment": environment_name, } ) if not len(deployments): if raise_if_not_exists: raise Exception("could not find deployment") return None return deployments[0] def deploy(algorithm_name, params={}): undeploy(algorithm_name) splunk = splunk_api.connect() environment_name = dltk_environment.get_name() dltk_api.call("POST", "deployments", data={ **{ "algorithm": algorithm_name, "environment": environment_name, "enable_schedule": False, }, **params, }, return_entries=False) try: while True: deployment = get_deployment(algorithm_name, environment_name, raise_if_not_exists=False) if deployment: deployment = get_deployment(algorithm_name, environment_name) status = deployment["status"] if status == "deploying": logging.info("still deploying...") run_job(algorithm_name) continue if status == "deployed": break status_message = deployment["status_message"] raise Exception("unexpected deployment status: %s: %s" % (status, status_message)) logging.info("successfully deployed algo \"%s\"" % algorithm_name) except: logging.warning("error deploying '%s' to '%s' -> undeploying ..." % (algorithm_name, environment_name)) # while True: # import time # time.sleep(10) undeploy(algorithm_name) logging.warning("finished undeploying") raise def undeploy(algorithm_name): splunk = splunk_api.connect() environment_name = dltk_environment.get_name() while True: try: dltk_api.call("DELETE", "deployments", data={ "algorithm": algorithm_name, "environment": environment_name, "enable_schedule": False, }, return_entries=False) except HTTPError as e: logging.error("error calling API: %s" % e) if e.status == 404: break raise run_job(algorithm_name)
[ "logging.warning", "logging.info", "logging.error", "re.compile" ]
[((268, 303), 're.compile', 're.compile', (['"""level=\\\\"([^\\\\"]*)\\\\\\""""'], {}), '(\'level=\\\\"([^\\\\"]*)\\\\"\')\n', (278, 303), False, 'import re\n'), ((313, 349), 're.compile', 're.compile', (['"""msg=\\\\"((?:\\\\n|.)*)\\\\\\""""'], {}), '(\'msg=\\\\"((?:\\\\n|.)*)\\\\"\')\n', (323, 349), False, 'import re\n'), ((3705, 3769), 'logging.info', 'logging.info', (['(\'successfully deployed algo "%s"\' % algorithm_name)'], {}), '(\'successfully deployed algo "%s"\' % algorithm_name)\n', (3717, 3769), False, 'import logging\n'), ((3792, 3900), 'logging.warning', 'logging.warning', (['("error deploying \'%s\' to \'%s\' -> undeploying ..." % (algorithm_name,\n environment_name))'], {}), '("error deploying \'%s\' to \'%s\' -> undeploying ..." % (\n algorithm_name, environment_name))\n', (3807, 3900), False, 'import logging\n'), ((4012, 4051), 'logging.warning', 'logging.warning', (['"""finished undeploying"""'], {}), "('finished undeploying')\n", (4027, 4051), False, 'import logging\n'), ((4486, 4528), 'logging.error', 'logging.error', (["('error calling API: %s' % e)"], {}), "('error calling API: %s' % e)\n", (4499, 4528), False, 'import logging\n'), ((3361, 3395), 'logging.info', 'logging.info', (['"""still deploying..."""'], {}), "('still deploying...')\n", (3373, 3395), False, 'import logging\n')]
from pydc import DC def main(): dc = DC("example_dc.pl", 200) #default is 0 sample (will produce nan if later on no n_samples provided) prob1 = dc.query("drawn(1)~=1") print(prob1) prob2 = dc.query("drawn(1)~=1", n_samples=2000) print(prob2) if __name__ == "__main__": main()
[ "pydc.DC" ]
[((42, 66), 'pydc.DC', 'DC', (['"""example_dc.pl"""', '(200)'], {}), "('example_dc.pl', 200)\n", (44, 66), False, 'from pydc import DC\n')]
from pymongo import MongoClient def path(): client = MongoClient('mongodb://localhost:27017/') db = client['UserBook'] return db
[ "pymongo.MongoClient" ]
[((59, 100), 'pymongo.MongoClient', 'MongoClient', (['"""mongodb://localhost:27017/"""'], {}), "('mongodb://localhost:27017/')\n", (70, 100), False, 'from pymongo import MongoClient\n')]
import os from ..utils.log import log from ..utils.yaml import read_yaml, write_yaml class BaseSpec: COMPONENTS = 'components' REF_FIELD = '$ref' def __init__(self, path, read_func=read_yaml, write_func=write_yaml): self.path = path self.path_dir = os.path.dirname(path) self.read_func = read_yaml self.write_func = write_yaml self.data = None self.ref_filenames = set() self.ref_paths = [] self.ref_spec = {} def __enter__(self): self.read() return self def __exit__(self, exc_type, exc_value, traceback): pass def read(self): self.data = self.read_func(self.path) def write(self, path): self.write_func(self.data, path) def get_external_refs_from_object(self, data): for key, value in data.items(): if isinstance(value, dict): yield from self.get_external_refs_from_object(value) elif isinstance(value, list): yield from self.get_external_refs_from_list(value) if key == self.REF_FIELD: pos = value.find('#/') if pos > 0: filename = value[:pos] if os.path.basename(self.path) != filename: yield filename def get_external_refs_from_list(self, data): for value in data: if isinstance(value, dict): yield from self.get_external_refs_from_object(value) elif isinstance(value, list): yield from self.get_external_refs_from_list(value) def get_external_refs(self, data): yield from self.get_external_refs_from_object(data) def walk(self, data): for filename in self.get_external_refs(data): self.ref_filenames.add(filename) def create_ref_spec(self, ref_path): with ReferenceSpec(ref_path) as spec: spec.resolve() spec.bundle() log.debug(f'created ref spec: {ref_path}') return spec def resolve(self): self.walk(self.data) for filename in self.ref_filenames: ref_path = os.path.join(self.path_dir, filename) self.ref_paths.append(ref_path) self.ref_spec[filename] = self.create_ref_spec(ref_path) self.replace_ref_fields(self.data) def replace_ref_fields(self, data): def replace(data, field, value): pos = value.find('#/') if pos > 0: filename = value[:pos] data[field] = value.replace(f'{filename}', '') log.debug(f'replaced ref field "{value}" to "{data[field]}"') for field, value in data.items(): if isinstance(value, dict): self.replace_ref_fields(value) elif isinstance(value, list): for v in value: self.replace_ref_fields({'dummy': v}) if field == self.REF_FIELD: replace(data, field, value) def merge_components(self): components = self.data.get(self.COMPONENTS, {}) for spec in self.ref_spec.values(): spec_components = spec.data.get(self.COMPONENTS, {}) for key, value in spec_components.items(): components.setdefault(key, {}) components[key].update(value) def bundle(self): self.merge_components() class ReferenceSpec(BaseSpec): pass class BundledSpec(BaseSpec): pass
[ "os.path.dirname", "os.path.join", "os.path.basename" ]
[((300, 321), 'os.path.dirname', 'os.path.dirname', (['path'], {}), '(path)\n', (315, 321), False, 'import os\n'), ((2198, 2235), 'os.path.join', 'os.path.join', (['self.path_dir', 'filename'], {}), '(self.path_dir, filename)\n', (2210, 2235), False, 'import os\n'), ((1264, 1291), 'os.path.basename', 'os.path.basename', (['self.path'], {}), '(self.path)\n', (1280, 1291), False, 'import os\n')]
import os import numpy as np from six.moves import cPickle from tensorflow import keras from tensorflow import keras import helper from tfomics import utils, metrics, explain #------------------------------------------------------------------------ model_names = ['residualbind'] activations = ['exponential', 'relu']# results_path = utils.make_directory('../results', 'task6') params_path = utils.make_directory(results_path, 'model_params') #------------------------------------------------------------------------ file_path = '../data/IRF1_400_h3k27ac.h5' data = helper.load_data(file_path, reverse_compliment=True) x_train, y_train, x_valid, y_valid, x_test, y_test = data #------------------------------------------------------------------------ file_path = os.path.join(results_path, 'task6_classification_performance.tsv') with open(file_path, 'w') as f: f.write('%s\t%s\t%s\n'%('model', 'ave roc', 'ave pr')) results = {} for model_name in model_names: for activation in activations: keras.backend.clear_session() # load model model = helper.load_model(model_name, activation=activation) name = model_name+'_'+activation+'_irf1' print('model: ' + name) # compile model helper.compile_model(model) # setup callbacks callbacks = helper.get_callbacks(monitor='val_auroc', patience=20, decay_patience=5, decay_factor=0.2) # train model history = model.fit(x_train, y_train, epochs=100, batch_size=100, shuffle=True, validation_data=(x_valid, y_valid), callbacks=callbacks) # save model weights_path = os.path.join(params_path, name+'.hdf5') model.save_weights(weights_path) # predict test sequences and calculate performance metrics predictions = model.predict(x_test) mean_vals, std_vals = metrics.calculate_metrics(y_test, predictions, 'binary') # print results to file f.write("%s\t%.3f\t%.3f\n"%(name, mean_vals[1], mean_vals[2])) # calculate saliency on a subset of data true_index = np.where(y_test[:,0] == 1)[0] X = x_test[true_index][:500] results[name] = explain.saliency(model, X, class_index=0, layer=-1) # save results file_path = os.path.join(results_path, 'task6_saliency_results.pickle') with open(file_path, 'wb') as f: cPickle.dump(results, f, protocol=cPickle.HIGHEST_PROTOCOL)
[ "helper.get_callbacks", "helper.load_data", "numpy.where", "six.moves.cPickle.dump", "os.path.join", "helper.load_model", "tfomics.explain.saliency", "helper.compile_model", "tensorflow.keras.backend.clear_session", "tfomics.utils.make_directory", "tfomics.metrics.calculate_metrics" ]
[((338, 381), 'tfomics.utils.make_directory', 'utils.make_directory', (['"""../results"""', '"""task6"""'], {}), "('../results', 'task6')\n", (358, 381), False, 'from tfomics import utils, metrics, explain\n'), ((396, 446), 'tfomics.utils.make_directory', 'utils.make_directory', (['results_path', '"""model_params"""'], {}), "(results_path, 'model_params')\n", (416, 446), False, 'from tfomics import utils, metrics, explain\n'), ((573, 625), 'helper.load_data', 'helper.load_data', (['file_path'], {'reverse_compliment': '(True)'}), '(file_path, reverse_compliment=True)\n', (589, 625), False, 'import helper\n'), ((772, 838), 'os.path.join', 'os.path.join', (['results_path', '"""task6_classification_performance.tsv"""'], {}), "(results_path, 'task6_classification_performance.tsv')\n", (784, 838), False, 'import os\n'), ((2593, 2652), 'os.path.join', 'os.path.join', (['results_path', '"""task6_saliency_results.pickle"""'], {}), "(results_path, 'task6_saliency_results.pickle')\n", (2605, 2652), False, 'import os\n'), ((2690, 2749), 'six.moves.cPickle.dump', 'cPickle.dump', (['results', 'f'], {'protocol': 'cPickle.HIGHEST_PROTOCOL'}), '(results, f, protocol=cPickle.HIGHEST_PROTOCOL)\n', (2702, 2749), False, 'from six.moves import cPickle\n'), ((1034, 1063), 'tensorflow.keras.backend.clear_session', 'keras.backend.clear_session', ([], {}), '()\n', (1061, 1063), False, 'from tensorflow import keras\n'), ((1122, 1174), 'helper.load_model', 'helper.load_model', (['model_name'], {'activation': 'activation'}), '(model_name, activation=activation)\n', (1139, 1174), False, 'import helper\n'), ((1305, 1332), 'helper.compile_model', 'helper.compile_model', (['model'], {}), '(model)\n', (1325, 1332), False, 'import helper\n'), ((1388, 1482), 'helper.get_callbacks', 'helper.get_callbacks', ([], {'monitor': '"""val_auroc"""', 'patience': '(20)', 'decay_patience': '(5)', 'decay_factor': '(0.2)'}), "(monitor='val_auroc', patience=20, decay_patience=5,\n decay_factor=0.2)\n", (1408, 1482), False, 'import helper\n'), ((1910, 1951), 'os.path.join', 'os.path.join', (['params_path', "(name + '.hdf5')"], {}), "(params_path, name + '.hdf5')\n", (1922, 1951), False, 'import os\n'), ((2165, 2221), 'tfomics.metrics.calculate_metrics', 'metrics.calculate_metrics', (['y_test', 'predictions', '"""binary"""'], {}), "(y_test, predictions, 'binary')\n", (2190, 2221), False, 'from tfomics import utils, metrics, explain\n'), ((2513, 2564), 'tfomics.explain.saliency', 'explain.saliency', (['model', 'X'], {'class_index': '(0)', 'layer': '(-1)'}), '(model, X, class_index=0, layer=-1)\n', (2529, 2564), False, 'from tfomics import utils, metrics, explain\n'), ((2414, 2441), 'numpy.where', 'np.where', (['(y_test[:, 0] == 1)'], {}), '(y_test[:, 0] == 1)\n', (2422, 2441), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 21 14:15:38 2019 @author: Satish """ # doing the ortho-correction on the processed data from matchedFilter import os import numpy as np import spectral as spy import spectral.io.envi as envi import spectral.algorithms as algo from spectral.algorithms.detectors import MatchedFilter, matched_filter import logging import coloredlogs import json import shutil import statistics # set the logger logging.basicConfig(level=logging.INFO) logger = logging.getLogger("aviris_data_loader") coloredlogs.install(level='DEBUG', logger=logger) #DIRECTORY = "/media/data/satish/avng.jpl.nasa.gov/pub/test_unrect" DIRECTORY = "../../data/raw_data" #manual offset file load try: #Read the manually computed offset file f = open('./manual_offset.json') offset_data = json.load(f) OFFSET_DICT = offset_data['OFFSET_DICT'] except: print("No manual offset file found") pass FILES = [] for x in os.listdir(DIRECTORY): if(os.path.isdir(os.path.join(DIRECTORY, x))): FILES.append(x) print(FILES) #%% return image object def image_obj(hdr, img): "create a object of the image corresponding to certain header" head = envi.read_envi_header(hdr) param = envi.gen_params(head) param.filename = img # spectral data file corresponding to .hdr file interleave = head['interleave'] if (interleave == 'bip' or interleave == 'BIP'): print("it is a bip") from spectral.io.bipfile import BipFile img_obj = BipFile(param, head) if (interleave == 'bil' or interleave == 'BIL'): print("It is a bil file") from spectral.io.bilfile import BilFile img_obj = BilFile(param, head) return img_obj # Use this fucntion in case you have data other than the custom dataset def ideal_ortho_correction(glt: np.ndarray, img: np.ndarray, b_val=0.0, output=None) -> np.ndarray: """does the ortho-correction of the file glt: 2L, world-relative coordinates L1: y (rows), L2: x (columns) img: 1L, unrectified, output from matched filter output: 1L, rectified version of img, with shape: glt.shape """ if output is None: output = np.zeros((glt.shape[0], glt.shape[1])) if not np.array_equal(output.shape, [glt.shape[0], glt.shape[1]]): print("image dimension of output arrary do not match the GLT file") # getting the absolute even if GLT has negative values # magnitude glt_mag = np.absolute(glt) # GLT value of zero means no data, extract this because python has zero-indexing. glt_mask = np.all(glt_mag==0, axis=2) output[glt_mask] = b_val glt_mag[glt_mag>(img.shape[0]-1)] = 0 # now check the lookup and fill in the location, -1 to map to zero-indexing # output[~glt_mask] = img[glt_mag[~glt_mask, 1] - 1, glt_mag[~glt_mask, 0] - 1] output[~glt_mask] = img[glt_mag[~glt_mask, 1]-1, glt_mag[~glt_mask, 0]-1] return output def custom_ortho_correct_for_data(file_name, glt: np.ndarray, img: np.ndarray, OFFSET_DICT, b_val=0.0, output=None) -> np.ndarray: """does the ortho-correction of the file glt: 2L, world-relative coordinates L1: y (rows), L2: x (columns) img: 1L, unrectified, output from matched filter output: 1L, rectified version of img, with shape: glt.shape """ if output is None: output = np.zeros((glt.shape[0], glt.shape[1])) if not np.array_equal(output.shape, [glt.shape[0], glt.shape[1]]): print("image dimension of output arrary do not match the GLT file") print(file_name) if file_name in OFFSET_DICT.keys(): offset_mul = OFFSET_DICT[file_name] else: return 0 print(offset_mul) off_v = int(offset_mul*1005) img_readB = img[off_v:img.shape[0],:] img_readA = img[0:off_v,:] img_read = np.vstack((img_readB,img_readA)) if ((glt.shape[0]-img.shape[0])>0): print("size mismatch. Fixing it...") completion_shape = np.zeros((glt.shape[0]-img.shape[0], img.shape[1])) img_read = np.vstack((img_read,completion_shape)) print(img_read.shape) # getting the absolute even if GLT has negative values # magnitude glt_mag = np.absolute(glt) # GLT value of zero means no data, extract this because python has zero-indexing. glt_mask = np.all(glt_mag==0, axis=2) output[glt_mask] = b_val glt_mag[glt_mag>(img.shape[0]-1)] = 0 # now check the lookup and fill in the location, -1 to map to zero-indexing output[~glt_mask] = img_read[glt_mag[~glt_mask,1]-1, glt_mag[~glt_mask,0]-1] return output #%% load file and rectify it in each band for fname in FILES: fname_glt = fname.split("_")[0] sname_glt = f'{fname_glt}_rdn_glt' #geo-ref file for ortho-correction hname_glt = f'{sname_glt}.hdr' #header file glt_img = f'{DIRECTORY}/{fname}/{sname_glt}' glt_hdr = f'{DIRECTORY}/{fname}/{hname_glt}' print(glt_img, glt_hdr) mf_folder = f'{DIRECTORY}/{fname}/{fname_glt}_rdn_v1f_clip_mfout' try: if (fname_glt not in OFFSET_DICT.keys()): continue if (os.path.exists(glt_hdr)): glt_data_obj = image_obj(glt_hdr, glt_img) glt = glt_data_obj.read_bands([0,1]) else: continue except: pass #mf_rect_path = f'/media/data/satish/detector_bank_input/corrected_output' mf_rect_folder = f'{DIRECTORY}/{fname}/{fname_glt}_rect' if not(os.path.isdir(mf_rect_folder)): os.mkdir(mf_rect_folder) print("\nDirectory", mf_rect_folder ," created.") elif os.path.isdir(mf_rect_folder): print("\nDirectory", mf_rect_folder ," already exists..deleting it") shutil.rmtree(mf_rect_folder) os.mkdir(mf_rect_folder) print("\nNew Directory", mf_rect_folder ," created.") for mfname in os.listdir(mf_folder): print("Ortho-correcting file", mfname) mf_filename = f'{mf_folder}/{mfname}' img_unrect = np.load(mf_filename) print(img_unrect.shape) ''' use this function in case you have any other dataset, the custom_ortho_correct_for_data function uses the OFFSET_DICT to correct the row positions in each band. rect_img = ideal_ortho_correction(fname_glt, glt, img_unrect) ''' rect_img = custom_ortho_correct_for_data(fname_glt, glt, img_unrect, OFFSET_DICT) rect_filename = f'{mf_rect_folder}/{mfname}' np.save(rect_filename, rect_img)
[ "logging.getLogger", "spectral.io.envi.read_envi_header", "spectral.io.envi.gen_params", "numpy.save", "os.path.exists", "os.listdir", "os.path.isdir", "numpy.vstack", "os.mkdir", "spectral.io.bipfile.BipFile", "logging.basicConfig", "coloredlogs.install", "numpy.absolute", "os.path.join",...
[((467, 506), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (486, 506), False, 'import logging\n'), ((516, 555), 'logging.getLogger', 'logging.getLogger', (['"""aviris_data_loader"""'], {}), "('aviris_data_loader')\n", (533, 555), False, 'import logging\n'), ((556, 605), 'coloredlogs.install', 'coloredlogs.install', ([], {'level': '"""DEBUG"""', 'logger': 'logger'}), "(level='DEBUG', logger=logger)\n", (575, 605), False, 'import coloredlogs\n'), ((976, 997), 'os.listdir', 'os.listdir', (['DIRECTORY'], {}), '(DIRECTORY)\n', (986, 997), False, 'import os\n'), ((839, 851), 'json.load', 'json.load', (['f'], {}), '(f)\n', (848, 851), False, 'import json\n'), ((1228, 1254), 'spectral.io.envi.read_envi_header', 'envi.read_envi_header', (['hdr'], {}), '(hdr)\n', (1249, 1254), True, 'import spectral.io.envi as envi\n'), ((1267, 1288), 'spectral.io.envi.gen_params', 'envi.gen_params', (['head'], {}), '(head)\n', (1282, 1288), True, 'import spectral.io.envi as envi\n'), ((2513, 2529), 'numpy.absolute', 'np.absolute', (['glt'], {}), '(glt)\n', (2524, 2529), True, 'import numpy as np\n'), ((2632, 2660), 'numpy.all', 'np.all', (['(glt_mag == 0)'], {'axis': '(2)'}), '(glt_mag == 0, axis=2)\n', (2638, 2660), True, 'import numpy as np\n'), ((3873, 3906), 'numpy.vstack', 'np.vstack', (['(img_readB, img_readA)'], {}), '((img_readB, img_readA))\n', (3882, 3906), True, 'import numpy as np\n'), ((4243, 4259), 'numpy.absolute', 'np.absolute', (['glt'], {}), '(glt)\n', (4254, 4259), True, 'import numpy as np\n'), ((4361, 4389), 'numpy.all', 'np.all', (['(glt_mag == 0)'], {'axis': '(2)'}), '(glt_mag == 0, axis=2)\n', (4367, 4389), True, 'import numpy as np\n'), ((5906, 5927), 'os.listdir', 'os.listdir', (['mf_folder'], {}), '(mf_folder)\n', (5916, 5927), False, 'import os\n'), ((1028, 1054), 'os.path.join', 'os.path.join', (['DIRECTORY', 'x'], {}), '(DIRECTORY, x)\n', (1040, 1054), False, 'import os\n'), ((1553, 1573), 'spectral.io.bipfile.BipFile', 'BipFile', (['param', 'head'], {}), '(param, head)\n', (1560, 1573), False, 'from spectral.io.bipfile import BipFile\n'), ((1736, 1756), 'spectral.io.bilfile.BilFile', 'BilFile', (['param', 'head'], {}), '(param, head)\n', (1743, 1756), False, 'from spectral.io.bilfile import BilFile\n'), ((2238, 2276), 'numpy.zeros', 'np.zeros', (['(glt.shape[0], glt.shape[1])'], {}), '((glt.shape[0], glt.shape[1]))\n', (2246, 2276), True, 'import numpy as np\n'), ((2288, 2346), 'numpy.array_equal', 'np.array_equal', (['output.shape', '[glt.shape[0], glt.shape[1]]'], {}), '(output.shape, [glt.shape[0], glt.shape[1]])\n', (2302, 2346), True, 'import numpy as np\n'), ((3407, 3445), 'numpy.zeros', 'np.zeros', (['(glt.shape[0], glt.shape[1])'], {}), '((glt.shape[0], glt.shape[1]))\n', (3415, 3445), True, 'import numpy as np\n'), ((3457, 3515), 'numpy.array_equal', 'np.array_equal', (['output.shape', '[glt.shape[0], glt.shape[1]]'], {}), '(output.shape, [glt.shape[0], glt.shape[1]])\n', (3471, 3515), True, 'import numpy as np\n'), ((4018, 4071), 'numpy.zeros', 'np.zeros', (['(glt.shape[0] - img.shape[0], img.shape[1])'], {}), '((glt.shape[0] - img.shape[0], img.shape[1]))\n', (4026, 4071), True, 'import numpy as np\n'), ((4089, 4128), 'numpy.vstack', 'np.vstack', (['(img_read, completion_shape)'], {}), '((img_read, completion_shape))\n', (4098, 4128), True, 'import numpy as np\n'), ((5168, 5191), 'os.path.exists', 'os.path.exists', (['glt_hdr'], {}), '(glt_hdr)\n', (5182, 5191), False, 'import os\n'), ((5510, 5539), 'os.path.isdir', 'os.path.isdir', (['mf_rect_folder'], {}), '(mf_rect_folder)\n', (5523, 5539), False, 'import os\n'), ((5550, 5574), 'os.mkdir', 'os.mkdir', (['mf_rect_folder'], {}), '(mf_rect_folder)\n', (5558, 5574), False, 'import os\n'), ((5642, 5671), 'os.path.isdir', 'os.path.isdir', (['mf_rect_folder'], {}), '(mf_rect_folder)\n', (5655, 5671), False, 'import os\n'), ((6043, 6063), 'numpy.load', 'np.load', (['mf_filename'], {}), '(mf_filename)\n', (6050, 6063), True, 'import numpy as np\n'), ((6518, 6550), 'numpy.save', 'np.save', (['rect_filename', 'rect_img'], {}), '(rect_filename, rect_img)\n', (6525, 6550), True, 'import numpy as np\n'), ((5758, 5787), 'shutil.rmtree', 'shutil.rmtree', (['mf_rect_folder'], {}), '(mf_rect_folder)\n', (5771, 5787), False, 'import shutil\n'), ((5796, 5820), 'os.mkdir', 'os.mkdir', (['mf_rect_folder'], {}), '(mf_rect_folder)\n', (5804, 5820), False, 'import os\n')]
# -*- coding: utf-8 -*- import numpy as np import csv import tensorflow as tf from config import Config from DataFeeder import DataFeeder,TestData from model import DKT from sklearn.metrics import f1_score,precision_score,recall_score indices = [precision_score,recall_score,f1_score] def make_prediction(folderName,index,max_iters = 200,target_key = 'FirstCorrect'): tf.reset_default_graph() cfg = Config(dataFile = '%s/Training.csv'%folderName) cfg.load() DF_train = DataFeeder(cfg) # problem vectors cfg.probVecs features = [['ProblemID','inp',[cfg.numP,8],False], ['FirstCorrect','inp',[2,8],True], ['EverCorrect','inp',[2,8],True], ['UsedHint','inp',[2,8],True]] targets = [['FirstCorrect',2 , 1. , [1., 1.2]]] model4train = DKT(features = features, targets = targets, keep_prob = 0.1, num_items = cfg.numP, rnn_units = [32,32], training = True, lr_decay = [1e-3,0.9,50]) model4test = DKT(features = features, targets = targets, keep_prob = 1., num_items = cfg.numP, rnn_units = [32,32], training = False, lr_decay = [5*1e-2,0.9,100]) session = tf.Session() session.run(tf.global_variables_initializer()) print('training on %s'%folderName) for i in range(1,max_iters+1): inputs,targets,bu_masks = DF_train.next_batch(batch_size = DF_train.size, cum = True) feed_data = model4train.zip_data(inputs,model4train.input_holders) feed_data_t = model4train.zip_data(targets,model4train.target_holders) feed_data.update(feed_data_t) _,predicts,costs = session.run([model4train.trainop, model4train.predicts, model4train.costs] , feed_dict=feed_data) if i%max_iters == 0: for name,values in predicts.items(): # y_pred = values[bu_masks] # y_true = targets[name][bu_masks] # indices = [func(y_true,y_pred) for func in evalue_indices] print('final cost',round(costs[target_key],3)) cfg_test = Config(dataFile = '%s/Test.csv'%folderName) cfg_test.load() TD = TestData(cfg_test) result = [] predictions = [] groundtruth = [] for data,(inputs,targets,seqIndices) in TD.export(): feed_data = model4test.zip_data(inputs,model4test.input_holders) predicts,probablities = session.run([model4test.predicts, model4test.probablities],feed_dict = feed_data) probs_on_correct = probablities[target_key][0,np.arange(inputs['lengths'][0]),seqIndices,1] y_pred = predicts[target_key][0,np.arange(inputs['lengths'][0]),seqIndices] y_true = targets[target_key][0,:] predictions.append(y_pred) groundtruth.append(y_true) for i in range(data.shape[0]): raw_data = list(data.iloc[i,:].values) raw_data +=[float(probs_on_correct[i]) , int(y_pred[i]) , index] result.append(raw_data) y_true = np.concatenate(groundtruth,axis=0) y_pred = np.concatenate(predictions,axis=0) index = [round(func(y_true,y_pred),3) for func in indices] print(' '*4,'testing',index) return result,list(data.columns) def main(datafolder): total_predicts = [] for i in range(10): predicts,labels = make_prediction(folderName = datafolder+'/fold%d'%i, index = i, max_iters = 400) total_predicts.extend(predicts) fobj = open('cv_predict.csv','w',newline='') writer = csv.writer(fobj) writer.writerow(labels+['pCorrectProblem','prediction','fold']) for line in total_predicts: writer.writerow(line) fobj.close() return True if __name__=='__main__': dataFolder = r'C:\Users\G7\Desktop\itemRL\DataChellenge\CV' main(dataFolder)
[ "tensorflow.reset_default_graph", "model.DKT", "tensorflow.Session", "config.Config", "csv.writer", "DataFeeder.TestData", "DataFeeder.DataFeeder", "tensorflow.global_variables_initializer", "numpy.concatenate", "numpy.arange" ]
[((388, 412), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (410, 412), True, 'import tensorflow as tf\n'), ((424, 471), 'config.Config', 'Config', ([], {'dataFile': "('%s/Training.csv' % folderName)"}), "(dataFile='%s/Training.csv' % folderName)\n", (430, 471), False, 'from config import Config\n'), ((504, 519), 'DataFeeder.DataFeeder', 'DataFeeder', (['cfg'], {}), '(cfg)\n', (514, 519), False, 'from DataFeeder import DataFeeder, TestData\n'), ((844, 984), 'model.DKT', 'DKT', ([], {'features': 'features', 'targets': 'targets', 'keep_prob': '(0.1)', 'num_items': 'cfg.numP', 'rnn_units': '[32, 32]', 'training': '(True)', 'lr_decay': '[0.001, 0.9, 50]'}), '(features=features, targets=targets, keep_prob=0.1, num_items=cfg.numP,\n rnn_units=[32, 32], training=True, lr_decay=[0.001, 0.9, 50])\n', (847, 984), False, 'from model import DKT\n'), ((1158, 1303), 'model.DKT', 'DKT', ([], {'features': 'features', 'targets': 'targets', 'keep_prob': '(1.0)', 'num_items': 'cfg.numP', 'rnn_units': '[32, 32]', 'training': '(False)', 'lr_decay': '[5 * 0.01, 0.9, 100]'}), '(features=features, targets=targets, keep_prob=1.0, num_items=cfg.numP,\n rnn_units=[32, 32], training=False, lr_decay=[5 * 0.01, 0.9, 100])\n', (1161, 1303), False, 'from model import DKT\n'), ((1467, 1479), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (1477, 1479), True, 'import tensorflow as tf\n'), ((2543, 2586), 'config.Config', 'Config', ([], {'dataFile': "('%s/Test.csv' % folderName)"}), "(dataFile='%s/Test.csv' % folderName)\n", (2549, 2586), False, 'from config import Config\n'), ((2624, 2642), 'DataFeeder.TestData', 'TestData', (['cfg_test'], {}), '(cfg_test)\n', (2632, 2642), False, 'from DataFeeder import DataFeeder, TestData\n'), ((3542, 3577), 'numpy.concatenate', 'np.concatenate', (['groundtruth'], {'axis': '(0)'}), '(groundtruth, axis=0)\n', (3556, 3577), True, 'import numpy as np\n'), ((3591, 3626), 'numpy.concatenate', 'np.concatenate', (['predictions'], {'axis': '(0)'}), '(predictions, axis=0)\n', (3605, 3626), True, 'import numpy as np\n'), ((4140, 4156), 'csv.writer', 'csv.writer', (['fobj'], {}), '(fobj)\n', (4150, 4156), False, 'import csv\n'), ((1497, 1530), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (1528, 1530), True, 'import tensorflow as tf\n'), ((3055, 3086), 'numpy.arange', 'np.arange', (["inputs['lengths'][0]"], {}), "(inputs['lengths'][0])\n", (3064, 3086), True, 'import numpy as np\n'), ((3152, 3183), 'numpy.arange', 'np.arange', (["inputs['lengths'][0]"], {}), "(inputs['lengths'][0])\n", (3161, 3183), True, 'import numpy as np\n')]
# Generated by Django 2.2.10 on 2020-06-16 17:08 import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('reo', '0063_auto_20200521_1528'), ] operations = [ migrations.AddField( model_name='profilemodel', name='julia_input_construction_seconds', field=models.FloatField(blank=True, null=True), ), migrations.AddField( model_name='profilemodel', name='julia_input_construction_seconds_bau', field=models.FloatField(blank=True, null=True), ), migrations.AddField( model_name='profilemodel', name='julia_reopt_constriants_seconds', field=models.FloatField(blank=True, null=True), ), migrations.AddField( model_name='profilemodel', name='julia_reopt_constriants_seconds_bau', field=models.FloatField(blank=True, null=True), ), migrations.AddField( model_name='profilemodel', name='julia_reopt_optimize_seconds', field=models.FloatField(blank=True, null=True), ), migrations.AddField( model_name='profilemodel', name='julia_reopt_optimize_seconds_bau', field=models.FloatField(blank=True, null=True), ), migrations.AddField( model_name='profilemodel', name='julia_reopt_postprocess_seconds', field=models.FloatField(blank=True, null=True), ), migrations.AddField( model_name='profilemodel', name='julia_reopt_postprocess_seconds_bau', field=models.FloatField(blank=True, null=True), ), migrations.AddField( model_name='profilemodel', name='julia_reopt_preamble_seconds', field=models.FloatField(blank=True, null=True), ), migrations.AddField( model_name='profilemodel', name='julia_reopt_preamble_seconds_bau', field=models.FloatField(blank=True, null=True), ), migrations.AddField( model_name='profilemodel', name='julia_reopt_variables_seconds', field=models.FloatField(blank=True, null=True), ), migrations.AddField( model_name='profilemodel', name='julia_reopt_variables_seconds_bau', field=models.FloatField(blank=True, null=True), ), migrations.AlterField( model_name='loadprofilemodel', name='doe_reference_name', field=django.contrib.postgres.fields.ArrayField(base_field=models.TextField(blank=True, null=True), default=list, size=None), ), ]
[ "django.db.models.FloatField", "django.db.models.TextField" ]
[((401, 441), 'django.db.models.FloatField', 'models.FloatField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (418, 441), False, 'from django.db import migrations, models\n'), ((597, 637), 'django.db.models.FloatField', 'models.FloatField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (614, 637), False, 'from django.db import migrations, models\n'), ((788, 828), 'django.db.models.FloatField', 'models.FloatField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (805, 828), False, 'from django.db import migrations, models\n'), ((983, 1023), 'django.db.models.FloatField', 'models.FloatField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (1000, 1023), False, 'from django.db import migrations, models\n'), ((1171, 1211), 'django.db.models.FloatField', 'models.FloatField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (1188, 1211), False, 'from django.db import migrations, models\n'), ((1363, 1403), 'django.db.models.FloatField', 'models.FloatField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (1380, 1403), False, 'from django.db import migrations, models\n'), ((1554, 1594), 'django.db.models.FloatField', 'models.FloatField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (1571, 1594), False, 'from django.db import migrations, models\n'), ((1749, 1789), 'django.db.models.FloatField', 'models.FloatField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (1766, 1789), False, 'from django.db import migrations, models\n'), ((1937, 1977), 'django.db.models.FloatField', 'models.FloatField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (1954, 1977), False, 'from django.db import migrations, models\n'), ((2129, 2169), 'django.db.models.FloatField', 'models.FloatField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (2146, 2169), False, 'from django.db import migrations, models\n'), ((2318, 2358), 'django.db.models.FloatField', 'models.FloatField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (2335, 2358), False, 'from django.db import migrations, models\n'), ((2511, 2551), 'django.db.models.FloatField', 'models.FloatField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (2528, 2551), False, 'from django.db import migrations, models\n'), ((2748, 2787), 'django.db.models.TextField', 'models.TextField', ([], {'blank': '(True)', 'null': '(True)'}), '(blank=True, null=True)\n', (2764, 2787), False, 'from django.db import migrations, models\n')]
# Generated by Django 2.2 on 2019-06-08 10:32 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Adult_Products', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.ImageField(upload_to='product_images')), ('name', models.CharField(max_length=200)), ('category', models.CharField(max_length=300)), ('slug', models.SlugField()), ('sales_price', models.IntegerField()), ('original_price', models.IntegerField()), ], ), migrations.CreateModel( name='Essential_Oils', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.ImageField(upload_to='product_images')), ('name', models.CharField(max_length=200)), ('category', models.CharField(max_length=300)), ('slug', models.SlugField()), ('sales_price', models.IntegerField()), ('original_price', models.IntegerField()), ], ), migrations.CreateModel( name='Smart_Watches', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.ImageField(upload_to='product_images')), ('name', models.CharField(max_length=200)), ('category', models.CharField(max_length=300)), ('slug', models.SlugField()), ('sales_price', models.IntegerField()), ('original_price', models.IntegerField()), ], ), ]
[ "django.db.models.IntegerField", "django.db.models.SlugField", "django.db.models.AutoField", "django.db.models.ImageField", "django.db.models.CharField" ]
[((308, 401), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (324, 401), False, 'from django.db import migrations, models\n'), ((426, 471), 'django.db.models.ImageField', 'models.ImageField', ([], {'upload_to': '"""product_images"""'}), "(upload_to='product_images')\n", (443, 471), False, 'from django.db import migrations, models\n'), ((499, 531), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)'}), '(max_length=200)\n', (515, 531), False, 'from django.db import migrations, models\n'), ((563, 595), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(300)'}), '(max_length=300)\n', (579, 595), False, 'from django.db import migrations, models\n'), ((623, 641), 'django.db.models.SlugField', 'models.SlugField', ([], {}), '()\n', (639, 641), False, 'from django.db import migrations, models\n'), ((676, 697), 'django.db.models.IntegerField', 'models.IntegerField', ([], {}), '()\n', (695, 697), False, 'from django.db import migrations, models\n'), ((735, 756), 'django.db.models.IntegerField', 'models.IntegerField', ([], {}), '()\n', (754, 756), False, 'from django.db import migrations, models\n'), ((896, 989), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (912, 989), False, 'from django.db import migrations, models\n'), ((1014, 1059), 'django.db.models.ImageField', 'models.ImageField', ([], {'upload_to': '"""product_images"""'}), "(upload_to='product_images')\n", (1031, 1059), False, 'from django.db import migrations, models\n'), ((1087, 1119), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)'}), '(max_length=200)\n', (1103, 1119), False, 'from django.db import migrations, models\n'), ((1151, 1183), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(300)'}), '(max_length=300)\n', (1167, 1183), False, 'from django.db import migrations, models\n'), ((1211, 1229), 'django.db.models.SlugField', 'models.SlugField', ([], {}), '()\n', (1227, 1229), False, 'from django.db import migrations, models\n'), ((1264, 1285), 'django.db.models.IntegerField', 'models.IntegerField', ([], {}), '()\n', (1283, 1285), False, 'from django.db import migrations, models\n'), ((1323, 1344), 'django.db.models.IntegerField', 'models.IntegerField', ([], {}), '()\n', (1342, 1344), False, 'from django.db import migrations, models\n'), ((1483, 1576), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (1499, 1576), False, 'from django.db import migrations, models\n'), ((1601, 1646), 'django.db.models.ImageField', 'models.ImageField', ([], {'upload_to': '"""product_images"""'}), "(upload_to='product_images')\n", (1618, 1646), False, 'from django.db import migrations, models\n'), ((1674, 1706), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)'}), '(max_length=200)\n', (1690, 1706), False, 'from django.db import migrations, models\n'), ((1738, 1770), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(300)'}), '(max_length=300)\n', (1754, 1770), False, 'from django.db import migrations, models\n'), ((1798, 1816), 'django.db.models.SlugField', 'models.SlugField', ([], {}), '()\n', (1814, 1816), False, 'from django.db import migrations, models\n'), ((1851, 1872), 'django.db.models.IntegerField', 'models.IntegerField', ([], {}), '()\n', (1870, 1872), False, 'from django.db import migrations, models\n'), ((1910, 1931), 'django.db.models.IntegerField', 'models.IntegerField', ([], {}), '()\n', (1929, 1931), False, 'from django.db import migrations, models\n')]
#!/usr/bin/env python """This module remains for backwards compatibility reasons and will be removed in PyDy 0.4.0.""" import warnings from .ode_function_generators import generate_ode_function as new_gen_ode_func with warnings.catch_warnings(): warnings.simplefilter('once') warnings.warn("This module, 'pydy.codgen.code', is deprecated. The " "function 'generate_ode_function' can be found in the " "'pydy.codegen.ode_function_generator' module. " "'CythonGenerator' has been removed, use " "'pydy.codegen.cython_code.CythonMatrixGenerator' " "instead.", DeprecationWarning) class CythonGenerator(object): def __init__(self, *args, **kwargs): with warnings.catch_warnings(): warnings.simplefilter('once') warnings.warn("'CythonGenerator' has been removed, use " "'pydy.codegen.cython_code.CythonMatrixGenerator' " "instead.", DeprecationWarning) def generate_ode_function(mass_matrix, forcing_vector, constants, coordinates, speeds, specified=None, generator='lambdify'): """Returns a numerical function which can evaluate the right hand side of the first order ordinary differential equations from a system described by: M(constants, coordinates) x' = F(constants, coordinates, speeds, specified) Parameters ---------- mass_matrix : sympy.Matrix, shape(n,n) The symbolic mass matrix of the system. The rows should correspond to the coordinates and speeds. forcing_vector : sympy.Matrix, shape(n,1) The symbolic forcing vector of the system. constants : list of sympy.Symbol The constants in the equations of motion. coordinates : list of sympy.Function The generalized coordinates of the system. speeds : list of sympy.Function The generalized speeds of the system. specified : list of sympy.Function The specifed quantities of the system. generator : string, {'lambdify'|'theano'|'cython'}, optional The method used for generating the numeric right hand side. Returns ------- evaluate_ode_function : function A function which evaluates the derivaties of the states. """ with warnings.catch_warnings(): warnings.simplefilter('once') warnings.warn("This function is deprecated and will be removed in " "PyDy 0.4.0. Use the the new 'generate_ode_function' " "in 'pydy.codegen.ode_function_generator'", DeprecationWarning) return new_gen_ode_func(forcing_vector, coordinates, speeds, constants, mass_matrix=mass_matrix, specifieds=specified, generator=generator)
[ "warnings.simplefilter", "warnings.warn", "warnings.catch_warnings" ]
[((223, 248), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (246, 248), False, 'import warnings\n'), ((254, 283), 'warnings.simplefilter', 'warnings.simplefilter', (['"""once"""'], {}), "('once')\n", (275, 283), False, 'import warnings\n'), ((288, 583), 'warnings.warn', 'warnings.warn', (['"""This module, \'pydy.codgen.code\', is deprecated. The function \'generate_ode_function\' can be found in the \'pydy.codegen.ode_function_generator\' module. \'CythonGenerator\' has been removed, use \'pydy.codegen.cython_code.CythonMatrixGenerator\' instead."""', 'DeprecationWarning'], {}), '(\n "This module, \'pydy.codgen.code\', is deprecated. The function \'generate_ode_function\' can be found in the \'pydy.codegen.ode_function_generator\' module. \'CythonGenerator\' has been removed, use \'pydy.codegen.cython_code.CythonMatrixGenerator\' instead."\n , DeprecationWarning)\n', (301, 583), False, 'import warnings\n'), ((2391, 2416), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (2414, 2416), False, 'import warnings\n'), ((2426, 2455), 'warnings.simplefilter', 'warnings.simplefilter', (['"""once"""'], {}), "('once')\n", (2447, 2455), False, 'import warnings\n'), ((2464, 2654), 'warnings.warn', 'warnings.warn', (['"""This function is deprecated and will be removed in PyDy 0.4.0. Use the the new \'generate_ode_function\' in \'pydy.codegen.ode_function_generator\'"""', 'DeprecationWarning'], {}), '(\n "This function is deprecated and will be removed in PyDy 0.4.0. Use the the new \'generate_ode_function\' in \'pydy.codegen.ode_function_generator\'"\n , DeprecationWarning)\n', (2477, 2654), False, 'import warnings\n'), ((784, 809), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (807, 809), False, 'import warnings\n'), ((823, 852), 'warnings.simplefilter', 'warnings.simplefilter', (['"""once"""'], {}), "('once')\n", (844, 852), False, 'import warnings\n'), ((865, 1009), 'warnings.warn', 'warnings.warn', (['"""\'CythonGenerator\' has been removed, use \'pydy.codegen.cython_code.CythonMatrixGenerator\' instead."""', 'DeprecationWarning'], {}), '(\n "\'CythonGenerator\' has been removed, use \'pydy.codegen.cython_code.CythonMatrixGenerator\' instead."\n , DeprecationWarning)\n', (878, 1009), False, 'import warnings\n')]
# ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ from azure.identity.aio._credentials.managed_identity import ImdsCredential import pytest from helpers_async import AsyncMockTransport @pytest.mark.asyncio async def test_imds_close(): transport = AsyncMockTransport() credential = ImdsCredential(transport=transport) await credential.close() assert transport.__aexit__.call_count == 1 @pytest.mark.asyncio async def test_imds_context_manager(): transport = AsyncMockTransport() credential = ImdsCredential(transport=transport) async with credential: pass assert transport.__aexit__.call_count == 1
[ "azure.identity.aio._credentials.managed_identity.ImdsCredential", "helpers_async.AsyncMockTransport" ]
[((355, 375), 'helpers_async.AsyncMockTransport', 'AsyncMockTransport', ([], {}), '()\n', (373, 375), False, 'from helpers_async import AsyncMockTransport\n'), ((394, 429), 'azure.identity.aio._credentials.managed_identity.ImdsCredential', 'ImdsCredential', ([], {'transport': 'transport'}), '(transport=transport)\n', (408, 429), False, 'from azure.identity.aio._credentials.managed_identity import ImdsCredential\n'), ((586, 606), 'helpers_async.AsyncMockTransport', 'AsyncMockTransport', ([], {}), '()\n', (604, 606), False, 'from helpers_async import AsyncMockTransport\n'), ((624, 659), 'azure.identity.aio._credentials.managed_identity.ImdsCredential', 'ImdsCredential', ([], {'transport': 'transport'}), '(transport=transport)\n', (638, 659), False, 'from azure.identity.aio._credentials.managed_identity import ImdsCredential\n')]
from django.http import HttpResponse from django.shortcuts import render, redirect from django.contrib.auth import login, logout, authenticate from django.contrib.auth.forms import AuthenticationForm from web3 import Web3 from .forms import SignupForm from Key.models import Key #The views and templates in this app are placeholders. Will use the ones in the Pages app instead later. #Currently deployed to local hardhat network only provider = Web3.HTTPProvider('http://127.0.0.1:8545/') web3 = Web3(provider) # Create your views here. def home_view(request): context={} if not request.user.is_authenticated: return render(request, 'User/home.html', context) else: return redirect('dashboard') def dashboard_view(request): context = {} if not request.user.is_authenticated: return redirect('home') else: context['username'] = request.user.username context['address'] = request.user.address context['balance'] = web3.fromWei(web3.eth.get_balance(request.user.address), 'ether') context['keys'] = Key.objects.filter(user=request.user,is_main_key=True) return render(request, 'User/dashboard.html', context) def signup_view(request): context = {} if request.POST: form = SignupForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('<PASSWORD>') user = authenticate(username=username,password=password) login(request,user) return redirect('home') else: context['signup_form'] = form else: form = SignupForm() context['signup_form'] = form return render(request, 'User/signup.html', context) def login_view(request): context = {} if request.POST: form = AuthenticationForm(request=request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username,password=password) if user is not None: login(request,user) return redirect('home') else: context['login_form'] = form else: form = AuthenticationForm() context['login_form'] = form return render(request, 'User/login.html', context) def logout_request(request): logout(request) return redirect('home')
[ "django.shortcuts.render", "django.contrib.auth.authenticate", "Key.models.Key.objects.filter", "django.contrib.auth.login", "web3.Web3", "django.contrib.auth.forms.AuthenticationForm", "django.shortcuts.redirect", "django.contrib.auth.logout", "web3.Web3.HTTPProvider" ]
[((449, 492), 'web3.Web3.HTTPProvider', 'Web3.HTTPProvider', (['"""http://127.0.0.1:8545/"""'], {}), "('http://127.0.0.1:8545/')\n", (466, 492), False, 'from web3 import Web3\n'), ((500, 514), 'web3.Web3', 'Web3', (['provider'], {}), '(provider)\n', (504, 514), False, 'from web3 import Web3\n'), ((1753, 1797), 'django.shortcuts.render', 'render', (['request', '"""User/signup.html"""', 'context'], {}), "(request, 'User/signup.html', context)\n", (1759, 1797), False, 'from django.shortcuts import render, redirect\n'), ((2402, 2445), 'django.shortcuts.render', 'render', (['request', '"""User/login.html"""', 'context'], {}), "(request, 'User/login.html', context)\n", (2408, 2445), False, 'from django.shortcuts import render, redirect\n'), ((2480, 2495), 'django.contrib.auth.logout', 'logout', (['request'], {}), '(request)\n', (2486, 2495), False, 'from django.contrib.auth import login, logout, authenticate\n'), ((2507, 2523), 'django.shortcuts.redirect', 'redirect', (['"""home"""'], {}), "('home')\n", (2515, 2523), False, 'from django.shortcuts import render, redirect\n'), ((638, 680), 'django.shortcuts.render', 'render', (['request', '"""User/home.html"""', 'context'], {}), "(request, 'User/home.html', context)\n", (644, 680), False, 'from django.shortcuts import render, redirect\n'), ((706, 727), 'django.shortcuts.redirect', 'redirect', (['"""dashboard"""'], {}), "('dashboard')\n", (714, 727), False, 'from django.shortcuts import render, redirect\n'), ((832, 848), 'django.shortcuts.redirect', 'redirect', (['"""home"""'], {}), "('home')\n", (840, 848), False, 'from django.shortcuts import render, redirect\n'), ((1082, 1137), 'Key.models.Key.objects.filter', 'Key.objects.filter', ([], {'user': 'request.user', 'is_main_key': '(True)'}), '(user=request.user, is_main_key=True)\n', (1100, 1137), False, 'from Key.models import Key\n'), ((1152, 1199), 'django.shortcuts.render', 'render', (['request', '"""User/dashboard.html"""', 'context'], {}), "(request, 'User/dashboard.html', context)\n", (1158, 1199), False, 'from django.shortcuts import render, redirect\n'), ((1877, 1931), 'django.contrib.auth.forms.AuthenticationForm', 'AuthenticationForm', ([], {'request': 'request', 'data': 'request.POST'}), '(request=request, data=request.POST)\n', (1895, 1931), False, 'from django.contrib.auth.forms import AuthenticationForm\n'), ((2332, 2352), 'django.contrib.auth.forms.AuthenticationForm', 'AuthenticationForm', ([], {}), '()\n', (2350, 2352), False, 'from django.contrib.auth.forms import AuthenticationForm\n'), ((1492, 1542), 'django.contrib.auth.authenticate', 'authenticate', ([], {'username': 'username', 'password': 'password'}), '(username=username, password=password)\n', (1504, 1542), False, 'from django.contrib.auth import login, logout, authenticate\n'), ((1554, 1574), 'django.contrib.auth.login', 'login', (['request', 'user'], {}), '(request, user)\n', (1559, 1574), False, 'from django.contrib.auth import login, logout, authenticate\n'), ((1593, 1609), 'django.shortcuts.redirect', 'redirect', (['"""home"""'], {}), "('home')\n", (1601, 1609), False, 'from django.shortcuts import render, redirect\n'), ((2093, 2143), 'django.contrib.auth.authenticate', 'authenticate', ([], {'username': 'username', 'password': 'password'}), '(username=username, password=password)\n', (2105, 2143), False, 'from django.contrib.auth import login, logout, authenticate\n'), ((2192, 2212), 'django.contrib.auth.login', 'login', (['request', 'user'], {}), '(request, user)\n', (2197, 2212), False, 'from django.contrib.auth import login, logout, authenticate\n'), ((2235, 2251), 'django.shortcuts.redirect', 'redirect', (['"""home"""'], {}), "('home')\n", (2243, 2251), False, 'from django.shortcuts import render, redirect\n')]
from flask import Flask, Blueprint from flask_jwt_extended import JWTManager def create_app(config): app = Flask(__name__) from instance.config import app_config app.config.from_object(app_config[config]) app.config['JWT_SECRET_KEY'] = 'jwt-secret-string' from .api.V1 import productsale_api as psa app.register_blueprint(psa) jwt = JWTManager(app) return app
[ "flask_jwt_extended.JWTManager", "flask.Flask" ]
[((113, 128), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (118, 128), False, 'from flask import Flask, Blueprint\n'), ((366, 381), 'flask_jwt_extended.JWTManager', 'JWTManager', (['app'], {}), '(app)\n', (376, 381), False, 'from flask_jwt_extended import JWTManager\n')]
""" preprocess MSP IMPROV csv run after MSP_IMPROV.py """ import os, torch, soundfile from pathlib import Path import librosa import pandas as pd ID2LABEL = { 0: "neu", 1: "sad", 2: "ang", 3: "hap" } pwd = Path(__file__).parent csv_dir = pwd / "../data/datasets/MSP-IMPROV" out_dir = pwd / "../data/datasets/MSP-IMPROV_12fold" os.makedirs(out_dir, exist_ok=True) # can compute stat here csv_path = csv_dir / f"post_session{1}.csv" dataset = pd.read_csv(csv_path) for sessionid in [2, 3, 4, 5, 6]: csv_path = csv_dir / f"post_session{sessionid}.csv" dataset = dataset.append( pd.read_csv(csv_path)) dataset.reset_index(inplace=True) for fold in range(1, 7): for gender in ["M", "F"]: partial = dataset[dataset["speaker"] == f"{gender}0{fold}"] assert len(partial) > 0 partial.to_csv( str(out_dir / f"post_session{fold}{gender}.csv"), index=False ) print()
[ "pathlib.Path", "os.makedirs", "pandas.read_csv" ]
[((332, 367), 'os.makedirs', 'os.makedirs', (['out_dir'], {'exist_ok': '(True)'}), '(out_dir, exist_ok=True)\n', (343, 367), False, 'import os, torch, soundfile\n'), ((447, 468), 'pandas.read_csv', 'pd.read_csv', (['csv_path'], {}), '(csv_path)\n', (458, 468), True, 'import pandas as pd\n'), ((211, 225), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (215, 225), False, 'from pathlib import Path\n'), ((589, 610), 'pandas.read_csv', 'pd.read_csv', (['csv_path'], {}), '(csv_path)\n', (600, 610), True, 'import pandas as pd\n')]
from django import template from django.template.loader import render_to_string register = template.Library() @register.simple_tag def richcomments_static(): return render_to_string('richcomments/templatetags/richcomments_static.html')
[ "django.template.loader.render_to_string", "django.template.Library" ]
[((92, 110), 'django.template.Library', 'template.Library', ([], {}), '()\n', (108, 110), False, 'from django import template\n'), ((171, 241), 'django.template.loader.render_to_string', 'render_to_string', (['"""richcomments/templatetags/richcomments_static.html"""'], {}), "('richcomments/templatetags/richcomments_static.html')\n", (187, 241), False, 'from django.template.loader import render_to_string\n')]
from logging import getLogger from openrazer.client import DeviceManager, constants as razer_constants from i3razer import config_contants as conf from i3razer.config_parser import ConfigParser from i3razer.layout import layouts from i3razer.pyxhook import HookManager ERR_DAEMON_OFF = -2 # openrazer is not running ERR_NO_KEYBOARD = -3 # no razer keyboard found ERR_CONFIG = -4 # Error in config file class I3Razer: _logger = None # Keyboard settings _serial = "" _keyboard = None _key_layout = {} _key_layout_name = "" # Only present if layout is set manually # handle modes and keys _listen_to_keys = set() # the keys which could change the displayed color scheme _current_pressed_keys = set() _current_scheme_name = "" _mode = None _config = None _drawing_scheme = set() # prevent infinite inherit loop in color schemes # Thread handling _hook = None _running = False def __init__(self, config_file, layout=None, logger=None): """ config_file: path to the config file layout: keyboard Layout to use for lighting the keys. If none is given it is detected automatically logger: Logger to use for logging """ if not logger: logger = getLogger(__name__) self._logger = logger self._load_config(config_file) self._load_keyboard(layout) def _update_color_scheme(self): """ Determines which color scheme should be displayed and displays it """ if self._running: if not self._mode: self._mode = self._config.get_mode_by_name(conf.mode_default) self._listen_to_keys = self._config.get_important_keys_mode(self._mode) self._logger.debug(f"pressed keys: {self._current_pressed_keys} in mode {self._mode[conf.field_name]}") # find mode next_mode = self._config.get_next_mode(self._current_pressed_keys, self._mode) if next_mode[conf.field_name] != self._mode[conf.field_name]: # swapped to a new mode self._mode = next_mode self._listen_to_keys = self._config.get_important_keys_mode(self._mode) # update color scheme for mode scheme = self._config.get_color_scheme(self._current_pressed_keys, self._mode) self._draw_color_scheme(scheme) def _draw_color_scheme(self, color_config): """ draw the given color scheme """ if self._current_scheme_name == color_config[conf.field_name]: return # parse type if conf.field_type in color_config: if color_config[conf.field_type] == conf.type_static: self._draw_static_scheme(color_config) else: self._draw_color_effect(color_config) else: self._draw_static_scheme(color_config) self._current_scheme_name = color_config[conf.field_name] self._logger.info(f"Drawn color scheme '{color_config[conf.field_name]}'") def _draw_color_effect(self, color_config): """ Draw an effect color scheme """ if conf.field_type not in color_config: return effect_type = color_config[conf.field_type] fx = self._keyboard.fx # find colors for effect color1, color2, color3 = None, None, None nr_colors = 0 if conf.type_color in color_config: color1 = self._config.get_color(color_config[conf.type_color]) nr_colors = 1 elif conf.type_color1 in color_config: color1 = self._config.get_color(color_config[conf.type_color1]) nr_colors = 1 if conf.type_color2 in color_config: color2 = self._config.get_color(color_config[conf.type_color2]) nr_colors = 2 if conf.type_color3 in color_config: color3 = self._config.get_color(color_config[conf.type_color3]) nr_colors = 3 # huge switch through all modes ----------------------------------------------------------------- # breath if effect_type == conf.type_breath: if nr_colors >= 3 and fx.has("breath_triple"): fx.breath_triple(color1[0], color1[1], color1[2], color2[0], color2[1], color2[2], color3[0], color3[1], color3[2]) elif nr_colors >= 2 and fx.has("breath_dual"): fx.breath_dual(color1[0], color1[1], color1[2], color2[0], color2[1], color2[2]) elif nr_colors >= 1 and fx.has("breath_single"): fx.breath_single(color1[0], color1[1], color1[2]) elif nr_colors >= 0: fx.breath_random() # reactive elif effect_type == conf.type_reactive: if not fx.has("reactive"): self._logger.warning(f"reactive not supported by keyboard {self._keyboard.name}") return if not color1: self._logger.warning(f"No color for reactive set in {color_config[conf.field_name]}") return time = conf.time_r_default if conf.type_option_time in color_config: time = color_config[conf.type_option_time] razer_time = razer_constants.REACTIVE_500MS if time == conf.time_500 \ else razer_constants.REACTIVE_1000MS if time == conf.time_1000 \ else razer_constants.REACTIVE_1500MS if time == conf.time_1500 \ else razer_constants.REACTIVE_2000MS if time == conf.time_2000 \ else None fx.reactive(color1[0], color1[1], color1[2], razer_time) # ripple elif effect_type == conf.type_ripple: if not fx.has("ripple"): self._logger.warning(f"ripple not supported by keyboard {self._keyboard.name}") return if color1: fx.ripple(color1[0], color1[1], color1[2], razer_constants.RIPPLE_REFRESH_RATE) else: fx.ripple_random(razer_constants.RIPPLE_REFRESH_RATE) # spectrum elif effect_type == conf.type_spectrum: if not fx.has("spectrum"): self._logger.warning(f"spectrum not supported by keyboard {self._keyboard.name}") return fx.spectrum() # starlight elif effect_type == conf.type_starlight: time = conf.time_s_default if conf.type_option_time in color_config: time = color_config[conf.type_option_time] razer_time = razer_constants.STARLIGHT_FAST if time == conf.time_fast \ else razer_constants.STARLIGHT_NORMAL if time == conf.time_normal \ else razer_constants.STARLIGHT_SLOW if time == conf.time_slow \ else None if nr_colors >= 2 and fx.has("starlight_dual"): fx.starlight_dual(color1[0], color1[1], color1[2], color2[0], color2[1], color2[2], razer_time) elif nr_colors >= 1 and fx.has("starlight_single"): fx.starlight_single(color1[0], color1[1], color1[2], razer_time) elif nr_colors >= 0: fx.starlight_random(razer_time) # wave right elif effect_type == conf.type_wave_right: fx.wave(razer_constants.WAVE_RIGHT) # wave left elif effect_type == conf.type_wave_left: fx.wave(razer_constants.WAVE_LEFT) else: self._logger.warning(f"type '{effect_type}' is not known") # switch finished def _draw_static_scheme(self, color_config): """ draw a static color scheme """ # One could save the result matrix to be faster on a following draw self._keyboard.fx.advanced.matrix.reset() self._add_to_static_scheme(color_config) self._keyboard.fx.advanced.draw() def _add_to_static_scheme(self, color_config): """ Adds inherited color schemes on display matrix """ # assert scheme type is static if color_config[conf.field_type] != conf.type_static: self._logger.warning(f"trying to inherit a non static color scheme '{color_config[conf.field_name]}") return # handle infinite loop name = color_config[conf.field_name] if name in self._drawing_scheme: # should be detected on reading config self._logger.warning(f"color scheme '{name}' is in an inherit loop with {self._drawing_scheme}") return self._drawing_scheme.add(name) # set colors for field in color_config: # handle "inherit if field == conf.field_inherit: add_scheme = self._config.get_color_scheme_by_name(color_config[conf.field_inherit]) self._add_to_static_scheme(add_scheme) continue # non color fields if field in conf.no_color_in_scheme: continue # handle "all" if field == conf.all_keys: keys = self._key_layout.keys() else: # field is a key array keys = self._config.get_keys(field) if keys: color = self._config.get_color(color_config[field]) self._set_color(color, keys) self._drawing_scheme.remove(name) def _set_color(self, color, keys): for key in keys: if key in self._key_layout: self._keyboard.fx.advanced.matrix[self._key_layout[key]] = color else: self._logger.warning(f"Key '{key}' not found in Layout") def _load_keyboard(self, layout): """ Load Keyboard on startup """ self._key_layout_name = layout if not self.reload_keyboard(): self._logger.critical("No Razer Keyboard found") exit(ERR_NO_KEYBOARD) def _setup_key_hook(self): """ Setup pyxhook to recognize key presses """ def on_key_pressed(event): # Key pressed, update scheme if needed key = event.Key.lower() # config is in lower case if key not in self._current_pressed_keys: self._current_pressed_keys.add(key) if key in self._listen_to_keys: self._update_color_scheme() def on_key_released(event): key = event.Key.lower() if key in self._current_pressed_keys: self._current_pressed_keys.remove(key) else: self._logger.warning( f"releasing key {key} not in pressed keys {self._current_pressed_keys}, resetting pressed keys") self._current_pressed_keys = set() if key in self._listen_to_keys: self._update_color_scheme() # init hook manager hook = HookManager() hook.KeyDown = on_key_pressed hook.KeyUp = on_key_released self._hook = hook def _load_config(self, config_file): """ Load config on startup """ self._config = ConfigParser(config_file, self._logger) if not self._config.is_integral(): self._logger.critical("Error while loading config file") exit(ERR_CONFIG) ############################################### # public methods to change or query the state # ############################################### def start(self): """ Start the shortcut visualisation. This starts a new Thread. Stop this by calling stop() on the object. """ if not self._running: self._logger.warning("Starting Hook") self._setup_key_hook() self._hook.start() self._running = True self._update_color_scheme() def stop(self): """ stops the program by stopping the internal thread waiting for keyboard events """ if self._running: self._logger.warning(f"Stopping hook") self._running = False self._hook.cancel() self._hook = None def reload_config(self, config_file=None) -> bool: """ Loads a new config file and updates color_scheme accordingly return: False if error in config """ if not self._config.read(config_file): self._logger.error(f"Error in config, using old config file") return False self.force_update_color_scheme() return True def reload_keyboard(self, layout=None) -> bool: """ Reloads to the computer connected keyboards, and could set an layout return: true if a razer keyboard was loaded """ device_manager = DeviceManager() for device in device_manager.devices: if device.type == "keyboard": self._keyboard = device break if self._keyboard: if layout: self._key_layout_name = layout device_manager.sync_effects = False self._serial = str(self._keyboard.serial) self.load_layout(self._key_layout_name) else: self._logger.error("no razer keyboard found") return False self._logger.info(f"successfully loaded Keyboard {self._keyboard.name}") return True def load_layout(self, layout_name=None) -> bool: """ Loads the named layout for the current keyboard. If none is named, the layout is detected automatically returns False if the layout cannot be found, the layout is not changed """ # Keysyms have a new map if layout changed if self._hook: self._hook.reset_keysyms() no_layout = False # flow control if not layout_name: no_layout = True if self._keyboard: layout_name = self._keyboard.keyboard_layout self._logger.info(f"Detected Layout {layout_name}") if layout_name not in layouts and no_layout: self._logger.error(f"Layout {layout_name} not found, using default 'en_US'") layout_name = "en_US" # en_US is default and in layout.py if layout_name in layouts: # Load the layout self._key_layout = layouts[layout_name] self._logger.info(f"Loaded keyboard layout {layout_name}") return True def change_mode(self, mode_name: str) -> bool: """ changes the current mode to the given one and updates the scheme return: False if mode does not exist in config """ new_mode = _mode = self._config.get_mode_by_name(mode_name) if new_mode: self._mode = new_mode self._listen_to_keys = self._config.get_important_keys_mode(self._mode) self._update_color_scheme() return True return False def get_mode_name(self) -> str: """ returns the name of the current mode """ if self._mode: return self._mode[conf.field_name] else: # if no mode loaded, return default name return conf.mode_default def change_color_scheme(self, color_scheme_name: str) -> bool: """ changes the displayed color scheme. On the next keypress, the old associated color scheme is shown again. Works also if the thread is not started yet, then the scheme does not change on a keypress return: false if the color scheme cannot be found """ color_config = self._config.get_color_scheme_by_name(color_scheme_name) if not color_config: return False self._draw_color_scheme(color_config) return True def get_color_scheme_name(self) -> str: """ returns the current drawn color scheme """ return self._current_scheme_name def force_update_color_scheme(self): """ deletes internal variables and detects which color scheme to show """ self._current_scheme_name = "" self._update_color_scheme()
[ "logging.getLogger", "i3razer.pyxhook.HookManager", "i3razer.config_parser.ConfigParser", "openrazer.client.DeviceManager" ]
[((11075, 11088), 'i3razer.pyxhook.HookManager', 'HookManager', ([], {}), '()\n', (11086, 11088), False, 'from i3razer.pyxhook import HookManager\n'), ((11310, 11349), 'i3razer.config_parser.ConfigParser', 'ConfigParser', (['config_file', 'self._logger'], {}), '(config_file, self._logger)\n', (11322, 11349), False, 'from i3razer.config_parser import ConfigParser\n'), ((12964, 12979), 'openrazer.client.DeviceManager', 'DeviceManager', ([], {}), '()\n', (12977, 12979), False, 'from openrazer.client import DeviceManager, constants as razer_constants\n'), ((1278, 1297), 'logging.getLogger', 'getLogger', (['__name__'], {}), '(__name__)\n', (1287, 1297), False, 'from logging import getLogger\n')]
#!/usr/bin/env python # coding: utf-8 import logging import asyncio import xumm class StorageExample: def __init__(self): logging.debug('') self.sdk = xumm.XummSdk('API_KEY', 'API_SECRET') self.logger = logging.getLogger(self.__module__) self.logger.setLevel(level=logging.DEBUG) async def run(self): # storge some json value in storage self.logger.info("Set storage value") set_storage_result = self.sdk.storage.set({'name': 'Wietse', 'age': 32, 'male': True}) # True if not set_storage_result: self.logger.error("Unable to set to storage: %s" % e) return # GET the storage content get_storage_result = self.sdk.storage.get() self.logger.info("Current storage value: %s" % get_storage_result.data) # { 'name': 'Wietse', 'age': 32, 'male': True } self.logger.info("Delete storage value") delete_storage_result = self.sdk.storage.delete() if not delete_storage_result: self.logger.error("Unable to delete the storage: %s" % delete_storage_result) get_storage_result_after_delete = self.sdk.storage.get() self.logger.info("Current storage value after delete: %s" % get_storage_result_after_delete.data) # None if __name__ == "__main__": example = StorageExample() loop = asyncio.get_event_loop() loop.run_until_complete(example.run())
[ "xumm.XummSdk", "asyncio.get_event_loop", "logging.getLogger", "logging.debug" ]
[((1402, 1426), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ([], {}), '()\n', (1424, 1426), False, 'import asyncio\n'), ((137, 154), 'logging.debug', 'logging.debug', (['""""""'], {}), "('')\n", (150, 154), False, 'import logging\n'), ((174, 211), 'xumm.XummSdk', 'xumm.XummSdk', (['"""API_KEY"""', '"""API_SECRET"""'], {}), "('API_KEY', 'API_SECRET')\n", (186, 211), False, 'import xumm\n'), ((234, 268), 'logging.getLogger', 'logging.getLogger', (['self.__module__'], {}), '(self.__module__)\n', (251, 268), False, 'import logging\n')]
""" dns_cache.py Copyright 2006 <NAME> This file is part of w3af, http://w3af.org/ . w3af 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 version 2 of the License. w3af 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 w3af; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import socket # pylint: disable=E0401 from darts.lib.utils.lru import SynchronizedLRUDict # pylint: enable=E0401 import w3af.core.controllers.output_manager as om def enable_dns_cache(): """ DNS cache trick This will speed up all the test! Before this dns cache voodoo magic every request to the HTTP server required a DNS query, this is slow on some networks so I added this feature. This method was taken from: # $Id: download.py,v 1.30 2004/05/13 09:55:30 torh Exp $ That is part of : swup-0.0.20040519/ Developed by: # Copyright 2001 - 2003 Trustix AS - <http://www.trustix.com> # Copyright 2003 - 2004 <NAME> - <<EMAIL>> # Copyright 2004 <NAME> for tinysofa - <http://www.tinysofa.org> """ om.out.debug('Enabling _dns_cache()') if not hasattr(socket, 'already_configured'): socket._getaddrinfo = socket.getaddrinfo _dns_cache = SynchronizedLRUDict(200) def _caching_getaddrinfo(*args, **kwargs): query = (args) try: res = _dns_cache[query] #This was too noisy and not so useful #om.out.debug('Cached DNS response for domain: ' + query[0] ) return res except KeyError: res = socket._getaddrinfo(*args, **kwargs) _dns_cache[args] = res msg = 'DNS response from DNS server for domain: %s' om.out.debug(msg % query[0]) return res if not hasattr(socket, 'already_configured'): socket.getaddrinfo = _caching_getaddrinfo socket.already_configured = True
[ "socket._getaddrinfo", "w3af.core.controllers.output_manager.out.debug", "darts.lib.utils.lru.SynchronizedLRUDict" ]
[((1464, 1501), 'w3af.core.controllers.output_manager.out.debug', 'om.out.debug', (['"""Enabling _dns_cache()"""'], {}), "('Enabling _dns_cache()')\n", (1476, 1501), True, 'import w3af.core.controllers.output_manager as om\n'), ((1620, 1644), 'darts.lib.utils.lru.SynchronizedLRUDict', 'SynchronizedLRUDict', (['(200)'], {}), '(200)\n', (1639, 1644), False, 'from darts.lib.utils.lru import SynchronizedLRUDict\n'), ((1956, 1992), 'socket._getaddrinfo', 'socket._getaddrinfo', (['*args'], {}), '(*args, **kwargs)\n', (1975, 1992), False, 'import socket\n'), ((2104, 2132), 'w3af.core.controllers.output_manager.out.debug', 'om.out.debug', (['(msg % query[0])'], {}), '(msg % query[0])\n', (2116, 2132), True, 'import w3af.core.controllers.output_manager as om\n')]
from factory import Faker from .network_node import NetworkNodeFactory from ..constants.network import ACCOUNT_FILE_HASH_LENGTH, BLOCK_IDENTIFIER_LENGTH, MAX_POINT_VALUE, MIN_POINT_VALUE from ..models.network_validator import NetworkValidator class NetworkValidatorFactory(NetworkNodeFactory): daily_confirmation_rate = Faker('pyint', max_value=MAX_POINT_VALUE, min_value=MIN_POINT_VALUE) root_account_file = Faker('url') root_account_file_hash = Faker('text', max_nb_chars=ACCOUNT_FILE_HASH_LENGTH) seed_block_identifier = Faker('text', max_nb_chars=BLOCK_IDENTIFIER_LENGTH) class Meta: model = NetworkValidator abstract = True
[ "factory.Faker" ]
[((327, 395), 'factory.Faker', 'Faker', (['"""pyint"""'], {'max_value': 'MAX_POINT_VALUE', 'min_value': 'MIN_POINT_VALUE'}), "('pyint', max_value=MAX_POINT_VALUE, min_value=MIN_POINT_VALUE)\n", (332, 395), False, 'from factory import Faker\n'), ((420, 432), 'factory.Faker', 'Faker', (['"""url"""'], {}), "('url')\n", (425, 432), False, 'from factory import Faker\n'), ((462, 514), 'factory.Faker', 'Faker', (['"""text"""'], {'max_nb_chars': 'ACCOUNT_FILE_HASH_LENGTH'}), "('text', max_nb_chars=ACCOUNT_FILE_HASH_LENGTH)\n", (467, 514), False, 'from factory import Faker\n'), ((543, 594), 'factory.Faker', 'Faker', (['"""text"""'], {'max_nb_chars': 'BLOCK_IDENTIFIER_LENGTH'}), "('text', max_nb_chars=BLOCK_IDENTIFIER_LENGTH)\n", (548, 594), False, 'from factory import Faker\n')]
from menu.models import Menu from products.models import Product, Category def get_dashboard_data_summary(): cardapios = Menu.objects.all() produtos = Product.objects.all() categorias = Category.objects.all() return {'total_cardapios': len(cardapios), 'total_produtos': len(produtos), 'total_categorias': len(categorias)}
[ "products.models.Category.objects.all", "products.models.Product.objects.all", "menu.models.Menu.objects.all" ]
[((127, 145), 'menu.models.Menu.objects.all', 'Menu.objects.all', ([], {}), '()\n', (143, 145), False, 'from menu.models import Menu\n'), ((161, 182), 'products.models.Product.objects.all', 'Product.objects.all', ([], {}), '()\n', (180, 182), False, 'from products.models import Product, Category\n'), ((200, 222), 'products.models.Category.objects.all', 'Category.objects.all', ([], {}), '()\n', (220, 222), False, 'from products.models import Product, Category\n')]
# -*- coding: utf-8 -*- # flake8: noqa # -------------- Add path of _k2.so into sys.path -------------- import os as _os import sys as _sys _current_module = _sys.modules[__name__] _k2_dir = _os.path.dirname(_current_module.__file__) if not hasattr(_current_module, "__path__"): __path__ = [_k2_dir] elif _k2_dir not in __path__: __path__.append(_k2_dir) _sys.path.append(__path__) # ---------------------- Absolute import ---------------------- from k2._k2host import IntArray2Size from k2._k2host import FbWeightType from k2 import python # ---------------------- Setting __all__ ---------------------- # Add more symbols in this file's scope that with names not start with '_'. __all__.extend( [_s for _s in dir() if not _s.startswith("_") and _s not in __all__] ) # Explicitly avoid importing the wild star, like "from k2 import *". # This give a suggestion for users to follow the conventional usage -- # just import needed symbols: # from k2 import Fsa # from k2.fsa import Fsa __all__.extend(["DO_NOT_WILD_IMPORT"])
[ "os.path.dirname", "sys.path.append" ]
[((194, 236), 'os.path.dirname', '_os.path.dirname', (['_current_module.__file__'], {}), '(_current_module.__file__)\n', (210, 236), True, 'import os as _os\n'), ((367, 393), 'sys.path.append', '_sys.path.append', (['__path__'], {}), '(__path__)\n', (383, 393), True, 'import sys as _sys\n')]