code
stringlengths
13
6.09M
order_type
stringclasses
2 values
original_example
dict
step_ids
listlengths
1
5
SSMDocumentName ='AWS-RunPowerShellScript' InstanceId = ['i-081a7260c79feb260'] Querytimeoutseconds = 3600 OutputS3BucketName = 'hccake' OutputS3KeyPrefix = 'log_' region_name ='us-east-2' aws_access_key_id ='' aws_secret_access_key ='' workingdirectory =["c:\\"] executiontimeout =["3600"]
normal
{ "blob_id": "e55fe845c18ff70ba12bb7c2db28ceded8ae9129", "index": 1580, "step-1": "<mask token>\n", "step-2": "SSMDocumentName = 'AWS-RunPowerShellScript'\nInstanceId = ['i-081a7260c79feb260']\nQuerytimeoutseconds = 3600\nOutputS3BucketName = 'hccake'\nOutputS3KeyPrefix = 'log_'\nregion_name = 'us-east-2'\naws_access_key_id = ''\naws_secret_access_key = ''\nworkingdirectory = ['c:\\\\']\nexecutiontimeout = ['3600']\n", "step-3": "SSMDocumentName ='AWS-RunPowerShellScript'\nInstanceId = ['i-081a7260c79feb260']\nQuerytimeoutseconds = 3600\nOutputS3BucketName = 'hccake'\nOutputS3KeyPrefix = 'log_'\nregion_name ='us-east-2'\naws_access_key_id =''\naws_secret_access_key =''\nworkingdirectory =[\"c:\\\\\"]\nexecutiontimeout =[\"3600\"]", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> class Pacman(object): <|reserved_special_token_0|> def __init__(self, mapa, neural_net): self.mapa = mapa self.pos_x = 11 self.pos_y = 17 self.vel_x = 1 self.vel_y = 0 self.isAlive = True self.Frame = 0 self.score = 0 self.count = 0 self.count2 = 0 self.lastMove = '' self.movesCount = 0 self.neural_network = neural_net def update(self, input_data): self.Frame += 1 self.handle_mov(input_data) self.handle_colision() if self.count > TimeToStarve: self.killPacman() if self.Frame == FPS / MPS: self.Frame = 0 def handle_colision(self): if self.mapa.map[self.pos_y][self.pos_x] == 2: self.mapa.getFruit(self.pos_y, self.pos_x) self.count = 0 self.score += 1 def draw(self, win): pygame.draw.circle(win, pygame.color.Color('yellow'), (self.pos_x * TILE_WIDTH + self.RADIUS, self.pos_y * TILE_HEIGHT + self. RADIUS), self.RADIUS) <|reserved_special_token_0|> def getPos(self): return self.pos_x, self.pos_y def getVel(self): return self.vel_x, self.vel_y <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Pacman(object): <|reserved_special_token_0|> def __init__(self, mapa, neural_net): self.mapa = mapa self.pos_x = 11 self.pos_y = 17 self.vel_x = 1 self.vel_y = 0 self.isAlive = True self.Frame = 0 self.score = 0 self.count = 0 self.count2 = 0 self.lastMove = '' self.movesCount = 0 self.neural_network = neural_net def update(self, input_data): self.Frame += 1 self.handle_mov(input_data) self.handle_colision() if self.count > TimeToStarve: self.killPacman() if self.Frame == FPS / MPS: self.Frame = 0 def handle_colision(self): if self.mapa.map[self.pos_y][self.pos_x] == 2: self.mapa.getFruit(self.pos_y, self.pos_x) self.count = 0 self.score += 1 def draw(self, win): pygame.draw.circle(win, pygame.color.Color('yellow'), (self.pos_x * TILE_WIDTH + self.RADIUS, self.pos_y * TILE_HEIGHT + self. RADIUS), self.RADIUS) <|reserved_special_token_0|> def getPos(self): return self.pos_x, self.pos_y def getVel(self): return self.vel_x, self.vel_y def killPacman(self): self.isAlive = False <|reserved_special_token_1|> <|reserved_special_token_0|> class Pacman(object): RADIUS = int(TILE_WIDTH / 2) def __init__(self, mapa, neural_net): self.mapa = mapa self.pos_x = 11 self.pos_y = 17 self.vel_x = 1 self.vel_y = 0 self.isAlive = True self.Frame = 0 self.score = 0 self.count = 0 self.count2 = 0 self.lastMove = '' self.movesCount = 0 self.neural_network = neural_net def update(self, input_data): self.Frame += 1 self.handle_mov(input_data) self.handle_colision() if self.count > TimeToStarve: self.killPacman() if self.Frame == FPS / MPS: self.Frame = 0 def handle_colision(self): if self.mapa.map[self.pos_y][self.pos_x] == 2: self.mapa.getFruit(self.pos_y, self.pos_x) self.count = 0 self.score += 1 def draw(self, win): pygame.draw.circle(win, pygame.color.Color('yellow'), (self.pos_x * TILE_WIDTH + self.RADIUS, self.pos_y * TILE_HEIGHT + self. RADIUS), self.RADIUS) def handle_mov(self, input_data): movement = self.vel_x, self.vel_y vel_list = {'up': (0, -1), 'down': (0, 1), 'left': (-1, 0), 'right': (1, 0)} movement = vel_list[self.neural_network.nextaction(input_data)] if self.lastMove == movement: self.movesCount += 1 else: self.movesCount = 0 self.lastMove = movement if self.mapa.map[self.pos_y + movement[1]][self.pos_x + movement[0] ] != 1: self.vel_x, self.vel_y = movement if self.Frame == FPS / MPS and self.mapa.map[self.pos_y + self.vel_y][ self.pos_x + self.vel_x] != 1: self.pos_x += self.vel_x self.pos_y += self.vel_y self.count2 += 1 self.count += 1 def getPos(self): return self.pos_x, self.pos_y def getVel(self): return self.vel_x, self.vel_y def killPacman(self): self.isAlive = False <|reserved_special_token_1|> import pygame from config import * from Map import * from NeuralNetwork import * class Pacman(object): RADIUS = int(TILE_WIDTH / 2) def __init__(self, mapa, neural_net): self.mapa = mapa self.pos_x = 11 self.pos_y = 17 self.vel_x = 1 self.vel_y = 0 self.isAlive = True self.Frame = 0 self.score = 0 self.count = 0 self.count2 = 0 self.lastMove = '' self.movesCount = 0 self.neural_network = neural_net def update(self, input_data): self.Frame += 1 self.handle_mov(input_data) self.handle_colision() if self.count > TimeToStarve: self.killPacman() if self.Frame == FPS / MPS: self.Frame = 0 def handle_colision(self): if self.mapa.map[self.pos_y][self.pos_x] == 2: self.mapa.getFruit(self.pos_y, self.pos_x) self.count = 0 self.score += 1 def draw(self, win): pygame.draw.circle(win, pygame.color.Color('yellow'), (self.pos_x * TILE_WIDTH + self.RADIUS, self.pos_y * TILE_HEIGHT + self. RADIUS), self.RADIUS) def handle_mov(self, input_data): movement = self.vel_x, self.vel_y vel_list = {'up': (0, -1), 'down': (0, 1), 'left': (-1, 0), 'right': (1, 0)} movement = vel_list[self.neural_network.nextaction(input_data)] if self.lastMove == movement: self.movesCount += 1 else: self.movesCount = 0 self.lastMove = movement if self.mapa.map[self.pos_y + movement[1]][self.pos_x + movement[0] ] != 1: self.vel_x, self.vel_y = movement if self.Frame == FPS / MPS and self.mapa.map[self.pos_y + self.vel_y][ self.pos_x + self.vel_x] != 1: self.pos_x += self.vel_x self.pos_y += self.vel_y self.count2 += 1 self.count += 1 def getPos(self): return self.pos_x, self.pos_y def getVel(self): return self.vel_x, self.vel_y def killPacman(self): self.isAlive = False <|reserved_special_token_1|> import pygame from config import * from Map import * from NeuralNetwork import * class Pacman(object): RADIUS = int(TILE_WIDTH/2) def __init__(self, mapa, neural_net): self.mapa = mapa self.pos_x = 11 self.pos_y = 17 self.vel_x = 1 self.vel_y = 0 self.isAlive = True self.Frame = 0 self.score = 0 self.count = 0 self.count2 = 0 self.lastMove = "" self.movesCount = 0 self.neural_network = neural_net def update(self, input_data): self.Frame += 1 self.handle_mov(input_data) self.handle_colision() if(self.count > TimeToStarve): self.killPacman() if(self.Frame == FPS/MPS): self.Frame = 0 def handle_colision(self): if(self.mapa.map[self.pos_y][self.pos_x] == 2): self.mapa.getFruit(self.pos_y,self.pos_x) self.count = 0 self.score += 1 def draw(self, win): pygame.draw.circle( win, pygame.color.Color("yellow"), ( self.pos_x * TILE_WIDTH + self.RADIUS, self.pos_y * TILE_HEIGHT + self.RADIUS ), self.RADIUS ) def handle_mov(self, input_data): movement = (self.vel_x, self.vel_y) vel_list = { 'up': (0, -1), 'down': (0, 1), 'left': (-1, 0), 'right': (1, 0) } movement = vel_list[self.neural_network.nextaction(input_data)] if self.lastMove == movement: self.movesCount += 1 else: self.movesCount = 0 self.lastMove = movement if(self.mapa.map[self.pos_y + movement[1]][self.pos_x + movement[0]] != 1): self.vel_x, self.vel_y = movement if(self.Frame == (FPS/MPS) and self.mapa.map[self.pos_y + self.vel_y][self.pos_x + self.vel_x] != 1): self.pos_x += self.vel_x self.pos_y += self.vel_y self.count2 += 1 self.count += 1 def getPos(self): return (self.pos_x, self.pos_y) def getVel(self): return (self.vel_x, self.vel_y) def killPacman(self): self.isAlive = False
flexible
{ "blob_id": "d3b5d87b56421940449fdef48be6da9fa650dd90", "index": 1756, "step-1": "<mask token>\n\n\nclass Pacman(object):\n <mask token>\n\n def __init__(self, mapa, neural_net):\n self.mapa = mapa\n self.pos_x = 11\n self.pos_y = 17\n self.vel_x = 1\n self.vel_y = 0\n self.isAlive = True\n self.Frame = 0\n self.score = 0\n self.count = 0\n self.count2 = 0\n self.lastMove = ''\n self.movesCount = 0\n self.neural_network = neural_net\n\n def update(self, input_data):\n self.Frame += 1\n self.handle_mov(input_data)\n self.handle_colision()\n if self.count > TimeToStarve:\n self.killPacman()\n if self.Frame == FPS / MPS:\n self.Frame = 0\n\n def handle_colision(self):\n if self.mapa.map[self.pos_y][self.pos_x] == 2:\n self.mapa.getFruit(self.pos_y, self.pos_x)\n self.count = 0\n self.score += 1\n\n def draw(self, win):\n pygame.draw.circle(win, pygame.color.Color('yellow'), (self.pos_x *\n TILE_WIDTH + self.RADIUS, self.pos_y * TILE_HEIGHT + self.\n RADIUS), self.RADIUS)\n <mask token>\n\n def getPos(self):\n return self.pos_x, self.pos_y\n\n def getVel(self):\n return self.vel_x, self.vel_y\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Pacman(object):\n <mask token>\n\n def __init__(self, mapa, neural_net):\n self.mapa = mapa\n self.pos_x = 11\n self.pos_y = 17\n self.vel_x = 1\n self.vel_y = 0\n self.isAlive = True\n self.Frame = 0\n self.score = 0\n self.count = 0\n self.count2 = 0\n self.lastMove = ''\n self.movesCount = 0\n self.neural_network = neural_net\n\n def update(self, input_data):\n self.Frame += 1\n self.handle_mov(input_data)\n self.handle_colision()\n if self.count > TimeToStarve:\n self.killPacman()\n if self.Frame == FPS / MPS:\n self.Frame = 0\n\n def handle_colision(self):\n if self.mapa.map[self.pos_y][self.pos_x] == 2:\n self.mapa.getFruit(self.pos_y, self.pos_x)\n self.count = 0\n self.score += 1\n\n def draw(self, win):\n pygame.draw.circle(win, pygame.color.Color('yellow'), (self.pos_x *\n TILE_WIDTH + self.RADIUS, self.pos_y * TILE_HEIGHT + self.\n RADIUS), self.RADIUS)\n <mask token>\n\n def getPos(self):\n return self.pos_x, self.pos_y\n\n def getVel(self):\n return self.vel_x, self.vel_y\n\n def killPacman(self):\n self.isAlive = False\n", "step-3": "<mask token>\n\n\nclass Pacman(object):\n RADIUS = int(TILE_WIDTH / 2)\n\n def __init__(self, mapa, neural_net):\n self.mapa = mapa\n self.pos_x = 11\n self.pos_y = 17\n self.vel_x = 1\n self.vel_y = 0\n self.isAlive = True\n self.Frame = 0\n self.score = 0\n self.count = 0\n self.count2 = 0\n self.lastMove = ''\n self.movesCount = 0\n self.neural_network = neural_net\n\n def update(self, input_data):\n self.Frame += 1\n self.handle_mov(input_data)\n self.handle_colision()\n if self.count > TimeToStarve:\n self.killPacman()\n if self.Frame == FPS / MPS:\n self.Frame = 0\n\n def handle_colision(self):\n if self.mapa.map[self.pos_y][self.pos_x] == 2:\n self.mapa.getFruit(self.pos_y, self.pos_x)\n self.count = 0\n self.score += 1\n\n def draw(self, win):\n pygame.draw.circle(win, pygame.color.Color('yellow'), (self.pos_x *\n TILE_WIDTH + self.RADIUS, self.pos_y * TILE_HEIGHT + self.\n RADIUS), self.RADIUS)\n\n def handle_mov(self, input_data):\n movement = self.vel_x, self.vel_y\n vel_list = {'up': (0, -1), 'down': (0, 1), 'left': (-1, 0), 'right':\n (1, 0)}\n movement = vel_list[self.neural_network.nextaction(input_data)]\n if self.lastMove == movement:\n self.movesCount += 1\n else:\n self.movesCount = 0\n self.lastMove = movement\n if self.mapa.map[self.pos_y + movement[1]][self.pos_x + movement[0]\n ] != 1:\n self.vel_x, self.vel_y = movement\n if self.Frame == FPS / MPS and self.mapa.map[self.pos_y + self.vel_y][\n self.pos_x + self.vel_x] != 1:\n self.pos_x += self.vel_x\n self.pos_y += self.vel_y\n self.count2 += 1\n self.count += 1\n\n def getPos(self):\n return self.pos_x, self.pos_y\n\n def getVel(self):\n return self.vel_x, self.vel_y\n\n def killPacman(self):\n self.isAlive = False\n", "step-4": "import pygame\nfrom config import *\nfrom Map import *\nfrom NeuralNetwork import *\n\n\nclass Pacman(object):\n RADIUS = int(TILE_WIDTH / 2)\n\n def __init__(self, mapa, neural_net):\n self.mapa = mapa\n self.pos_x = 11\n self.pos_y = 17\n self.vel_x = 1\n self.vel_y = 0\n self.isAlive = True\n self.Frame = 0\n self.score = 0\n self.count = 0\n self.count2 = 0\n self.lastMove = ''\n self.movesCount = 0\n self.neural_network = neural_net\n\n def update(self, input_data):\n self.Frame += 1\n self.handle_mov(input_data)\n self.handle_colision()\n if self.count > TimeToStarve:\n self.killPacman()\n if self.Frame == FPS / MPS:\n self.Frame = 0\n\n def handle_colision(self):\n if self.mapa.map[self.pos_y][self.pos_x] == 2:\n self.mapa.getFruit(self.pos_y, self.pos_x)\n self.count = 0\n self.score += 1\n\n def draw(self, win):\n pygame.draw.circle(win, pygame.color.Color('yellow'), (self.pos_x *\n TILE_WIDTH + self.RADIUS, self.pos_y * TILE_HEIGHT + self.\n RADIUS), self.RADIUS)\n\n def handle_mov(self, input_data):\n movement = self.vel_x, self.vel_y\n vel_list = {'up': (0, -1), 'down': (0, 1), 'left': (-1, 0), 'right':\n (1, 0)}\n movement = vel_list[self.neural_network.nextaction(input_data)]\n if self.lastMove == movement:\n self.movesCount += 1\n else:\n self.movesCount = 0\n self.lastMove = movement\n if self.mapa.map[self.pos_y + movement[1]][self.pos_x + movement[0]\n ] != 1:\n self.vel_x, self.vel_y = movement\n if self.Frame == FPS / MPS and self.mapa.map[self.pos_y + self.vel_y][\n self.pos_x + self.vel_x] != 1:\n self.pos_x += self.vel_x\n self.pos_y += self.vel_y\n self.count2 += 1\n self.count += 1\n\n def getPos(self):\n return self.pos_x, self.pos_y\n\n def getVel(self):\n return self.vel_x, self.vel_y\n\n def killPacman(self):\n self.isAlive = False\n", "step-5": "import pygame\nfrom config import *\nfrom Map import *\nfrom NeuralNetwork import *\n\n\nclass Pacman(object):\n RADIUS = int(TILE_WIDTH/2)\n def __init__(self, mapa, neural_net):\n self.mapa = mapa\n self.pos_x = 11\n self.pos_y = 17\n\n self.vel_x = 1\n self.vel_y = 0\n\n self.isAlive = True\n\n self.Frame = 0\n self.score = 0\n\n self.count = 0\n self.count2 = 0\n self.lastMove = \"\"\n self.movesCount = 0\n\n self.neural_network = neural_net\n\n def update(self, input_data):\n self.Frame += 1\n\n self.handle_mov(input_data)\n self.handle_colision()\n\n if(self.count > TimeToStarve):\n self.killPacman()\n \n\n if(self.Frame == FPS/MPS):\n self.Frame = 0\n \n \n def handle_colision(self):\n if(self.mapa.map[self.pos_y][self.pos_x] == 2):\n self.mapa.getFruit(self.pos_y,self.pos_x)\n self.count = 0\n self.score += 1\n\n\n def draw(self, win):\n pygame.draw.circle(\n win,\n pygame.color.Color(\"yellow\"),\n (\n self.pos_x * TILE_WIDTH + self.RADIUS,\n self.pos_y * TILE_HEIGHT + self.RADIUS\n ), self.RADIUS\n )\n\n \n\n def handle_mov(self, input_data):\n movement = (self.vel_x, self.vel_y)\n vel_list = {\n 'up': (0, -1),\n 'down': (0, 1),\n 'left': (-1, 0),\n 'right': (1, 0)\n }\n\n movement = vel_list[self.neural_network.nextaction(input_data)]\n if self.lastMove == movement:\n self.movesCount += 1\n else:\n self.movesCount = 0\n self.lastMove = movement\n\n\n if(self.mapa.map[self.pos_y + movement[1]][self.pos_x + movement[0]] != 1):\n self.vel_x, self.vel_y = movement\n \n if(self.Frame == (FPS/MPS) and self.mapa.map[self.pos_y + self.vel_y][self.pos_x + self.vel_x] != 1):\n self.pos_x += self.vel_x\n self.pos_y += self.vel_y\n self.count2 += 1\n \n self.count += 1\n\n def getPos(self):\n return (self.pos_x, self.pos_y)\n \n def getVel(self):\n return (self.vel_x, self.vel_y)\n \n def killPacman(self):\n self.isAlive = False", "step-ids": [ 7, 8, 10, 11, 12 ] }
[ 7, 8, 10, 11, 12 ]
# %% import os print(os.getcwd()) # %% from TransformerModel.Model import Model from dataset.DatasetLoader import DatasetLoader import pytorch_lightning as pl from pytorch_lightning.callbacks import EarlyStopping import argparse from argparse import ArgumentParser, ArgumentTypeError # %% def run_training(arguments_parser): data = DatasetLoader(arguments_parser) data.setup() arguments_parser.num_training_steps = ( len(data.train_dataloader()) * arguments_parser.max_epochs ) dict_args = vars(arguments_parser) model = Model(**dict_args) arguments_parser.early_stop_callback = EarlyStopping("val_loss") trainer = pl.Trainer.from_argparse_args(arguments_parser) trainer.fit(model, data) # %% if __name__ == "__main__": parser = ArgumentParser() parser.add_argument("--pretrained", type=str, default="bert-base-uncased") parser.add_argument("--nr_frozen_epochs", type=int, default=5) parser.add_argument("--training_portion", type=float, default=0.9) parser.add_argument("--batch_size", type=float, default=32) parser.add_argument("--learning_rate", type=float, default=2e-5) parser.add_argument("--frac", type=float, default=1) parser = pl.Trainer.add_argparse_args(parser) args = parser.parse_args() run_training(args) # %%
normal
{ "blob_id": "328a03acab2a0550bea0795d22110a152db6c503", "index": 806, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef run_training(arguments_parser):\n data = DatasetLoader(arguments_parser)\n data.setup()\n arguments_parser.num_training_steps = len(data.train_dataloader()\n ) * arguments_parser.max_epochs\n dict_args = vars(arguments_parser)\n model = Model(**dict_args)\n arguments_parser.early_stop_callback = EarlyStopping('val_loss')\n trainer = pl.Trainer.from_argparse_args(arguments_parser)\n trainer.fit(model, data)\n\n\n<mask token>\n", "step-3": "<mask token>\nprint(os.getcwd())\n<mask token>\n\n\ndef run_training(arguments_parser):\n data = DatasetLoader(arguments_parser)\n data.setup()\n arguments_parser.num_training_steps = len(data.train_dataloader()\n ) * arguments_parser.max_epochs\n dict_args = vars(arguments_parser)\n model = Model(**dict_args)\n arguments_parser.early_stop_callback = EarlyStopping('val_loss')\n trainer = pl.Trainer.from_argparse_args(arguments_parser)\n trainer.fit(model, data)\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n parser.add_argument('--pretrained', type=str, default='bert-base-uncased')\n parser.add_argument('--nr_frozen_epochs', type=int, default=5)\n parser.add_argument('--training_portion', type=float, default=0.9)\n parser.add_argument('--batch_size', type=float, default=32)\n parser.add_argument('--learning_rate', type=float, default=2e-05)\n parser.add_argument('--frac', type=float, default=1)\n parser = pl.Trainer.add_argparse_args(parser)\n args = parser.parse_args()\n run_training(args)\n", "step-4": "import os\nprint(os.getcwd())\nfrom TransformerModel.Model import Model\nfrom dataset.DatasetLoader import DatasetLoader\nimport pytorch_lightning as pl\nfrom pytorch_lightning.callbacks import EarlyStopping\nimport argparse\nfrom argparse import ArgumentParser, ArgumentTypeError\n\n\ndef run_training(arguments_parser):\n data = DatasetLoader(arguments_parser)\n data.setup()\n arguments_parser.num_training_steps = len(data.train_dataloader()\n ) * arguments_parser.max_epochs\n dict_args = vars(arguments_parser)\n model = Model(**dict_args)\n arguments_parser.early_stop_callback = EarlyStopping('val_loss')\n trainer = pl.Trainer.from_argparse_args(arguments_parser)\n trainer.fit(model, data)\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n parser.add_argument('--pretrained', type=str, default='bert-base-uncased')\n parser.add_argument('--nr_frozen_epochs', type=int, default=5)\n parser.add_argument('--training_portion', type=float, default=0.9)\n parser.add_argument('--batch_size', type=float, default=32)\n parser.add_argument('--learning_rate', type=float, default=2e-05)\n parser.add_argument('--frac', type=float, default=1)\n parser = pl.Trainer.add_argparse_args(parser)\n args = parser.parse_args()\n run_training(args)\n", "step-5": "# %%\nimport os\n\nprint(os.getcwd())\n# %%\nfrom TransformerModel.Model import Model\nfrom dataset.DatasetLoader import DatasetLoader\nimport pytorch_lightning as pl\nfrom pytorch_lightning.callbacks import EarlyStopping\nimport argparse\nfrom argparse import ArgumentParser, ArgumentTypeError\n\n# %%\n\n\ndef run_training(arguments_parser):\n data = DatasetLoader(arguments_parser)\n data.setup()\n\n arguments_parser.num_training_steps = (\n len(data.train_dataloader()) * arguments_parser.max_epochs\n )\n\n dict_args = vars(arguments_parser)\n\n model = Model(**dict_args)\n\n arguments_parser.early_stop_callback = EarlyStopping(\"val_loss\")\n\n trainer = pl.Trainer.from_argparse_args(arguments_parser)\n\n trainer.fit(model, data)\n\n\n# %%\nif __name__ == \"__main__\":\n\n parser = ArgumentParser()\n parser.add_argument(\"--pretrained\", type=str, default=\"bert-base-uncased\")\n parser.add_argument(\"--nr_frozen_epochs\", type=int, default=5)\n parser.add_argument(\"--training_portion\", type=float, default=0.9)\n parser.add_argument(\"--batch_size\", type=float, default=32)\n parser.add_argument(\"--learning_rate\", type=float, default=2e-5)\n parser.add_argument(\"--frac\", type=float, default=1)\n\n parser = pl.Trainer.add_argparse_args(parser)\n args = parser.parse_args()\n run_training(args)\n\n\n# %%\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> class CPU: <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def op_ldi(self, operand_a, operand_b): self.reg[operand_a] = operand_b def op_prn(self, operand_a, operand_b): print('prn:', self.reg[operand_a]) def op_mul(self, operand_a, operand_b): self.alu('MUL', operand_a, operand_b) def op_push(self, operand_a, operand_b): self.sp -= 1 val = self.reg[operand_a] self.ram_write(self.sp, val) def op_pop(self, operand_a, operand_b): self.reg[operand_a] = self.ram_read(self.sp) self.sp += 1 def op_call(self, operand_a, operand_b): ret_addr = self.pc + 2 self.sp -= 1 self.ram_write(self.sp, ret_addr) sub_addr = self.reg[operand_a] self.pc = sub_addr <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def op_jne(self, operand_a, operand_b): if self.fl != 1: self.op_jmp(operand_a, operand_b) else: self.pc += 2 def op_and(self, operand_a, operand_b): self.alu('AND', operand_a, operand_b) def op_or(self, operand_a, operand_b): self.alu('ADD', operand_a, operand_b) def op_xor(self, operand_a, operand_b): self.alu('CMP', operand_a, operand_b) <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def trace(self): """ Handy function to print out the CPU state. You might want to call this from run() if you need help debugging. """ print(f'TRACE: %02X | %02X %02X %02X |' % (self.pc, self.ram_read( self.pc), self.ram_read(self.pc + 1), self.ram_read(self.pc + 2 )), end='') for i in range(8): print(' %02X' % self.reg[i], end='') print() def run(self): """Run the CPU.""" self.trace() while self.running is True: IR = self.ram_read(self.pc) operand_a = self.ram_read(self.pc + 1) operand_b = self.ram_read(self.pc + 2) op_size = IR >> 6 ins_set = IR >> 4 & 1 == 1 if not ins_set: self.pc += op_size + 1 if IR in self.branchtable: self.branchtable[IR](operand_a, operand_b) <|reserved_special_token_1|> <|reserved_special_token_0|> class CPU: <|reserved_special_token_0|> def __init__(self): """Construct a new CPU.""" self.reg = [0] * 8 self.pc = 0 self.ram = [0] * 256 self.running = True self.reg[7] = 244 self.sp = self.reg[7] self.fl = 0 self.branchtable = {} self.branchtable[HLT] = self.op_hlt self.branchtable[LDI] = self.op_ldi self.branchtable[PRN] = self.op_prn self.branchtable[MUL] = self.op_mul self.branchtable[PUSH] = self.op_push self.branchtable[POP] = self.op_pop self.branchtable[CALL] = self.op_call self.branchtable[RET] = self.op_ret self.branchtable[ADD] = self.op_add self.branchtable[CMP] = self.op_cmp self.branchtable[JMP] = self.op_jmp self.branchtable[JEQ] = self.op_jeq self.branchtable[JNE] = self.op_jne self.branchtable[AND] = self.op_and self.branchtable[NOT] = self.op_not self.branchtable[OR] = self.op_or self.branchtable[XOR] = self.op_xor self.branchtable[SHL] = self.op_shl self.branchtable[SHR] = self.op_shr self.branchtable[MOD] = self.op_mod <|reserved_special_token_0|> def ram_write(self, MAR, MDR): self.ram[MAR] = MDR def op_hlt(self, operand_a, operand_b): self.running = False def op_ldi(self, operand_a, operand_b): self.reg[operand_a] = operand_b def op_prn(self, operand_a, operand_b): print('prn:', self.reg[operand_a]) def op_mul(self, operand_a, operand_b): self.alu('MUL', operand_a, operand_b) def op_push(self, operand_a, operand_b): self.sp -= 1 val = self.reg[operand_a] self.ram_write(self.sp, val) def op_pop(self, operand_a, operand_b): self.reg[operand_a] = self.ram_read(self.sp) self.sp += 1 def op_call(self, operand_a, operand_b): ret_addr = self.pc + 2 self.sp -= 1 self.ram_write(self.sp, ret_addr) sub_addr = self.reg[operand_a] self.pc = sub_addr def op_ret(self, operand_a, operand_b): ret_addr = self.ram_read(self.sp) self.sp += 1 self.pc = ret_addr <|reserved_special_token_0|> def op_cmp(self, operand_a, operand_b): self.alu('CMP', operand_a, operand_b) <|reserved_special_token_0|> <|reserved_special_token_0|> def op_jne(self, operand_a, operand_b): if self.fl != 1: self.op_jmp(operand_a, operand_b) else: self.pc += 2 def op_and(self, operand_a, operand_b): self.alu('AND', operand_a, operand_b) def op_or(self, operand_a, operand_b): self.alu('ADD', operand_a, operand_b) def op_xor(self, operand_a, operand_b): self.alu('CMP', operand_a, operand_b) <|reserved_special_token_0|> def op_shl(self, operand_a, operand_b): self.alu('CMP', operand_a, operand_b) def op_shr(self, operand_a, operand_b): self.alu('ADD', operand_a, operand_b) def op_mod(self, operand_a, operand_b): self.alu('CMP', operand_a, operand_b) <|reserved_special_token_0|> def alu(self, op, reg_a, reg_b): """ALU operations.""" if op == 'ADD': self.reg[reg_a] = self.reg[reg_a] + self.reg[reg_b] elif op == 'MUL': self.reg[reg_a] = self.reg[reg_a] * self.reg[reg_b] elif op == 'CMP': if self.reg[reg_a] < self.reg[reg_b]: self.fl = 4 elif self.reg[reg_a] > self.reg[reg_b]: self.fl = 2 elif self.reg[reg_a] == self.reg[reg_b]: self.fl = 1 elif op == 'AND': self.reg[reg_a] = self.reg[reg_a] & self.reg[reg_b] elif op == 'OR': self.reg[reg_a] = self.reg[reg_a] | self.reg[reg_b] elif op == 'XOR': self.reg[reg_a] = self.reg[reg_a] ^ self.reg[reg_b] elif op == 'NOT': self.reg[reg_a] = ~self.reg[reg_a] elif op == 'SHL': self.reg[reg_a] = self.reg[reg_a] << self.reg[reg_b] elif op == 'SHR': self.reg[reg_a] = self.reg[reg_a] >> self.reg[reg_b] elif op == 'MOD': if self.reg[reg_b] == 0: print('ERROR: divide by 0') self.op_hlt() else: remainder = self.reg[reg_a] % self.reg[reg_b] self.reg[reg_a] = remainder else: raise Exception('Unsupported ALU operation') def trace(self): """ Handy function to print out the CPU state. You might want to call this from run() if you need help debugging. """ print(f'TRACE: %02X | %02X %02X %02X |' % (self.pc, self.ram_read( self.pc), self.ram_read(self.pc + 1), self.ram_read(self.pc + 2 )), end='') for i in range(8): print(' %02X' % self.reg[i], end='') print() def run(self): """Run the CPU.""" self.trace() while self.running is True: IR = self.ram_read(self.pc) operand_a = self.ram_read(self.pc + 1) operand_b = self.ram_read(self.pc + 2) op_size = IR >> 6 ins_set = IR >> 4 & 1 == 1 if not ins_set: self.pc += op_size + 1 if IR in self.branchtable: self.branchtable[IR](operand_a, operand_b) <|reserved_special_token_1|> <|reserved_special_token_0|> class CPU: <|reserved_special_token_0|> def __init__(self): """Construct a new CPU.""" self.reg = [0] * 8 self.pc = 0 self.ram = [0] * 256 self.running = True self.reg[7] = 244 self.sp = self.reg[7] self.fl = 0 self.branchtable = {} self.branchtable[HLT] = self.op_hlt self.branchtable[LDI] = self.op_ldi self.branchtable[PRN] = self.op_prn self.branchtable[MUL] = self.op_mul self.branchtable[PUSH] = self.op_push self.branchtable[POP] = self.op_pop self.branchtable[CALL] = self.op_call self.branchtable[RET] = self.op_ret self.branchtable[ADD] = self.op_add self.branchtable[CMP] = self.op_cmp self.branchtable[JMP] = self.op_jmp self.branchtable[JEQ] = self.op_jeq self.branchtable[JNE] = self.op_jne self.branchtable[AND] = self.op_and self.branchtable[NOT] = self.op_not self.branchtable[OR] = self.op_or self.branchtable[XOR] = self.op_xor self.branchtable[SHL] = self.op_shl self.branchtable[SHR] = self.op_shr self.branchtable[MOD] = self.op_mod <|reserved_special_token_0|> def ram_write(self, MAR, MDR): self.ram[MAR] = MDR def op_hlt(self, operand_a, operand_b): self.running = False def op_ldi(self, operand_a, operand_b): self.reg[operand_a] = operand_b def op_prn(self, operand_a, operand_b): print('prn:', self.reg[operand_a]) def op_mul(self, operand_a, operand_b): self.alu('MUL', operand_a, operand_b) def op_push(self, operand_a, operand_b): self.sp -= 1 val = self.reg[operand_a] self.ram_write(self.sp, val) def op_pop(self, operand_a, operand_b): self.reg[operand_a] = self.ram_read(self.sp) self.sp += 1 def op_call(self, operand_a, operand_b): ret_addr = self.pc + 2 self.sp -= 1 self.ram_write(self.sp, ret_addr) sub_addr = self.reg[operand_a] self.pc = sub_addr def op_ret(self, operand_a, operand_b): ret_addr = self.ram_read(self.sp) self.sp += 1 self.pc = ret_addr def op_add(self, operand_a, operand_b): self.alu('ADD', operand_a, operand_b) def op_cmp(self, operand_a, operand_b): self.alu('CMP', operand_a, operand_b) <|reserved_special_token_0|> <|reserved_special_token_0|> def op_jne(self, operand_a, operand_b): if self.fl != 1: self.op_jmp(operand_a, operand_b) else: self.pc += 2 def op_and(self, operand_a, operand_b): self.alu('AND', operand_a, operand_b) def op_or(self, operand_a, operand_b): self.alu('ADD', operand_a, operand_b) def op_xor(self, operand_a, operand_b): self.alu('CMP', operand_a, operand_b) <|reserved_special_token_0|> def op_shl(self, operand_a, operand_b): self.alu('CMP', operand_a, operand_b) def op_shr(self, operand_a, operand_b): self.alu('ADD', operand_a, operand_b) def op_mod(self, operand_a, operand_b): self.alu('CMP', operand_a, operand_b) <|reserved_special_token_0|> def alu(self, op, reg_a, reg_b): """ALU operations.""" if op == 'ADD': self.reg[reg_a] = self.reg[reg_a] + self.reg[reg_b] elif op == 'MUL': self.reg[reg_a] = self.reg[reg_a] * self.reg[reg_b] elif op == 'CMP': if self.reg[reg_a] < self.reg[reg_b]: self.fl = 4 elif self.reg[reg_a] > self.reg[reg_b]: self.fl = 2 elif self.reg[reg_a] == self.reg[reg_b]: self.fl = 1 elif op == 'AND': self.reg[reg_a] = self.reg[reg_a] & self.reg[reg_b] elif op == 'OR': self.reg[reg_a] = self.reg[reg_a] | self.reg[reg_b] elif op == 'XOR': self.reg[reg_a] = self.reg[reg_a] ^ self.reg[reg_b] elif op == 'NOT': self.reg[reg_a] = ~self.reg[reg_a] elif op == 'SHL': self.reg[reg_a] = self.reg[reg_a] << self.reg[reg_b] elif op == 'SHR': self.reg[reg_a] = self.reg[reg_a] >> self.reg[reg_b] elif op == 'MOD': if self.reg[reg_b] == 0: print('ERROR: divide by 0') self.op_hlt() else: remainder = self.reg[reg_a] % self.reg[reg_b] self.reg[reg_a] = remainder else: raise Exception('Unsupported ALU operation') def trace(self): """ Handy function to print out the CPU state. You might want to call this from run() if you need help debugging. """ print(f'TRACE: %02X | %02X %02X %02X |' % (self.pc, self.ram_read( self.pc), self.ram_read(self.pc + 1), self.ram_read(self.pc + 2 )), end='') for i in range(8): print(' %02X' % self.reg[i], end='') print() def run(self): """Run the CPU.""" self.trace() while self.running is True: IR = self.ram_read(self.pc) operand_a = self.ram_read(self.pc + 1) operand_b = self.ram_read(self.pc + 2) op_size = IR >> 6 ins_set = IR >> 4 & 1 == 1 if not ins_set: self.pc += op_size + 1 if IR in self.branchtable: self.branchtable[IR](operand_a, operand_b) <|reserved_special_token_1|> <|reserved_special_token_0|> class CPU: <|reserved_special_token_0|> def __init__(self): """Construct a new CPU.""" self.reg = [0] * 8 self.pc = 0 self.ram = [0] * 256 self.running = True self.reg[7] = 244 self.sp = self.reg[7] self.fl = 0 self.branchtable = {} self.branchtable[HLT] = self.op_hlt self.branchtable[LDI] = self.op_ldi self.branchtable[PRN] = self.op_prn self.branchtable[MUL] = self.op_mul self.branchtable[PUSH] = self.op_push self.branchtable[POP] = self.op_pop self.branchtable[CALL] = self.op_call self.branchtable[RET] = self.op_ret self.branchtable[ADD] = self.op_add self.branchtable[CMP] = self.op_cmp self.branchtable[JMP] = self.op_jmp self.branchtable[JEQ] = self.op_jeq self.branchtable[JNE] = self.op_jne self.branchtable[AND] = self.op_and self.branchtable[NOT] = self.op_not self.branchtable[OR] = self.op_or self.branchtable[XOR] = self.op_xor self.branchtable[SHL] = self.op_shl self.branchtable[SHR] = self.op_shr self.branchtable[MOD] = self.op_mod def ram_read(self, MAR): return self.ram[MAR] def ram_write(self, MAR, MDR): self.ram[MAR] = MDR def op_hlt(self, operand_a, operand_b): self.running = False def op_ldi(self, operand_a, operand_b): self.reg[operand_a] = operand_b def op_prn(self, operand_a, operand_b): print('prn:', self.reg[operand_a]) def op_mul(self, operand_a, operand_b): self.alu('MUL', operand_a, operand_b) def op_push(self, operand_a, operand_b): self.sp -= 1 val = self.reg[operand_a] self.ram_write(self.sp, val) def op_pop(self, operand_a, operand_b): self.reg[operand_a] = self.ram_read(self.sp) self.sp += 1 def op_call(self, operand_a, operand_b): ret_addr = self.pc + 2 self.sp -= 1 self.ram_write(self.sp, ret_addr) sub_addr = self.reg[operand_a] self.pc = sub_addr def op_ret(self, operand_a, operand_b): ret_addr = self.ram_read(self.sp) self.sp += 1 self.pc = ret_addr def op_add(self, operand_a, operand_b): self.alu('ADD', operand_a, operand_b) def op_cmp(self, operand_a, operand_b): self.alu('CMP', operand_a, operand_b) <|reserved_special_token_0|> def op_jeq(self, operand_a, operand_b): if self.fl == 1: self.op_jmp(operand_a, operand_b) else: self.pc += 2 def op_jne(self, operand_a, operand_b): if self.fl != 1: self.op_jmp(operand_a, operand_b) else: self.pc += 2 def op_and(self, operand_a, operand_b): self.alu('AND', operand_a, operand_b) def op_or(self, operand_a, operand_b): self.alu('ADD', operand_a, operand_b) def op_xor(self, operand_a, operand_b): self.alu('CMP', operand_a, operand_b) def op_not(self, operand_a, operand_b): self.alu('ADD', operand_a, operand_b) def op_shl(self, operand_a, operand_b): self.alu('CMP', operand_a, operand_b) def op_shr(self, operand_a, operand_b): self.alu('ADD', operand_a, operand_b) def op_mod(self, operand_a, operand_b): self.alu('CMP', operand_a, operand_b) def load(self, filename): """Load a program into memory.""" address = 0 with open(filename) as file: for line in file: val = line.split('#')[0].strip() if val == '': continue instruction = int(val, 2) self.ram[address] = instruction address += 1 def alu(self, op, reg_a, reg_b): """ALU operations.""" if op == 'ADD': self.reg[reg_a] = self.reg[reg_a] + self.reg[reg_b] elif op == 'MUL': self.reg[reg_a] = self.reg[reg_a] * self.reg[reg_b] elif op == 'CMP': if self.reg[reg_a] < self.reg[reg_b]: self.fl = 4 elif self.reg[reg_a] > self.reg[reg_b]: self.fl = 2 elif self.reg[reg_a] == self.reg[reg_b]: self.fl = 1 elif op == 'AND': self.reg[reg_a] = self.reg[reg_a] & self.reg[reg_b] elif op == 'OR': self.reg[reg_a] = self.reg[reg_a] | self.reg[reg_b] elif op == 'XOR': self.reg[reg_a] = self.reg[reg_a] ^ self.reg[reg_b] elif op == 'NOT': self.reg[reg_a] = ~self.reg[reg_a] elif op == 'SHL': self.reg[reg_a] = self.reg[reg_a] << self.reg[reg_b] elif op == 'SHR': self.reg[reg_a] = self.reg[reg_a] >> self.reg[reg_b] elif op == 'MOD': if self.reg[reg_b] == 0: print('ERROR: divide by 0') self.op_hlt() else: remainder = self.reg[reg_a] % self.reg[reg_b] self.reg[reg_a] = remainder else: raise Exception('Unsupported ALU operation') def trace(self): """ Handy function to print out the CPU state. You might want to call this from run() if you need help debugging. """ print(f'TRACE: %02X | %02X %02X %02X |' % (self.pc, self.ram_read( self.pc), self.ram_read(self.pc + 1), self.ram_read(self.pc + 2 )), end='') for i in range(8): print(' %02X' % self.reg[i], end='') print() def run(self): """Run the CPU.""" self.trace() while self.running is True: IR = self.ram_read(self.pc) operand_a = self.ram_read(self.pc + 1) operand_b = self.ram_read(self.pc + 2) op_size = IR >> 6 ins_set = IR >> 4 & 1 == 1 if not ins_set: self.pc += op_size + 1 if IR in self.branchtable: self.branchtable[IR](operand_a, operand_b) <|reserved_special_token_1|> """CPU functionality.""" import sys HLT = 0b00000001 LDI = 0b10000010 PRN = 0b01000111 MUL = 0b10100010 PUSH = 0b01000101 POP = 0b01000110 CMP = 0b10100111 CALL = 0b01010000 RET = 0b00010001 ADD = 0b10100000 CMP = 0b10100111 JMP = 0b01010100 JEQ = 0b01010101 JNE = 0b01010110 AND = 0b10101000 NOT = 0b01101001 OR = 0b10101010 XOR = 0b10101011 SHL = 0b10101100 SHR = 0b10101101 MOD = 0b10100100 class CPU: """Main CPU class.""" def __init__(self): """Construct a new CPU.""" self.reg = [0] * 8 self.pc = 0 self.ram = [0] * 256 self.running = True self.reg[7] = 0xf4 self.sp = self.reg[7] self.fl = 0b00000000 self.branchtable = {} self.branchtable[HLT] = self.op_hlt self.branchtable[LDI] = self.op_ldi self.branchtable[PRN] = self.op_prn self.branchtable[MUL] = self.op_mul self.branchtable[PUSH] = self.op_push self.branchtable[POP] = self.op_pop self.branchtable[CALL] = self.op_call self.branchtable[RET] = self.op_ret self.branchtable[ADD] = self.op_add self.branchtable[CMP] = self.op_cmp self.branchtable[JMP] = self.op_jmp self.branchtable[JEQ] = self.op_jeq self.branchtable[JNE] = self.op_jne self.branchtable[AND] = self.op_and self.branchtable[NOT] = self.op_not self.branchtable[OR] = self.op_or self.branchtable[XOR] = self.op_xor self.branchtable[SHL] = self.op_shl self.branchtable[SHR] = self.op_shr self.branchtable[MOD] = self.op_mod def ram_read(self, MAR): return self.ram[MAR] def ram_write(self, MAR, MDR): self.ram[MAR] = MDR def op_hlt(self, operand_a, operand_b): self.running = False def op_ldi(self, operand_a, operand_b): self.reg[operand_a] = operand_b # self.pc += 3 def op_prn(self, operand_a, operand_b): print('prn:', self.reg[operand_a]) # self.pc += 2 def op_mul(self, operand_a, operand_b): self.alu('MUL', operand_a, operand_b) # self.pc += 3 def op_push(self, operand_a, operand_b): self.sp -= 1 val = self.reg[operand_a] self.ram_write(self.sp, val) # self.pc += 2 def op_pop(self, operand_a, operand_b): self.reg[operand_a] = self.ram_read(self.sp) # self.pc += 2 self.sp += 1 def op_call(self, operand_a, operand_b): ret_addr = self.pc + 2 self.sp -= 1 self.ram_write(self.sp, ret_addr) # write sp and pc location to ram sub_addr = self.reg[operand_a] self.pc = sub_addr def op_ret(self, operand_a, operand_b): ret_addr = self.ram_read(self.sp) # set ret_addr to location in ram self.sp += 1 self.pc = ret_addr def op_add(self, operand_a, operand_b): self.alu('ADD', operand_a, operand_b) def op_cmp(self, operand_a, operand_b): self.alu('CMP', operand_a, operand_b) def op_jmp(self, operand_a, operand_b): self.pc = self.reg[operand_a] def op_jeq(self, operand_a, operand_b): if self.fl == 0b00000001: self.op_jmp(operand_a, operand_b) else: self.pc += 2 def op_jne(self, operand_a, operand_b): if self.fl != 0b00000001: self.op_jmp(operand_a, operand_b) else: self.pc += 2 def op_and(self, operand_a, operand_b): self.alu('AND', operand_a, operand_b) def op_or(self, operand_a, operand_b): self.alu('ADD', operand_a, operand_b) def op_xor(self, operand_a, operand_b): self.alu('CMP', operand_a, operand_b) def op_not(self, operand_a, operand_b): self.alu('ADD', operand_a, operand_b) def op_shl(self, operand_a, operand_b): self.alu('CMP', operand_a, operand_b) def op_shr(self, operand_a, operand_b): self.alu('ADD', operand_a, operand_b) def op_mod(self, operand_a, operand_b): self.alu('CMP', operand_a, operand_b) def load(self, filename): """Load a program into memory.""" address = 0 with open(filename) as file: for line in file: val = line.split("#")[0].strip() if val == '': continue instruction = int(val, 2) self.ram[address] = instruction address += 1 # For now, we've just hardcoded a program: # program = [ # # From print8.ls8 # 0b10000010, # LDI R0,8 # 0b00000000, # 0b00001000, # 0b01000111, # PRN R0 # 0b00000000, # 0b00000001, # HLT # ] # for instruction in program: # self.ram[address] = instruction # address += 1 def alu(self, op, reg_a, reg_b): """ALU operations.""" if op == 'ADD': self.reg[reg_a] = self.reg[reg_a] + self.reg[reg_b] elif op == 'MUL': self.reg[reg_a] = self.reg[reg_a] * self.reg[reg_b] elif op == 'CMP': if self.reg[reg_a] < self.reg[reg_b]: self.fl = 0b00000100 elif self.reg[reg_a] > self.reg[reg_b]: self.fl = 0b00000010 elif self.reg[reg_a] == self.reg[reg_b]: self.fl = 0b00000001 elif op == 'AND': self.reg[reg_a] = self.reg[reg_a] & self.reg[reg_b] elif op == 'OR': self.reg[reg_a] = self.reg[reg_a] | self.reg[reg_b] elif op == 'XOR': self.reg[reg_a] = self.reg[reg_a] ^ self.reg[reg_b] elif op == 'NOT': self.reg[reg_a] = ~self.reg[reg_a] elif op == 'SHL': self.reg[reg_a] = self.reg[reg_a] << self.reg[reg_b] elif op == 'SHR': self.reg[reg_a] = self.reg[reg_a] >> self.reg[reg_b] elif op == 'MOD': if self.reg[reg_b] == 0: print('ERROR: divide by 0') self.op_hlt() else: remainder = self.reg[reg_a] % self.reg[reg_b] self.reg[reg_a] = remainder else: raise Exception("Unsupported ALU operation") def trace(self): """ Handy function to print out the CPU state. You might want to call this from run() if you need help debugging. """ print(f"TRACE: %02X | %02X %02X %02X |" % ( self.pc, # self.fl, # self.ie, self.ram_read(self.pc), self.ram_read(self.pc + 1), self.ram_read(self.pc + 2) ), end='') for i in range(8): print(" %02X" % self.reg[i], end='') print() def run(self): """Run the CPU.""" self.trace() while self.running is True: IR = self.ram_read(self.pc) operand_a = self.ram_read(self.pc + 1) operand_b = self.ram_read(self.pc + 2) # This increments the pc position automatically op_size = IR >> 6 ins_set = ((IR >> 4) & 0b1) == 1 if not ins_set: self.pc += op_size + 1 if IR in self.branchtable: self.branchtable[IR](operand_a, operand_b) # SAVE WHERE WE'RE COMING FROM TO THE STACK AND SET PC TO WHERE WE'RE GOING
flexible
{ "blob_id": "58d144b2c6c307719cef0b5097945c8206135ccf", "index": 6048, "step-1": "<mask token>\n\n\nclass CPU:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def op_ldi(self, operand_a, operand_b):\n self.reg[operand_a] = operand_b\n\n def op_prn(self, operand_a, operand_b):\n print('prn:', self.reg[operand_a])\n\n def op_mul(self, operand_a, operand_b):\n self.alu('MUL', operand_a, operand_b)\n\n def op_push(self, operand_a, operand_b):\n self.sp -= 1\n val = self.reg[operand_a]\n self.ram_write(self.sp, val)\n\n def op_pop(self, operand_a, operand_b):\n self.reg[operand_a] = self.ram_read(self.sp)\n self.sp += 1\n\n def op_call(self, operand_a, operand_b):\n ret_addr = self.pc + 2\n self.sp -= 1\n self.ram_write(self.sp, ret_addr)\n sub_addr = self.reg[operand_a]\n self.pc = sub_addr\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def op_jne(self, operand_a, operand_b):\n if self.fl != 1:\n self.op_jmp(operand_a, operand_b)\n else:\n self.pc += 2\n\n def op_and(self, operand_a, operand_b):\n self.alu('AND', operand_a, operand_b)\n\n def op_or(self, operand_a, operand_b):\n self.alu('ADD', operand_a, operand_b)\n\n def op_xor(self, operand_a, operand_b):\n self.alu('CMP', operand_a, operand_b)\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def trace(self):\n \"\"\"\n Handy function to print out the CPU state. You might want to call this\n from run() if you need help debugging.\n \"\"\"\n print(f'TRACE: %02X | %02X %02X %02X |' % (self.pc, self.ram_read(\n self.pc), self.ram_read(self.pc + 1), self.ram_read(self.pc + 2\n )), end='')\n for i in range(8):\n print(' %02X' % self.reg[i], end='')\n print()\n\n def run(self):\n \"\"\"Run the CPU.\"\"\"\n self.trace()\n while self.running is True:\n IR = self.ram_read(self.pc)\n operand_a = self.ram_read(self.pc + 1)\n operand_b = self.ram_read(self.pc + 2)\n op_size = IR >> 6\n ins_set = IR >> 4 & 1 == 1\n if not ins_set:\n self.pc += op_size + 1\n if IR in self.branchtable:\n self.branchtable[IR](operand_a, operand_b)\n", "step-2": "<mask token>\n\n\nclass CPU:\n <mask token>\n\n def __init__(self):\n \"\"\"Construct a new CPU.\"\"\"\n self.reg = [0] * 8\n self.pc = 0\n self.ram = [0] * 256\n self.running = True\n self.reg[7] = 244\n self.sp = self.reg[7]\n self.fl = 0\n self.branchtable = {}\n self.branchtable[HLT] = self.op_hlt\n self.branchtable[LDI] = self.op_ldi\n self.branchtable[PRN] = self.op_prn\n self.branchtable[MUL] = self.op_mul\n self.branchtable[PUSH] = self.op_push\n self.branchtable[POP] = self.op_pop\n self.branchtable[CALL] = self.op_call\n self.branchtable[RET] = self.op_ret\n self.branchtable[ADD] = self.op_add\n self.branchtable[CMP] = self.op_cmp\n self.branchtable[JMP] = self.op_jmp\n self.branchtable[JEQ] = self.op_jeq\n self.branchtable[JNE] = self.op_jne\n self.branchtable[AND] = self.op_and\n self.branchtable[NOT] = self.op_not\n self.branchtable[OR] = self.op_or\n self.branchtable[XOR] = self.op_xor\n self.branchtable[SHL] = self.op_shl\n self.branchtable[SHR] = self.op_shr\n self.branchtable[MOD] = self.op_mod\n <mask token>\n\n def ram_write(self, MAR, MDR):\n self.ram[MAR] = MDR\n\n def op_hlt(self, operand_a, operand_b):\n self.running = False\n\n def op_ldi(self, operand_a, operand_b):\n self.reg[operand_a] = operand_b\n\n def op_prn(self, operand_a, operand_b):\n print('prn:', self.reg[operand_a])\n\n def op_mul(self, operand_a, operand_b):\n self.alu('MUL', operand_a, operand_b)\n\n def op_push(self, operand_a, operand_b):\n self.sp -= 1\n val = self.reg[operand_a]\n self.ram_write(self.sp, val)\n\n def op_pop(self, operand_a, operand_b):\n self.reg[operand_a] = self.ram_read(self.sp)\n self.sp += 1\n\n def op_call(self, operand_a, operand_b):\n ret_addr = self.pc + 2\n self.sp -= 1\n self.ram_write(self.sp, ret_addr)\n sub_addr = self.reg[operand_a]\n self.pc = sub_addr\n\n def op_ret(self, operand_a, operand_b):\n ret_addr = self.ram_read(self.sp)\n self.sp += 1\n self.pc = ret_addr\n <mask token>\n\n def op_cmp(self, operand_a, operand_b):\n self.alu('CMP', operand_a, operand_b)\n <mask token>\n <mask token>\n\n def op_jne(self, operand_a, operand_b):\n if self.fl != 1:\n self.op_jmp(operand_a, operand_b)\n else:\n self.pc += 2\n\n def op_and(self, operand_a, operand_b):\n self.alu('AND', operand_a, operand_b)\n\n def op_or(self, operand_a, operand_b):\n self.alu('ADD', operand_a, operand_b)\n\n def op_xor(self, operand_a, operand_b):\n self.alu('CMP', operand_a, operand_b)\n <mask token>\n\n def op_shl(self, operand_a, operand_b):\n self.alu('CMP', operand_a, operand_b)\n\n def op_shr(self, operand_a, operand_b):\n self.alu('ADD', operand_a, operand_b)\n\n def op_mod(self, operand_a, operand_b):\n self.alu('CMP', operand_a, operand_b)\n <mask token>\n\n def alu(self, op, reg_a, reg_b):\n \"\"\"ALU operations.\"\"\"\n if op == 'ADD':\n self.reg[reg_a] = self.reg[reg_a] + self.reg[reg_b]\n elif op == 'MUL':\n self.reg[reg_a] = self.reg[reg_a] * self.reg[reg_b]\n elif op == 'CMP':\n if self.reg[reg_a] < self.reg[reg_b]:\n self.fl = 4\n elif self.reg[reg_a] > self.reg[reg_b]:\n self.fl = 2\n elif self.reg[reg_a] == self.reg[reg_b]:\n self.fl = 1\n elif op == 'AND':\n self.reg[reg_a] = self.reg[reg_a] & self.reg[reg_b]\n elif op == 'OR':\n self.reg[reg_a] = self.reg[reg_a] | self.reg[reg_b]\n elif op == 'XOR':\n self.reg[reg_a] = self.reg[reg_a] ^ self.reg[reg_b]\n elif op == 'NOT':\n self.reg[reg_a] = ~self.reg[reg_a]\n elif op == 'SHL':\n self.reg[reg_a] = self.reg[reg_a] << self.reg[reg_b]\n elif op == 'SHR':\n self.reg[reg_a] = self.reg[reg_a] >> self.reg[reg_b]\n elif op == 'MOD':\n if self.reg[reg_b] == 0:\n print('ERROR: divide by 0')\n self.op_hlt()\n else:\n remainder = self.reg[reg_a] % self.reg[reg_b]\n self.reg[reg_a] = remainder\n else:\n raise Exception('Unsupported ALU operation')\n\n def trace(self):\n \"\"\"\n Handy function to print out the CPU state. You might want to call this\n from run() if you need help debugging.\n \"\"\"\n print(f'TRACE: %02X | %02X %02X %02X |' % (self.pc, self.ram_read(\n self.pc), self.ram_read(self.pc + 1), self.ram_read(self.pc + 2\n )), end='')\n for i in range(8):\n print(' %02X' % self.reg[i], end='')\n print()\n\n def run(self):\n \"\"\"Run the CPU.\"\"\"\n self.trace()\n while self.running is True:\n IR = self.ram_read(self.pc)\n operand_a = self.ram_read(self.pc + 1)\n operand_b = self.ram_read(self.pc + 2)\n op_size = IR >> 6\n ins_set = IR >> 4 & 1 == 1\n if not ins_set:\n self.pc += op_size + 1\n if IR in self.branchtable:\n self.branchtable[IR](operand_a, operand_b)\n", "step-3": "<mask token>\n\n\nclass CPU:\n <mask token>\n\n def __init__(self):\n \"\"\"Construct a new CPU.\"\"\"\n self.reg = [0] * 8\n self.pc = 0\n self.ram = [0] * 256\n self.running = True\n self.reg[7] = 244\n self.sp = self.reg[7]\n self.fl = 0\n self.branchtable = {}\n self.branchtable[HLT] = self.op_hlt\n self.branchtable[LDI] = self.op_ldi\n self.branchtable[PRN] = self.op_prn\n self.branchtable[MUL] = self.op_mul\n self.branchtable[PUSH] = self.op_push\n self.branchtable[POP] = self.op_pop\n self.branchtable[CALL] = self.op_call\n self.branchtable[RET] = self.op_ret\n self.branchtable[ADD] = self.op_add\n self.branchtable[CMP] = self.op_cmp\n self.branchtable[JMP] = self.op_jmp\n self.branchtable[JEQ] = self.op_jeq\n self.branchtable[JNE] = self.op_jne\n self.branchtable[AND] = self.op_and\n self.branchtable[NOT] = self.op_not\n self.branchtable[OR] = self.op_or\n self.branchtable[XOR] = self.op_xor\n self.branchtable[SHL] = self.op_shl\n self.branchtable[SHR] = self.op_shr\n self.branchtable[MOD] = self.op_mod\n <mask token>\n\n def ram_write(self, MAR, MDR):\n self.ram[MAR] = MDR\n\n def op_hlt(self, operand_a, operand_b):\n self.running = False\n\n def op_ldi(self, operand_a, operand_b):\n self.reg[operand_a] = operand_b\n\n def op_prn(self, operand_a, operand_b):\n print('prn:', self.reg[operand_a])\n\n def op_mul(self, operand_a, operand_b):\n self.alu('MUL', operand_a, operand_b)\n\n def op_push(self, operand_a, operand_b):\n self.sp -= 1\n val = self.reg[operand_a]\n self.ram_write(self.sp, val)\n\n def op_pop(self, operand_a, operand_b):\n self.reg[operand_a] = self.ram_read(self.sp)\n self.sp += 1\n\n def op_call(self, operand_a, operand_b):\n ret_addr = self.pc + 2\n self.sp -= 1\n self.ram_write(self.sp, ret_addr)\n sub_addr = self.reg[operand_a]\n self.pc = sub_addr\n\n def op_ret(self, operand_a, operand_b):\n ret_addr = self.ram_read(self.sp)\n self.sp += 1\n self.pc = ret_addr\n\n def op_add(self, operand_a, operand_b):\n self.alu('ADD', operand_a, operand_b)\n\n def op_cmp(self, operand_a, operand_b):\n self.alu('CMP', operand_a, operand_b)\n <mask token>\n <mask token>\n\n def op_jne(self, operand_a, operand_b):\n if self.fl != 1:\n self.op_jmp(operand_a, operand_b)\n else:\n self.pc += 2\n\n def op_and(self, operand_a, operand_b):\n self.alu('AND', operand_a, operand_b)\n\n def op_or(self, operand_a, operand_b):\n self.alu('ADD', operand_a, operand_b)\n\n def op_xor(self, operand_a, operand_b):\n self.alu('CMP', operand_a, operand_b)\n <mask token>\n\n def op_shl(self, operand_a, operand_b):\n self.alu('CMP', operand_a, operand_b)\n\n def op_shr(self, operand_a, operand_b):\n self.alu('ADD', operand_a, operand_b)\n\n def op_mod(self, operand_a, operand_b):\n self.alu('CMP', operand_a, operand_b)\n <mask token>\n\n def alu(self, op, reg_a, reg_b):\n \"\"\"ALU operations.\"\"\"\n if op == 'ADD':\n self.reg[reg_a] = self.reg[reg_a] + self.reg[reg_b]\n elif op == 'MUL':\n self.reg[reg_a] = self.reg[reg_a] * self.reg[reg_b]\n elif op == 'CMP':\n if self.reg[reg_a] < self.reg[reg_b]:\n self.fl = 4\n elif self.reg[reg_a] > self.reg[reg_b]:\n self.fl = 2\n elif self.reg[reg_a] == self.reg[reg_b]:\n self.fl = 1\n elif op == 'AND':\n self.reg[reg_a] = self.reg[reg_a] & self.reg[reg_b]\n elif op == 'OR':\n self.reg[reg_a] = self.reg[reg_a] | self.reg[reg_b]\n elif op == 'XOR':\n self.reg[reg_a] = self.reg[reg_a] ^ self.reg[reg_b]\n elif op == 'NOT':\n self.reg[reg_a] = ~self.reg[reg_a]\n elif op == 'SHL':\n self.reg[reg_a] = self.reg[reg_a] << self.reg[reg_b]\n elif op == 'SHR':\n self.reg[reg_a] = self.reg[reg_a] >> self.reg[reg_b]\n elif op == 'MOD':\n if self.reg[reg_b] == 0:\n print('ERROR: divide by 0')\n self.op_hlt()\n else:\n remainder = self.reg[reg_a] % self.reg[reg_b]\n self.reg[reg_a] = remainder\n else:\n raise Exception('Unsupported ALU operation')\n\n def trace(self):\n \"\"\"\n Handy function to print out the CPU state. You might want to call this\n from run() if you need help debugging.\n \"\"\"\n print(f'TRACE: %02X | %02X %02X %02X |' % (self.pc, self.ram_read(\n self.pc), self.ram_read(self.pc + 1), self.ram_read(self.pc + 2\n )), end='')\n for i in range(8):\n print(' %02X' % self.reg[i], end='')\n print()\n\n def run(self):\n \"\"\"Run the CPU.\"\"\"\n self.trace()\n while self.running is True:\n IR = self.ram_read(self.pc)\n operand_a = self.ram_read(self.pc + 1)\n operand_b = self.ram_read(self.pc + 2)\n op_size = IR >> 6\n ins_set = IR >> 4 & 1 == 1\n if not ins_set:\n self.pc += op_size + 1\n if IR in self.branchtable:\n self.branchtable[IR](operand_a, operand_b)\n", "step-4": "<mask token>\n\n\nclass CPU:\n <mask token>\n\n def __init__(self):\n \"\"\"Construct a new CPU.\"\"\"\n self.reg = [0] * 8\n self.pc = 0\n self.ram = [0] * 256\n self.running = True\n self.reg[7] = 244\n self.sp = self.reg[7]\n self.fl = 0\n self.branchtable = {}\n self.branchtable[HLT] = self.op_hlt\n self.branchtable[LDI] = self.op_ldi\n self.branchtable[PRN] = self.op_prn\n self.branchtable[MUL] = self.op_mul\n self.branchtable[PUSH] = self.op_push\n self.branchtable[POP] = self.op_pop\n self.branchtable[CALL] = self.op_call\n self.branchtable[RET] = self.op_ret\n self.branchtable[ADD] = self.op_add\n self.branchtable[CMP] = self.op_cmp\n self.branchtable[JMP] = self.op_jmp\n self.branchtable[JEQ] = self.op_jeq\n self.branchtable[JNE] = self.op_jne\n self.branchtable[AND] = self.op_and\n self.branchtable[NOT] = self.op_not\n self.branchtable[OR] = self.op_or\n self.branchtable[XOR] = self.op_xor\n self.branchtable[SHL] = self.op_shl\n self.branchtable[SHR] = self.op_shr\n self.branchtable[MOD] = self.op_mod\n\n def ram_read(self, MAR):\n return self.ram[MAR]\n\n def ram_write(self, MAR, MDR):\n self.ram[MAR] = MDR\n\n def op_hlt(self, operand_a, operand_b):\n self.running = False\n\n def op_ldi(self, operand_a, operand_b):\n self.reg[operand_a] = operand_b\n\n def op_prn(self, operand_a, operand_b):\n print('prn:', self.reg[operand_a])\n\n def op_mul(self, operand_a, operand_b):\n self.alu('MUL', operand_a, operand_b)\n\n def op_push(self, operand_a, operand_b):\n self.sp -= 1\n val = self.reg[operand_a]\n self.ram_write(self.sp, val)\n\n def op_pop(self, operand_a, operand_b):\n self.reg[operand_a] = self.ram_read(self.sp)\n self.sp += 1\n\n def op_call(self, operand_a, operand_b):\n ret_addr = self.pc + 2\n self.sp -= 1\n self.ram_write(self.sp, ret_addr)\n sub_addr = self.reg[operand_a]\n self.pc = sub_addr\n\n def op_ret(self, operand_a, operand_b):\n ret_addr = self.ram_read(self.sp)\n self.sp += 1\n self.pc = ret_addr\n\n def op_add(self, operand_a, operand_b):\n self.alu('ADD', operand_a, operand_b)\n\n def op_cmp(self, operand_a, operand_b):\n self.alu('CMP', operand_a, operand_b)\n <mask token>\n\n def op_jeq(self, operand_a, operand_b):\n if self.fl == 1:\n self.op_jmp(operand_a, operand_b)\n else:\n self.pc += 2\n\n def op_jne(self, operand_a, operand_b):\n if self.fl != 1:\n self.op_jmp(operand_a, operand_b)\n else:\n self.pc += 2\n\n def op_and(self, operand_a, operand_b):\n self.alu('AND', operand_a, operand_b)\n\n def op_or(self, operand_a, operand_b):\n self.alu('ADD', operand_a, operand_b)\n\n def op_xor(self, operand_a, operand_b):\n self.alu('CMP', operand_a, operand_b)\n\n def op_not(self, operand_a, operand_b):\n self.alu('ADD', operand_a, operand_b)\n\n def op_shl(self, operand_a, operand_b):\n self.alu('CMP', operand_a, operand_b)\n\n def op_shr(self, operand_a, operand_b):\n self.alu('ADD', operand_a, operand_b)\n\n def op_mod(self, operand_a, operand_b):\n self.alu('CMP', operand_a, operand_b)\n\n def load(self, filename):\n \"\"\"Load a program into memory.\"\"\"\n address = 0\n with open(filename) as file:\n for line in file:\n val = line.split('#')[0].strip()\n if val == '':\n continue\n instruction = int(val, 2)\n self.ram[address] = instruction\n address += 1\n\n def alu(self, op, reg_a, reg_b):\n \"\"\"ALU operations.\"\"\"\n if op == 'ADD':\n self.reg[reg_a] = self.reg[reg_a] + self.reg[reg_b]\n elif op == 'MUL':\n self.reg[reg_a] = self.reg[reg_a] * self.reg[reg_b]\n elif op == 'CMP':\n if self.reg[reg_a] < self.reg[reg_b]:\n self.fl = 4\n elif self.reg[reg_a] > self.reg[reg_b]:\n self.fl = 2\n elif self.reg[reg_a] == self.reg[reg_b]:\n self.fl = 1\n elif op == 'AND':\n self.reg[reg_a] = self.reg[reg_a] & self.reg[reg_b]\n elif op == 'OR':\n self.reg[reg_a] = self.reg[reg_a] | self.reg[reg_b]\n elif op == 'XOR':\n self.reg[reg_a] = self.reg[reg_a] ^ self.reg[reg_b]\n elif op == 'NOT':\n self.reg[reg_a] = ~self.reg[reg_a]\n elif op == 'SHL':\n self.reg[reg_a] = self.reg[reg_a] << self.reg[reg_b]\n elif op == 'SHR':\n self.reg[reg_a] = self.reg[reg_a] >> self.reg[reg_b]\n elif op == 'MOD':\n if self.reg[reg_b] == 0:\n print('ERROR: divide by 0')\n self.op_hlt()\n else:\n remainder = self.reg[reg_a] % self.reg[reg_b]\n self.reg[reg_a] = remainder\n else:\n raise Exception('Unsupported ALU operation')\n\n def trace(self):\n \"\"\"\n Handy function to print out the CPU state. You might want to call this\n from run() if you need help debugging.\n \"\"\"\n print(f'TRACE: %02X | %02X %02X %02X |' % (self.pc, self.ram_read(\n self.pc), self.ram_read(self.pc + 1), self.ram_read(self.pc + 2\n )), end='')\n for i in range(8):\n print(' %02X' % self.reg[i], end='')\n print()\n\n def run(self):\n \"\"\"Run the CPU.\"\"\"\n self.trace()\n while self.running is True:\n IR = self.ram_read(self.pc)\n operand_a = self.ram_read(self.pc + 1)\n operand_b = self.ram_read(self.pc + 2)\n op_size = IR >> 6\n ins_set = IR >> 4 & 1 == 1\n if not ins_set:\n self.pc += op_size + 1\n if IR in self.branchtable:\n self.branchtable[IR](operand_a, operand_b)\n", "step-5": "\"\"\"CPU functionality.\"\"\"\n\nimport sys\nHLT = 0b00000001\nLDI = 0b10000010\nPRN = 0b01000111\nMUL = 0b10100010\nPUSH = 0b01000101\nPOP = 0b01000110\nCMP = 0b10100111\nCALL = 0b01010000\nRET = 0b00010001\nADD = 0b10100000\nCMP = 0b10100111\nJMP = 0b01010100\nJEQ = 0b01010101\nJNE = 0b01010110\nAND = 0b10101000\nNOT = 0b01101001\nOR = 0b10101010\nXOR = 0b10101011\nSHL = 0b10101100\nSHR = 0b10101101\nMOD = 0b10100100\n\n\nclass CPU:\n \"\"\"Main CPU class.\"\"\"\n\n def __init__(self):\n \"\"\"Construct a new CPU.\"\"\"\n self.reg = [0] * 8\n self.pc = 0\n self.ram = [0] * 256\n self.running = True\n self.reg[7] = 0xf4\n self.sp = self.reg[7]\n self.fl = 0b00000000\n self.branchtable = {}\n self.branchtable[HLT] = self.op_hlt\n self.branchtable[LDI] = self.op_ldi\n self.branchtable[PRN] = self.op_prn\n self.branchtable[MUL] = self.op_mul\n self.branchtable[PUSH] = self.op_push\n self.branchtable[POP] = self.op_pop\n self.branchtable[CALL] = self.op_call\n self.branchtable[RET] = self.op_ret\n self.branchtable[ADD] = self.op_add\n self.branchtable[CMP] = self.op_cmp\n self.branchtable[JMP] = self.op_jmp\n self.branchtable[JEQ] = self.op_jeq\n self.branchtable[JNE] = self.op_jne\n self.branchtable[AND] = self.op_and\n self.branchtable[NOT] = self.op_not\n self.branchtable[OR] = self.op_or\n self.branchtable[XOR] = self.op_xor\n self.branchtable[SHL] = self.op_shl\n self.branchtable[SHR] = self.op_shr\n self.branchtable[MOD] = self.op_mod\n\n def ram_read(self, MAR):\n return self.ram[MAR]\n\n def ram_write(self, MAR, MDR):\n self.ram[MAR] = MDR\n\n def op_hlt(self, operand_a, operand_b):\n self.running = False\n\n def op_ldi(self, operand_a, operand_b):\n self.reg[operand_a] = operand_b\n # self.pc += 3\n\n def op_prn(self, operand_a, operand_b):\n print('prn:', self.reg[operand_a])\n # self.pc += 2\n\n def op_mul(self, operand_a, operand_b):\n self.alu('MUL', operand_a, operand_b)\n # self.pc += 3\n\n def op_push(self, operand_a, operand_b):\n self.sp -= 1\n val = self.reg[operand_a]\n self.ram_write(self.sp, val)\n # self.pc += 2\n\n def op_pop(self, operand_a, operand_b):\n self.reg[operand_a] = self.ram_read(self.sp)\n # self.pc += 2\n self.sp += 1\n\n def op_call(self, operand_a, operand_b):\n ret_addr = self.pc + 2\n self.sp -= 1\n self.ram_write(self.sp, ret_addr) # write sp and pc location to ram\n sub_addr = self.reg[operand_a]\n self.pc = sub_addr\n\n def op_ret(self, operand_a, operand_b):\n ret_addr = self.ram_read(self.sp) # set ret_addr to location in ram\n self.sp += 1\n self.pc = ret_addr\n\n def op_add(self, operand_a, operand_b):\n self.alu('ADD', operand_a, operand_b)\n\n def op_cmp(self, operand_a, operand_b):\n self.alu('CMP', operand_a, operand_b)\n\n def op_jmp(self, operand_a, operand_b):\n self.pc = self.reg[operand_a]\n\n def op_jeq(self, operand_a, operand_b):\n if self.fl == 0b00000001:\n self.op_jmp(operand_a, operand_b)\n else:\n self.pc += 2\n\n def op_jne(self, operand_a, operand_b):\n if self.fl != 0b00000001:\n self.op_jmp(operand_a, operand_b)\n else:\n self.pc += 2\n\n def op_and(self, operand_a, operand_b):\n self.alu('AND', operand_a, operand_b)\n\n def op_or(self, operand_a, operand_b):\n self.alu('ADD', operand_a, operand_b)\n\n def op_xor(self, operand_a, operand_b):\n self.alu('CMP', operand_a, operand_b)\n\n def op_not(self, operand_a, operand_b):\n self.alu('ADD', operand_a, operand_b)\n\n def op_shl(self, operand_a, operand_b):\n self.alu('CMP', operand_a, operand_b)\n\n def op_shr(self, operand_a, operand_b):\n self.alu('ADD', operand_a, operand_b)\n\n def op_mod(self, operand_a, operand_b):\n self.alu('CMP', operand_a, operand_b)\n\n def load(self, filename):\n \"\"\"Load a program into memory.\"\"\"\n\n address = 0\n\n with open(filename) as file:\n for line in file:\n val = line.split(\"#\")[0].strip()\n if val == '':\n continue\n instruction = int(val, 2)\n self.ram[address] = instruction\n address += 1\n\n # For now, we've just hardcoded a program:\n # program = [\n # # From print8.ls8\n # 0b10000010, # LDI R0,8\n # 0b00000000,\n # 0b00001000,\n # 0b01000111, # PRN R0\n # 0b00000000,\n # 0b00000001, # HLT\n # ]\n # for instruction in program:\n # self.ram[address] = instruction\n # address += 1\n\n def alu(self, op, reg_a, reg_b):\n \"\"\"ALU operations.\"\"\"\n\n if op == 'ADD':\n self.reg[reg_a] = self.reg[reg_a] + self.reg[reg_b]\n elif op == 'MUL':\n self.reg[reg_a] = self.reg[reg_a] * self.reg[reg_b]\n elif op == 'CMP':\n if self.reg[reg_a] < self.reg[reg_b]:\n self.fl = 0b00000100\n elif self.reg[reg_a] > self.reg[reg_b]:\n self.fl = 0b00000010\n elif self.reg[reg_a] == self.reg[reg_b]:\n self.fl = 0b00000001\n elif op == 'AND':\n self.reg[reg_a] = self.reg[reg_a] & self.reg[reg_b]\n elif op == 'OR':\n self.reg[reg_a] = self.reg[reg_a] | self.reg[reg_b]\n elif op == 'XOR':\n self.reg[reg_a] = self.reg[reg_a] ^ self.reg[reg_b]\n elif op == 'NOT':\n self.reg[reg_a] = ~self.reg[reg_a]\n elif op == 'SHL':\n self.reg[reg_a] = self.reg[reg_a] << self.reg[reg_b]\n elif op == 'SHR':\n self.reg[reg_a] = self.reg[reg_a] >> self.reg[reg_b]\n elif op == 'MOD':\n if self.reg[reg_b] == 0:\n print('ERROR: divide by 0')\n self.op_hlt()\n else:\n remainder = self.reg[reg_a] % self.reg[reg_b]\n self.reg[reg_a] = remainder\n\n else:\n raise Exception(\"Unsupported ALU operation\")\n\n def trace(self):\n \"\"\"\n Handy function to print out the CPU state. You might want to call this\n from run() if you need help debugging.\n \"\"\"\n\n print(f\"TRACE: %02X | %02X %02X %02X |\" % (\n self.pc,\n # self.fl,\n # self.ie,\n self.ram_read(self.pc),\n self.ram_read(self.pc + 1),\n self.ram_read(self.pc + 2)\n ), end='')\n\n for i in range(8):\n print(\" %02X\" % self.reg[i], end='')\n\n print()\n\n def run(self):\n \"\"\"Run the CPU.\"\"\"\n self.trace()\n\n while self.running is True:\n IR = self.ram_read(self.pc)\n operand_a = self.ram_read(self.pc + 1)\n operand_b = self.ram_read(self.pc + 2)\n\n # This increments the pc position automatically\n op_size = IR >> 6\n ins_set = ((IR >> 4) & 0b1) == 1\n if not ins_set:\n self.pc += op_size + 1\n\n if IR in self.branchtable:\n self.branchtable[IR](operand_a, operand_b)\n\n# SAVE WHERE WE'RE COMING FROM TO THE STACK AND SET PC TO WHERE WE'RE GOING\n", "step-ids": [ 13, 22, 23, 27, 32 ] }
[ 13, 22, 23, 27, 32 ]
# Copyright (c) 2009 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'chromium_code': 1, }, 'includes': [ 'ots-common.gypi', ], 'targets': [ { 'target_name': 'ots', 'type': '<(library)', 'sources': [ '<@(ots_sources)', ], 'include_dirs': [ '<@(ots_include_dirs)', ], 'direct_dependent_settings': { 'include_dirs': [ '<@(ots_include_dirs)', ], }, 'dependencies': [ '../zlib/zlib.gyp:zlib', ], }, ], }
normal
{ "blob_id": "7413d4e98f79bf7b389a6305257833293714fc81", "index": 1786, "step-1": "<mask token>\n", "step-2": "{'variables': {'chromium_code': 1}, 'includes': ['ots-common.gypi'],\n 'targets': [{'target_name': 'ots', 'type': '<(library)', 'sources': [\n '<@(ots_sources)'], 'include_dirs': ['<@(ots_include_dirs)'],\n 'direct_dependent_settings': {'include_dirs': ['<@(ots_include_dirs)']},\n 'dependencies': ['../zlib/zlib.gyp:zlib']}]}\n", "step-3": "# Copyright (c) 2009 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\n{\n 'variables': {\n 'chromium_code': 1,\n },\n 'includes': [\n 'ots-common.gypi',\n ],\n 'targets': [\n {\n 'target_name': 'ots',\n 'type': '<(library)',\n 'sources': [\n '<@(ots_sources)',\n ],\n 'include_dirs': [\n '<@(ots_include_dirs)',\n ],\n 'direct_dependent_settings': {\n 'include_dirs': [\n '<@(ots_include_dirs)',\n ],\n },\n 'dependencies': [\n '../zlib/zlib.gyp:zlib',\n ],\n },\n ],\n}\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> class Assignment(models.Model): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def __str__(self): return self.name + '-' + self.technology class Assestment(models.Model): name = models.CharField(max_length=250) technology = models.CharField(max_length=100) username = models.CharField(max_length=100, default='NA') date = models.DateTimeField(default=datetime.datetime.now, blank=True) def __str__(self): return self.name + '-' + self.technology class UserProfile(models.Model): user = models.OneToOneField(User) email = models.CharField(max_length=100) phone = models.IntegerField(default=0) city = models.CharField(max_length=100) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Assignment(models.Model): name = models.CharField(max_length=250) technology = models.CharField(max_length=100) directory = models.CharField(max_length=500, default='NA') def __str__(self): return self.name + '-' + self.technology class Assestment(models.Model): name = models.CharField(max_length=250) technology = models.CharField(max_length=100) username = models.CharField(max_length=100, default='NA') date = models.DateTimeField(default=datetime.datetime.now, blank=True) def __str__(self): return self.name + '-' + self.technology class UserProfile(models.Model): user = models.OneToOneField(User) email = models.CharField(max_length=100) phone = models.IntegerField(default=0) city = models.CharField(max_length=100) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Document(models.Model): document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.document) class Assignment(models.Model): name = models.CharField(max_length=250) technology = models.CharField(max_length=100) directory = models.CharField(max_length=500, default='NA') def __str__(self): return self.name + '-' + self.technology class Assestment(models.Model): name = models.CharField(max_length=250) technology = models.CharField(max_length=100) username = models.CharField(max_length=100, default='NA') date = models.DateTimeField(default=datetime.datetime.now, blank=True) def __str__(self): return self.name + '-' + self.technology class UserProfile(models.Model): user = models.OneToOneField(User) email = models.CharField(max_length=100) phone = models.IntegerField(default=0) city = models.CharField(max_length=100) <|reserved_special_token_0|> <|reserved_special_token_1|> from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.core.urlresolvers import reverse import datetime class Document(models.Model): document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.document) class Assignment(models.Model): name = models.CharField(max_length=250) technology = models.CharField(max_length=100) directory = models.CharField(max_length=500, default='NA') def __str__(self): return self.name + '-' + self.technology class Assestment(models.Model): name = models.CharField(max_length=250) technology = models.CharField(max_length=100) username = models.CharField(max_length=100, default='NA') date = models.DateTimeField(default=datetime.datetime.now, blank=True) def __str__(self): return self.name + '-' + self.technology class UserProfile(models.Model): user = models.OneToOneField(User) email = models.CharField(max_length=100) phone = models.IntegerField(default=0) city = models.CharField(max_length=100) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) <|reserved_special_token_1|> from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.core.urlresolvers import reverse import datetime class Document(models.Model): document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.document) class Assignment(models.Model): name= models.CharField(max_length=250) technology= models.CharField(max_length=100) directory= models.CharField(max_length=500, default="NA") def __str__(self): return self.name + '-' + self.technology class Assestment(models.Model): name= models.CharField(max_length=250) technology= models.CharField(max_length=100) username= models.CharField(max_length=100, default="NA") date = models.DateTimeField(default=datetime.datetime.now, blank=True) def __str__(self): return self.name + '-' + self.technology class UserProfile(models.Model): user = models.OneToOneField(User) email = models.CharField(max_length=100) phone = models.IntegerField(default=0) city = models.CharField(max_length=100) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User)
flexible
{ "blob_id": "01b14da7d081a67bab6f9921bb1a6a4c3d5ac216", "index": 3003, "step-1": "<mask token>\n\n\nclass Assignment(models.Model):\n <mask token>\n <mask token>\n <mask token>\n\n def __str__(self):\n return self.name + '-' + self.technology\n\n\nclass Assestment(models.Model):\n name = models.CharField(max_length=250)\n technology = models.CharField(max_length=100)\n username = models.CharField(max_length=100, default='NA')\n date = models.DateTimeField(default=datetime.datetime.now, blank=True)\n\n def __str__(self):\n return self.name + '-' + self.technology\n\n\nclass UserProfile(models.Model):\n user = models.OneToOneField(User)\n email = models.CharField(max_length=100)\n phone = models.IntegerField(default=0)\n city = models.CharField(max_length=100)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Assignment(models.Model):\n name = models.CharField(max_length=250)\n technology = models.CharField(max_length=100)\n directory = models.CharField(max_length=500, default='NA')\n\n def __str__(self):\n return self.name + '-' + self.technology\n\n\nclass Assestment(models.Model):\n name = models.CharField(max_length=250)\n technology = models.CharField(max_length=100)\n username = models.CharField(max_length=100, default='NA')\n date = models.DateTimeField(default=datetime.datetime.now, blank=True)\n\n def __str__(self):\n return self.name + '-' + self.technology\n\n\nclass UserProfile(models.Model):\n user = models.OneToOneField(User)\n email = models.CharField(max_length=100)\n phone = models.IntegerField(default=0)\n city = models.CharField(max_length=100)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass Document(models.Model):\n document = models.FileField(upload_to='documents/')\n uploaded_at = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return str(self.document)\n\n\nclass Assignment(models.Model):\n name = models.CharField(max_length=250)\n technology = models.CharField(max_length=100)\n directory = models.CharField(max_length=500, default='NA')\n\n def __str__(self):\n return self.name + '-' + self.technology\n\n\nclass Assestment(models.Model):\n name = models.CharField(max_length=250)\n technology = models.CharField(max_length=100)\n username = models.CharField(max_length=100, default='NA')\n date = models.DateTimeField(default=datetime.datetime.now, blank=True)\n\n def __str__(self):\n return self.name + '-' + self.technology\n\n\nclass UserProfile(models.Model):\n user = models.OneToOneField(User)\n email = models.CharField(max_length=100)\n phone = models.IntegerField(default=0)\n city = models.CharField(max_length=100)\n\n\n<mask token>\n", "step-4": "from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.db.models.signals import post_save\nfrom django.core.urlresolvers import reverse\nimport datetime\n\n\nclass Document(models.Model):\n document = models.FileField(upload_to='documents/')\n uploaded_at = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return str(self.document)\n\n\nclass Assignment(models.Model):\n name = models.CharField(max_length=250)\n technology = models.CharField(max_length=100)\n directory = models.CharField(max_length=500, default='NA')\n\n def __str__(self):\n return self.name + '-' + self.technology\n\n\nclass Assestment(models.Model):\n name = models.CharField(max_length=250)\n technology = models.CharField(max_length=100)\n username = models.CharField(max_length=100, default='NA')\n date = models.DateTimeField(default=datetime.datetime.now, blank=True)\n\n def __str__(self):\n return self.name + '-' + self.technology\n\n\nclass UserProfile(models.Model):\n user = models.OneToOneField(User)\n email = models.CharField(max_length=100)\n phone = models.IntegerField(default=0)\n city = models.CharField(max_length=100)\n\n\ndef create_profile(sender, **kwargs):\n if kwargs['created']:\n user_profile = UserProfile.objects.create(user=kwargs['instance'])\n\n\npost_save.connect(create_profile, sender=User)\n", "step-5": "from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.db.models.signals import post_save\nfrom django.core.urlresolvers import reverse\nimport datetime\n\n\nclass Document(models.Model):\n document = models.FileField(upload_to='documents/')\n uploaded_at = models.DateTimeField(auto_now_add=True)\n\n def __str__(self):\n return str(self.document)\n\n\nclass Assignment(models.Model):\n name= models.CharField(max_length=250)\n technology= models.CharField(max_length=100)\n directory= models.CharField(max_length=500, default=\"NA\")\n\n def __str__(self):\n return self.name + '-' + self.technology\n\n\nclass Assestment(models.Model):\n name= models.CharField(max_length=250)\n technology= models.CharField(max_length=100)\n username= models.CharField(max_length=100, default=\"NA\")\n date = models.DateTimeField(default=datetime.datetime.now, blank=True)\n\n\n def __str__(self):\n return self.name + '-' + self.technology\n\nclass UserProfile(models.Model):\n user = models.OneToOneField(User)\n email = models.CharField(max_length=100)\n phone = models.IntegerField(default=0)\n city = models.CharField(max_length=100)\n\n\n\ndef create_profile(sender, **kwargs):\n if kwargs['created']:\n user_profile = UserProfile.objects.create(user=kwargs['instance'])\n\n\npost_save.connect(create_profile, sender=User)", "step-ids": [ 7, 8, 11, 14, 15 ] }
[ 7, 8, 11, 14, 15 ]
print("n:",end="") n=int(input()) print("a:",end="") a=list(map(int,input().split())) ans=0 for i in range(n): for j in range(i+1,n): for k in range(j+1,n): ai,aj,ak=sorted([a[i],a[j],a[k]]) if(ai+aj>ak and ai+aj+ak>ans): ans=ai+aj+ak print(ans)
normal
{ "blob_id": "130f49028833bf57d7e4f9fbb0764801c3508c3b", "index": 3055, "step-1": "<mask token>\n", "step-2": "print('n:', end='')\n<mask token>\nprint('a:', end='')\n<mask token>\nfor i in range(n):\n for j in range(i + 1, n):\n for k in range(j + 1, n):\n ai, aj, ak = sorted([a[i], a[j], a[k]])\n if ai + aj > ak and ai + aj + ak > ans:\n ans = ai + aj + ak\nprint(ans)\n", "step-3": "print('n:', end='')\nn = int(input())\nprint('a:', end='')\na = list(map(int, input().split()))\nans = 0\nfor i in range(n):\n for j in range(i + 1, n):\n for k in range(j + 1, n):\n ai, aj, ak = sorted([a[i], a[j], a[k]])\n if ai + aj > ak and ai + aj + ak > ans:\n ans = ai + aj + ak\nprint(ans)\n", "step-4": "print(\"n:\",end=\"\")\nn=int(input())\nprint(\"a:\",end=\"\")\na=list(map(int,input().split()))\n\nans=0\nfor i in range(n):\n for j in range(i+1,n):\n for k in range(j+1,n):\n ai,aj,ak=sorted([a[i],a[j],a[k]])\n if(ai+aj>ak and ai+aj+ak>ans):\n ans=ai+aj+ak\nprint(ans)", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from __future__ import print_function, division import os from os.path import exists, join, basename, dirname from os import makedirs import numpy as np import datetime import time import argparse import torch import torch.nn as nn import torch.optim as optim from lib.dataloader import DataLoader from lib.im_pair_dataset import ImagePairDataset from lib.normalization import NormalizeImageDict from lib.torch_util import save_checkpoint from lib.torch_util import BatchTensorToVars from lib.eval_util_dynamic import pfdataset_pck, pfpascal_val_dataloader # import DCCNet from models.model_dynamic import DCCNet from models.loss_dynamic import weak_loss # Seed and CUDA use_cuda = torch.cuda.is_available() torch.manual_seed(1) if use_cuda: torch.cuda.manual_seed(1) np.random.seed(1) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False print('DCCNet training script') # Argument parsing parser = argparse.ArgumentParser(description='Compute PF Pascal matches') parser.add_argument('--checkpoint', type=str, default='') parser.add_argument('--image_size', type=int, default=400) parser.add_argument('--dataset_image_path', type=str, default='datasets/pf-pascal/', help='path to PF Pascal dataset') parser.add_argument('--dataset_csv_path', type=str, default='datasets/pf-pascal/image_pairs/', help='path to PF Pascal training csv') parser.add_argument('--num_epochs', type=int, default=5, help='number of training epochs') parser.add_argument('--batch_size', type=int, default=16, help='training batch size') parser.add_argument('--lr', type=float, default=0.0005, help='learning rate') parser.add_argument('--result_model_fn', type=str, default='checkpoint_adam', help='trained model filename') parser.add_argument('--result-model-dir', type=str, default='../model/checkpoints', help='path to trained models folder') parser.add_argument('--fe_finetune_params', type=int, default=0, help='number of layers to finetune') parser.add_argument('--exp_name', type=str, default='exp_delete', help='experiment name') # DCCNet args parser.add_argument('--ncons_kernel_sizes', nargs='+', type=int, default=[5,5,5], help='kernels sizes in neigh. cons.') parser.add_argument('--ncons_channels', nargs='+', type=int, default=[16,16,1], help='channels in neigh. cons') parser.add_argument('--sce_kernel_size',type=int,default=25,help='kernel size in sce.') parser.add_argument('--sce_hidden_dim',type=int,default=1024,help='hidden dim in sce') parser.add_argument('--scaleloss_weight',type=float,default=1.0,help='whether use scale loss, if use the weight for scale loss') parser.add_argument('--att_scale_ncons_kernel_sizes', nargs='+', type=int, default=[5,5,5], help='kernels sizes in dynamic fusion net.') parser.add_argument('--att_scale_ncons_channels', nargs='+', type=int, default=[16,16,1], help='channels in dynamic fusion net') args = parser.parse_args() print(args) # Create model print('Creating CNN model...') model = DCCNet(use_cuda=use_cuda, checkpoint=args.checkpoint, ncons_kernel_sizes=args.ncons_kernel_sizes, ncons_channels=args.ncons_channels, sce_kernel_size=args.sce_kernel_size, sce_hidden_dim=args.sce_hidden_dim, att_scale_ncons_kernel_sizes=args.att_scale_ncons_kernel_sizes, att_scale_ncons_channels=args.att_scale_ncons_channels, ) #Multi-GPU support model = nn.DataParallel(model) # Set which parts of the model to train if args.fe_finetune_params>0: for i in range(args.fe_finetune_params): for p in model.module.FeatureExtraction.model[-1][-(i+1)].parameters(): p.requires_grad=True print('Trainable parameters:') count = 0 for i,param in enumerate(model.named_parameters()): name,p = param if p.requires_grad: count+=1 print(str(count)+": "+name+"\t"+str(p.shape)+"\t") print(model) # Optimizer print('using Adam optimizer') optimizer = optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr) cnn_image_size=(args.image_size,args.image_size) Dataset = ImagePairDataset train_csv = 'train_pairs.csv' #val_pairs_nocoords.csv: for compute loss, with flip column in csv, no coordinates #val_pairs.csv: for compute pck, with coordinates val_nocoordinates_csv = 'val_pairs_nocoords.csv' val_csv = 'image_pairs/val_pairs.csv' normalization_tnf = NormalizeImageDict(['source_image','target_image']) batch_preprocessing_fn = BatchTensorToVars(use_cuda=use_cuda) # Dataset and dataloader dataset = Dataset(transform=normalization_tnf, dataset_image_path=args.dataset_image_path, dataset_csv_path=args.dataset_csv_path, dataset_csv_file = train_csv, output_size=cnn_image_size, ) dataloader = DataLoader(dataset, batch_size=args.batch_size, shuffle=True, num_workers=0) dataset_val = Dataset(transform=normalization_tnf, dataset_image_path=args.dataset_image_path, dataset_csv_path=args.dataset_csv_path, dataset_csv_file=val_nocoordinates_csv, output_size=cnn_image_size) # compute val loss dataloader_val = DataLoader(dataset_val, batch_size=args.batch_size, shuffle=True, num_workers=4) # compute val pck dataloader_val_pck = pfpascal_val_dataloader(image_size=args.image_size, eval_dataset_path=args.dataset_image_path, csv_file=val_csv) #load pfpascal val dataset # Define checkpoint name checkpoint_dir = os.path.join(args.result_model_dir,args.exp_name) checkpoint_name = os.path.join(args.result_model_dir,args.exp_name, datetime.datetime.now().strftime("%Y-%m-%d_%H:%M")+'_'+args.result_model_fn + '.pth.tar') log_name = os.path.join(args.result_model_dir,args.exp_name, 'logmain_'+args.exp_name+'.txt') if not exists(dirname(log_name)): makedirs(dirname(log_name)) print('Checkpoint name: '+checkpoint_name) # Train best_val_pck = float("-inf") loss_fn = lambda model,batch: weak_loss(model, batch, normalization='softmax', scaleloss_weight=args.scaleloss_weight) # define epoch function def process_epoch(mode,epoch,model,loss_fn,optimizer,dataloader,batch_preprocessing_fn,use_cuda=True,log_interval=50): epoch_loss = 0 for batch_idx, batch in enumerate(dataloader): st = time.time() if mode=='train': optimizer.zero_grad() tnf_batch = batch_preprocessing_fn(batch) loss = loss_fn(model,tnf_batch) loss_np = loss.data.cpu().numpy()[0] #loss_np = loss.data.cpu().numpy() epoch_loss += loss_np if mode=='train': loss.backward() optimizer.step() else: loss=None if batch_idx % log_interval == 0: print(mode.capitalize()+' Epoch: {} [{}/{} ({:.0f}%)]\t\tLoss: {:.12f}\t\tcost time: {:.1f}'.format( epoch, batch_idx , len(dataloader), 100. * batch_idx / len(dataloader), loss_np,time.time()-st)) epoch_loss /= len(dataloader) print(mode.capitalize()+' set: Average loss: {:.12f}'.format(epoch_loss)) return epoch_loss train_loss = np.zeros(args.num_epochs) val_loss = np.zeros(args.num_epochs) val_pcks = np.zeros(args.num_epochs) model.module.FeatureExtraction.eval() print('Starting training...') for epoch in range(1, args.num_epochs+1): st = time.time() train_loss_curepoch = process_epoch('train',epoch,model,loss_fn,optimizer,dataloader,batch_preprocessing_fn,log_interval=1) time_train = time.time()-st st = time.time() val_loss_curepoch = process_epoch('val', epoch, model, loss_fn, optimizer, dataloader_val, batch_preprocessing_fn, log_interval=1) time_valloss = time.time()-st st = time.time() val_pck_curepoch = pfdataset_pck(dataloader=dataloader_val_pck,model=model,verbose=False) time_valpck = time.time()-st train_loss[epoch - 1] = train_loss_curepoch val_loss[epoch - 1] = val_loss_curepoch val_pcks[epoch-1] = val_pck_curepoch # remember best loss is_best = val_pcks[epoch - 1] > best_val_pck best_val_pck = max(val_pcks[epoch - 1], best_val_pck) save_checkpoint({ 'epoch': epoch, 'args': args, 'state_dict': model.state_dict(), 'optimizer' : optimizer.state_dict(), 'train_loss': train_loss, 'val_loss': val_loss, 'val_pck': val_pcks, 'best_val_pck':best_val_pck, }, is_best,checkpoint_name,save_all_epochs=False) message = 'Epoch{}\tTrain_loss{:.6f}\tcost time{:.1f}\tVal_loss{:.6f}\tcost time{:.1f}\tVal_pck{:.6f}\tcost time{:.1f}\n'.format\ (epoch, train_loss_curepoch, time_train, val_loss_curepoch, time_valloss,val_pck_curepoch,time_valpck,) print(message) with open(log_name, "a") as log_file: log_file.write('%s\n' % message) print('Done!')
normal
{ "blob_id": "0c97569c77fb3598d83eba607960328bb2134dd2", "index": 333, "step-1": "<mask token>\n", "step-2": "<mask token>\ntorch.manual_seed(1)\nif use_cuda:\n torch.cuda.manual_seed(1)\nnp.random.seed(1)\n<mask token>\nprint('DCCNet training script')\n<mask token>\nparser.add_argument('--checkpoint', type=str, default='')\nparser.add_argument('--image_size', type=int, default=400)\nparser.add_argument('--dataset_image_path', type=str, default=\n 'datasets/pf-pascal/', help='path to PF Pascal dataset')\nparser.add_argument('--dataset_csv_path', type=str, default=\n 'datasets/pf-pascal/image_pairs/', help='path to PF Pascal training csv')\nparser.add_argument('--num_epochs', type=int, default=5, help=\n 'number of training epochs')\nparser.add_argument('--batch_size', type=int, default=16, help=\n 'training batch size')\nparser.add_argument('--lr', type=float, default=0.0005, help='learning rate')\nparser.add_argument('--result_model_fn', type=str, default=\n 'checkpoint_adam', help='trained model filename')\nparser.add_argument('--result-model-dir', type=str, default=\n '../model/checkpoints', help='path to trained models folder')\nparser.add_argument('--fe_finetune_params', type=int, default=0, help=\n 'number of layers to finetune')\nparser.add_argument('--exp_name', type=str, default='exp_delete', help=\n 'experiment name')\nparser.add_argument('--ncons_kernel_sizes', nargs='+', type=int, default=[5,\n 5, 5], help='kernels sizes in neigh. cons.')\nparser.add_argument('--ncons_channels', nargs='+', type=int, default=[16, \n 16, 1], help='channels in neigh. cons')\nparser.add_argument('--sce_kernel_size', type=int, default=25, help=\n 'kernel size in sce.')\nparser.add_argument('--sce_hidden_dim', type=int, default=1024, help=\n 'hidden dim in sce')\nparser.add_argument('--scaleloss_weight', type=float, default=1.0, help=\n 'whether use scale loss, if use the weight for scale loss')\nparser.add_argument('--att_scale_ncons_kernel_sizes', nargs='+', type=int,\n default=[5, 5, 5], help='kernels sizes in dynamic fusion net.')\nparser.add_argument('--att_scale_ncons_channels', nargs='+', type=int,\n default=[16, 16, 1], help='channels in dynamic fusion net')\n<mask token>\nprint(args)\nprint('Creating CNN model...')\n<mask token>\nif args.fe_finetune_params > 0:\n for i in range(args.fe_finetune_params):\n for p in model.module.FeatureExtraction.model[-1][-(i + 1)].parameters(\n ):\n p.requires_grad = True\nprint('Trainable parameters:')\n<mask token>\nfor i, param in enumerate(model.named_parameters()):\n name, p = param\n if p.requires_grad:\n count += 1\n print(str(count) + ': ' + name + '\\t' + str(p.shape) + '\\t')\nprint(model)\nprint('using Adam optimizer')\n<mask token>\nif not exists(dirname(log_name)):\n makedirs(dirname(log_name))\nprint('Checkpoint name: ' + checkpoint_name)\n<mask token>\n\n\ndef process_epoch(mode, epoch, model, loss_fn, optimizer, dataloader,\n batch_preprocessing_fn, use_cuda=True, log_interval=50):\n epoch_loss = 0\n for batch_idx, batch in enumerate(dataloader):\n st = time.time()\n if mode == 'train':\n optimizer.zero_grad()\n tnf_batch = batch_preprocessing_fn(batch)\n loss = loss_fn(model, tnf_batch)\n loss_np = loss.data.cpu().numpy()[0]\n epoch_loss += loss_np\n if mode == 'train':\n loss.backward()\n optimizer.step()\n else:\n loss = None\n if batch_idx % log_interval == 0:\n print(mode.capitalize() +\n ' Epoch: {} [{}/{} ({:.0f}%)]\\t\\tLoss: {:.12f}\\t\\tcost time: {:.1f}'\n .format(epoch, batch_idx, len(dataloader), 100.0 *\n batch_idx / len(dataloader), loss_np, time.time() - st))\n epoch_loss /= len(dataloader)\n print(mode.capitalize() + ' set: Average loss: {:.12f}'.format(epoch_loss))\n return epoch_loss\n\n\n<mask token>\nmodel.module.FeatureExtraction.eval()\nprint('Starting training...')\nfor epoch in range(1, args.num_epochs + 1):\n st = time.time()\n train_loss_curepoch = process_epoch('train', epoch, model, loss_fn,\n optimizer, dataloader, batch_preprocessing_fn, log_interval=1)\n time_train = time.time() - st\n st = time.time()\n val_loss_curepoch = process_epoch('val', epoch, model, loss_fn,\n optimizer, dataloader_val, batch_preprocessing_fn, log_interval=1)\n time_valloss = time.time() - st\n st = time.time()\n val_pck_curepoch = pfdataset_pck(dataloader=dataloader_val_pck, model=\n model, verbose=False)\n time_valpck = time.time() - st\n train_loss[epoch - 1] = train_loss_curepoch\n val_loss[epoch - 1] = val_loss_curepoch\n val_pcks[epoch - 1] = val_pck_curepoch\n is_best = val_pcks[epoch - 1] > best_val_pck\n best_val_pck = max(val_pcks[epoch - 1], best_val_pck)\n save_checkpoint({'epoch': epoch, 'args': args, 'state_dict': model.\n state_dict(), 'optimizer': optimizer.state_dict(), 'train_loss':\n train_loss, 'val_loss': val_loss, 'val_pck': val_pcks,\n 'best_val_pck': best_val_pck}, is_best, checkpoint_name,\n save_all_epochs=False)\n message = (\n \"\"\"Epoch{}\tTrain_loss{:.6f}\tcost time{:.1f}\tVal_loss{:.6f}\tcost time{:.1f}\tVal_pck{:.6f}\tcost time{:.1f}\n\"\"\"\n .format(epoch, train_loss_curepoch, time_train, val_loss_curepoch,\n time_valloss, val_pck_curepoch, time_valpck))\n print(message)\n with open(log_name, 'a') as log_file:\n log_file.write('%s\\n' % message)\nprint('Done!')\n", "step-3": "<mask token>\nuse_cuda = torch.cuda.is_available()\ntorch.manual_seed(1)\nif use_cuda:\n torch.cuda.manual_seed(1)\nnp.random.seed(1)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\nprint('DCCNet training script')\nparser = argparse.ArgumentParser(description='Compute PF Pascal matches')\nparser.add_argument('--checkpoint', type=str, default='')\nparser.add_argument('--image_size', type=int, default=400)\nparser.add_argument('--dataset_image_path', type=str, default=\n 'datasets/pf-pascal/', help='path to PF Pascal dataset')\nparser.add_argument('--dataset_csv_path', type=str, default=\n 'datasets/pf-pascal/image_pairs/', help='path to PF Pascal training csv')\nparser.add_argument('--num_epochs', type=int, default=5, help=\n 'number of training epochs')\nparser.add_argument('--batch_size', type=int, default=16, help=\n 'training batch size')\nparser.add_argument('--lr', type=float, default=0.0005, help='learning rate')\nparser.add_argument('--result_model_fn', type=str, default=\n 'checkpoint_adam', help='trained model filename')\nparser.add_argument('--result-model-dir', type=str, default=\n '../model/checkpoints', help='path to trained models folder')\nparser.add_argument('--fe_finetune_params', type=int, default=0, help=\n 'number of layers to finetune')\nparser.add_argument('--exp_name', type=str, default='exp_delete', help=\n 'experiment name')\nparser.add_argument('--ncons_kernel_sizes', nargs='+', type=int, default=[5,\n 5, 5], help='kernels sizes in neigh. cons.')\nparser.add_argument('--ncons_channels', nargs='+', type=int, default=[16, \n 16, 1], help='channels in neigh. cons')\nparser.add_argument('--sce_kernel_size', type=int, default=25, help=\n 'kernel size in sce.')\nparser.add_argument('--sce_hidden_dim', type=int, default=1024, help=\n 'hidden dim in sce')\nparser.add_argument('--scaleloss_weight', type=float, default=1.0, help=\n 'whether use scale loss, if use the weight for scale loss')\nparser.add_argument('--att_scale_ncons_kernel_sizes', nargs='+', type=int,\n default=[5, 5, 5], help='kernels sizes in dynamic fusion net.')\nparser.add_argument('--att_scale_ncons_channels', nargs='+', type=int,\n default=[16, 16, 1], help='channels in dynamic fusion net')\nargs = parser.parse_args()\nprint(args)\nprint('Creating CNN model...')\nmodel = DCCNet(use_cuda=use_cuda, checkpoint=args.checkpoint,\n ncons_kernel_sizes=args.ncons_kernel_sizes, ncons_channels=args.\n ncons_channels, sce_kernel_size=args.sce_kernel_size, sce_hidden_dim=\n args.sce_hidden_dim, att_scale_ncons_kernel_sizes=args.\n att_scale_ncons_kernel_sizes, att_scale_ncons_channels=args.\n att_scale_ncons_channels)\nmodel = nn.DataParallel(model)\nif args.fe_finetune_params > 0:\n for i in range(args.fe_finetune_params):\n for p in model.module.FeatureExtraction.model[-1][-(i + 1)].parameters(\n ):\n p.requires_grad = True\nprint('Trainable parameters:')\ncount = 0\nfor i, param in enumerate(model.named_parameters()):\n name, p = param\n if p.requires_grad:\n count += 1\n print(str(count) + ': ' + name + '\\t' + str(p.shape) + '\\t')\nprint(model)\nprint('using Adam optimizer')\noptimizer = optim.Adam(filter(lambda p: p.requires_grad, model.parameters()\n ), lr=args.lr)\ncnn_image_size = args.image_size, args.image_size\nDataset = ImagePairDataset\ntrain_csv = 'train_pairs.csv'\nval_nocoordinates_csv = 'val_pairs_nocoords.csv'\nval_csv = 'image_pairs/val_pairs.csv'\nnormalization_tnf = NormalizeImageDict(['source_image', 'target_image'])\nbatch_preprocessing_fn = BatchTensorToVars(use_cuda=use_cuda)\ndataset = Dataset(transform=normalization_tnf, dataset_image_path=args.\n dataset_image_path, dataset_csv_path=args.dataset_csv_path,\n dataset_csv_file=train_csv, output_size=cnn_image_size)\ndataloader = DataLoader(dataset, batch_size=args.batch_size, shuffle=True,\n num_workers=0)\ndataset_val = Dataset(transform=normalization_tnf, dataset_image_path=args.\n dataset_image_path, dataset_csv_path=args.dataset_csv_path,\n dataset_csv_file=val_nocoordinates_csv, output_size=cnn_image_size)\ndataloader_val = DataLoader(dataset_val, batch_size=args.batch_size,\n shuffle=True, num_workers=4)\ndataloader_val_pck = pfpascal_val_dataloader(image_size=args.image_size,\n eval_dataset_path=args.dataset_image_path, csv_file=val_csv)\ncheckpoint_dir = os.path.join(args.result_model_dir, args.exp_name)\ncheckpoint_name = os.path.join(args.result_model_dir, args.exp_name, \n datetime.datetime.now().strftime('%Y-%m-%d_%H:%M') + '_' + args.\n result_model_fn + '.pth.tar')\nlog_name = os.path.join(args.result_model_dir, args.exp_name, 'logmain_' +\n args.exp_name + '.txt')\nif not exists(dirname(log_name)):\n makedirs(dirname(log_name))\nprint('Checkpoint name: ' + checkpoint_name)\nbest_val_pck = float('-inf')\nloss_fn = lambda model, batch: weak_loss(model, batch, normalization=\n 'softmax', scaleloss_weight=args.scaleloss_weight)\n\n\ndef process_epoch(mode, epoch, model, loss_fn, optimizer, dataloader,\n batch_preprocessing_fn, use_cuda=True, log_interval=50):\n epoch_loss = 0\n for batch_idx, batch in enumerate(dataloader):\n st = time.time()\n if mode == 'train':\n optimizer.zero_grad()\n tnf_batch = batch_preprocessing_fn(batch)\n loss = loss_fn(model, tnf_batch)\n loss_np = loss.data.cpu().numpy()[0]\n epoch_loss += loss_np\n if mode == 'train':\n loss.backward()\n optimizer.step()\n else:\n loss = None\n if batch_idx % log_interval == 0:\n print(mode.capitalize() +\n ' Epoch: {} [{}/{} ({:.0f}%)]\\t\\tLoss: {:.12f}\\t\\tcost time: {:.1f}'\n .format(epoch, batch_idx, len(dataloader), 100.0 *\n batch_idx / len(dataloader), loss_np, time.time() - st))\n epoch_loss /= len(dataloader)\n print(mode.capitalize() + ' set: Average loss: {:.12f}'.format(epoch_loss))\n return epoch_loss\n\n\ntrain_loss = np.zeros(args.num_epochs)\nval_loss = np.zeros(args.num_epochs)\nval_pcks = np.zeros(args.num_epochs)\nmodel.module.FeatureExtraction.eval()\nprint('Starting training...')\nfor epoch in range(1, args.num_epochs + 1):\n st = time.time()\n train_loss_curepoch = process_epoch('train', epoch, model, loss_fn,\n optimizer, dataloader, batch_preprocessing_fn, log_interval=1)\n time_train = time.time() - st\n st = time.time()\n val_loss_curepoch = process_epoch('val', epoch, model, loss_fn,\n optimizer, dataloader_val, batch_preprocessing_fn, log_interval=1)\n time_valloss = time.time() - st\n st = time.time()\n val_pck_curepoch = pfdataset_pck(dataloader=dataloader_val_pck, model=\n model, verbose=False)\n time_valpck = time.time() - st\n train_loss[epoch - 1] = train_loss_curepoch\n val_loss[epoch - 1] = val_loss_curepoch\n val_pcks[epoch - 1] = val_pck_curepoch\n is_best = val_pcks[epoch - 1] > best_val_pck\n best_val_pck = max(val_pcks[epoch - 1], best_val_pck)\n save_checkpoint({'epoch': epoch, 'args': args, 'state_dict': model.\n state_dict(), 'optimizer': optimizer.state_dict(), 'train_loss':\n train_loss, 'val_loss': val_loss, 'val_pck': val_pcks,\n 'best_val_pck': best_val_pck}, is_best, checkpoint_name,\n save_all_epochs=False)\n message = (\n \"\"\"Epoch{}\tTrain_loss{:.6f}\tcost time{:.1f}\tVal_loss{:.6f}\tcost time{:.1f}\tVal_pck{:.6f}\tcost time{:.1f}\n\"\"\"\n .format(epoch, train_loss_curepoch, time_train, val_loss_curepoch,\n time_valloss, val_pck_curepoch, time_valpck))\n print(message)\n with open(log_name, 'a') as log_file:\n log_file.write('%s\\n' % message)\nprint('Done!')\n", "step-4": "from __future__ import print_function, division\nimport os\nfrom os.path import exists, join, basename, dirname\nfrom os import makedirs\nimport numpy as np\nimport datetime\nimport time\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom lib.dataloader import DataLoader\nfrom lib.im_pair_dataset import ImagePairDataset\nfrom lib.normalization import NormalizeImageDict\nfrom lib.torch_util import save_checkpoint\nfrom lib.torch_util import BatchTensorToVars\nfrom lib.eval_util_dynamic import pfdataset_pck, pfpascal_val_dataloader\nfrom models.model_dynamic import DCCNet\nfrom models.loss_dynamic import weak_loss\nuse_cuda = torch.cuda.is_available()\ntorch.manual_seed(1)\nif use_cuda:\n torch.cuda.manual_seed(1)\nnp.random.seed(1)\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\nprint('DCCNet training script')\nparser = argparse.ArgumentParser(description='Compute PF Pascal matches')\nparser.add_argument('--checkpoint', type=str, default='')\nparser.add_argument('--image_size', type=int, default=400)\nparser.add_argument('--dataset_image_path', type=str, default=\n 'datasets/pf-pascal/', help='path to PF Pascal dataset')\nparser.add_argument('--dataset_csv_path', type=str, default=\n 'datasets/pf-pascal/image_pairs/', help='path to PF Pascal training csv')\nparser.add_argument('--num_epochs', type=int, default=5, help=\n 'number of training epochs')\nparser.add_argument('--batch_size', type=int, default=16, help=\n 'training batch size')\nparser.add_argument('--lr', type=float, default=0.0005, help='learning rate')\nparser.add_argument('--result_model_fn', type=str, default=\n 'checkpoint_adam', help='trained model filename')\nparser.add_argument('--result-model-dir', type=str, default=\n '../model/checkpoints', help='path to trained models folder')\nparser.add_argument('--fe_finetune_params', type=int, default=0, help=\n 'number of layers to finetune')\nparser.add_argument('--exp_name', type=str, default='exp_delete', help=\n 'experiment name')\nparser.add_argument('--ncons_kernel_sizes', nargs='+', type=int, default=[5,\n 5, 5], help='kernels sizes in neigh. cons.')\nparser.add_argument('--ncons_channels', nargs='+', type=int, default=[16, \n 16, 1], help='channels in neigh. cons')\nparser.add_argument('--sce_kernel_size', type=int, default=25, help=\n 'kernel size in sce.')\nparser.add_argument('--sce_hidden_dim', type=int, default=1024, help=\n 'hidden dim in sce')\nparser.add_argument('--scaleloss_weight', type=float, default=1.0, help=\n 'whether use scale loss, if use the weight for scale loss')\nparser.add_argument('--att_scale_ncons_kernel_sizes', nargs='+', type=int,\n default=[5, 5, 5], help='kernels sizes in dynamic fusion net.')\nparser.add_argument('--att_scale_ncons_channels', nargs='+', type=int,\n default=[16, 16, 1], help='channels in dynamic fusion net')\nargs = parser.parse_args()\nprint(args)\nprint('Creating CNN model...')\nmodel = DCCNet(use_cuda=use_cuda, checkpoint=args.checkpoint,\n ncons_kernel_sizes=args.ncons_kernel_sizes, ncons_channels=args.\n ncons_channels, sce_kernel_size=args.sce_kernel_size, sce_hidden_dim=\n args.sce_hidden_dim, att_scale_ncons_kernel_sizes=args.\n att_scale_ncons_kernel_sizes, att_scale_ncons_channels=args.\n att_scale_ncons_channels)\nmodel = nn.DataParallel(model)\nif args.fe_finetune_params > 0:\n for i in range(args.fe_finetune_params):\n for p in model.module.FeatureExtraction.model[-1][-(i + 1)].parameters(\n ):\n p.requires_grad = True\nprint('Trainable parameters:')\ncount = 0\nfor i, param in enumerate(model.named_parameters()):\n name, p = param\n if p.requires_grad:\n count += 1\n print(str(count) + ': ' + name + '\\t' + str(p.shape) + '\\t')\nprint(model)\nprint('using Adam optimizer')\noptimizer = optim.Adam(filter(lambda p: p.requires_grad, model.parameters()\n ), lr=args.lr)\ncnn_image_size = args.image_size, args.image_size\nDataset = ImagePairDataset\ntrain_csv = 'train_pairs.csv'\nval_nocoordinates_csv = 'val_pairs_nocoords.csv'\nval_csv = 'image_pairs/val_pairs.csv'\nnormalization_tnf = NormalizeImageDict(['source_image', 'target_image'])\nbatch_preprocessing_fn = BatchTensorToVars(use_cuda=use_cuda)\ndataset = Dataset(transform=normalization_tnf, dataset_image_path=args.\n dataset_image_path, dataset_csv_path=args.dataset_csv_path,\n dataset_csv_file=train_csv, output_size=cnn_image_size)\ndataloader = DataLoader(dataset, batch_size=args.batch_size, shuffle=True,\n num_workers=0)\ndataset_val = Dataset(transform=normalization_tnf, dataset_image_path=args.\n dataset_image_path, dataset_csv_path=args.dataset_csv_path,\n dataset_csv_file=val_nocoordinates_csv, output_size=cnn_image_size)\ndataloader_val = DataLoader(dataset_val, batch_size=args.batch_size,\n shuffle=True, num_workers=4)\ndataloader_val_pck = pfpascal_val_dataloader(image_size=args.image_size,\n eval_dataset_path=args.dataset_image_path, csv_file=val_csv)\ncheckpoint_dir = os.path.join(args.result_model_dir, args.exp_name)\ncheckpoint_name = os.path.join(args.result_model_dir, args.exp_name, \n datetime.datetime.now().strftime('%Y-%m-%d_%H:%M') + '_' + args.\n result_model_fn + '.pth.tar')\nlog_name = os.path.join(args.result_model_dir, args.exp_name, 'logmain_' +\n args.exp_name + '.txt')\nif not exists(dirname(log_name)):\n makedirs(dirname(log_name))\nprint('Checkpoint name: ' + checkpoint_name)\nbest_val_pck = float('-inf')\nloss_fn = lambda model, batch: weak_loss(model, batch, normalization=\n 'softmax', scaleloss_weight=args.scaleloss_weight)\n\n\ndef process_epoch(mode, epoch, model, loss_fn, optimizer, dataloader,\n batch_preprocessing_fn, use_cuda=True, log_interval=50):\n epoch_loss = 0\n for batch_idx, batch in enumerate(dataloader):\n st = time.time()\n if mode == 'train':\n optimizer.zero_grad()\n tnf_batch = batch_preprocessing_fn(batch)\n loss = loss_fn(model, tnf_batch)\n loss_np = loss.data.cpu().numpy()[0]\n epoch_loss += loss_np\n if mode == 'train':\n loss.backward()\n optimizer.step()\n else:\n loss = None\n if batch_idx % log_interval == 0:\n print(mode.capitalize() +\n ' Epoch: {} [{}/{} ({:.0f}%)]\\t\\tLoss: {:.12f}\\t\\tcost time: {:.1f}'\n .format(epoch, batch_idx, len(dataloader), 100.0 *\n batch_idx / len(dataloader), loss_np, time.time() - st))\n epoch_loss /= len(dataloader)\n print(mode.capitalize() + ' set: Average loss: {:.12f}'.format(epoch_loss))\n return epoch_loss\n\n\ntrain_loss = np.zeros(args.num_epochs)\nval_loss = np.zeros(args.num_epochs)\nval_pcks = np.zeros(args.num_epochs)\nmodel.module.FeatureExtraction.eval()\nprint('Starting training...')\nfor epoch in range(1, args.num_epochs + 1):\n st = time.time()\n train_loss_curepoch = process_epoch('train', epoch, model, loss_fn,\n optimizer, dataloader, batch_preprocessing_fn, log_interval=1)\n time_train = time.time() - st\n st = time.time()\n val_loss_curepoch = process_epoch('val', epoch, model, loss_fn,\n optimizer, dataloader_val, batch_preprocessing_fn, log_interval=1)\n time_valloss = time.time() - st\n st = time.time()\n val_pck_curepoch = pfdataset_pck(dataloader=dataloader_val_pck, model=\n model, verbose=False)\n time_valpck = time.time() - st\n train_loss[epoch - 1] = train_loss_curepoch\n val_loss[epoch - 1] = val_loss_curepoch\n val_pcks[epoch - 1] = val_pck_curepoch\n is_best = val_pcks[epoch - 1] > best_val_pck\n best_val_pck = max(val_pcks[epoch - 1], best_val_pck)\n save_checkpoint({'epoch': epoch, 'args': args, 'state_dict': model.\n state_dict(), 'optimizer': optimizer.state_dict(), 'train_loss':\n train_loss, 'val_loss': val_loss, 'val_pck': val_pcks,\n 'best_val_pck': best_val_pck}, is_best, checkpoint_name,\n save_all_epochs=False)\n message = (\n \"\"\"Epoch{}\tTrain_loss{:.6f}\tcost time{:.1f}\tVal_loss{:.6f}\tcost time{:.1f}\tVal_pck{:.6f}\tcost time{:.1f}\n\"\"\"\n .format(epoch, train_loss_curepoch, time_train, val_loss_curepoch,\n time_valloss, val_pck_curepoch, time_valpck))\n print(message)\n with open(log_name, 'a') as log_file:\n log_file.write('%s\\n' % message)\nprint('Done!')\n", "step-5": "from __future__ import print_function, division\nimport os\nfrom os.path import exists, join, basename, dirname\nfrom os import makedirs\nimport numpy as np\nimport datetime\nimport time\nimport argparse\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom lib.dataloader import DataLoader\nfrom lib.im_pair_dataset import ImagePairDataset\nfrom lib.normalization import NormalizeImageDict\nfrom lib.torch_util import save_checkpoint\nfrom lib.torch_util import BatchTensorToVars\nfrom lib.eval_util_dynamic import pfdataset_pck, pfpascal_val_dataloader\n\n# import DCCNet\nfrom models.model_dynamic import DCCNet\nfrom models.loss_dynamic import weak_loss\n\n\n# Seed and CUDA\nuse_cuda = torch.cuda.is_available()\ntorch.manual_seed(1)\nif use_cuda:\n torch.cuda.manual_seed(1)\nnp.random.seed(1)\n\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\n\nprint('DCCNet training script')\n\n# Argument parsing\nparser = argparse.ArgumentParser(description='Compute PF Pascal matches')\nparser.add_argument('--checkpoint', type=str, default='')\nparser.add_argument('--image_size', type=int, default=400)\nparser.add_argument('--dataset_image_path', type=str, default='datasets/pf-pascal/', help='path to PF Pascal dataset')\nparser.add_argument('--dataset_csv_path', type=str, default='datasets/pf-pascal/image_pairs/', help='path to PF Pascal training csv')\nparser.add_argument('--num_epochs', type=int, default=5, help='number of training epochs')\nparser.add_argument('--batch_size', type=int, default=16, help='training batch size')\nparser.add_argument('--lr', type=float, default=0.0005, help='learning rate')\nparser.add_argument('--result_model_fn', type=str, default='checkpoint_adam', help='trained model filename')\nparser.add_argument('--result-model-dir', type=str, default='../model/checkpoints', help='path to trained models folder')\nparser.add_argument('--fe_finetune_params', type=int, default=0, help='number of layers to finetune')\nparser.add_argument('--exp_name', type=str, default='exp_delete', help='experiment name')\n\n# DCCNet args\nparser.add_argument('--ncons_kernel_sizes', nargs='+', type=int, default=[5,5,5], help='kernels sizes in neigh. cons.')\nparser.add_argument('--ncons_channels', nargs='+', type=int, default=[16,16,1], help='channels in neigh. cons')\n\nparser.add_argument('--sce_kernel_size',type=int,default=25,help='kernel size in sce.')\nparser.add_argument('--sce_hidden_dim',type=int,default=1024,help='hidden dim in sce')\nparser.add_argument('--scaleloss_weight',type=float,default=1.0,help='whether use scale loss, if use the weight for scale loss')\nparser.add_argument('--att_scale_ncons_kernel_sizes', nargs='+', type=int, default=[5,5,5], help='kernels sizes in dynamic fusion net.')\nparser.add_argument('--att_scale_ncons_channels', nargs='+', type=int, default=[16,16,1], help='channels in dynamic fusion net')\n\nargs = parser.parse_args()\nprint(args)\n\n# Create model\nprint('Creating CNN model...')\nmodel = DCCNet(use_cuda=use_cuda,\n checkpoint=args.checkpoint,\n ncons_kernel_sizes=args.ncons_kernel_sizes,\n ncons_channels=args.ncons_channels,\n sce_kernel_size=args.sce_kernel_size,\n sce_hidden_dim=args.sce_hidden_dim,\n att_scale_ncons_kernel_sizes=args.att_scale_ncons_kernel_sizes,\n att_scale_ncons_channels=args.att_scale_ncons_channels,\n )\n\n#Multi-GPU support\nmodel = nn.DataParallel(model)\n\n# Set which parts of the model to train\nif args.fe_finetune_params>0:\n for i in range(args.fe_finetune_params):\n for p in model.module.FeatureExtraction.model[-1][-(i+1)].parameters():\n p.requires_grad=True\n\nprint('Trainable parameters:')\ncount = 0\nfor i,param in enumerate(model.named_parameters()):\n name,p = param\n if p.requires_grad:\n count+=1\n print(str(count)+\": \"+name+\"\\t\"+str(p.shape)+\"\\t\")\n\nprint(model)\n\n\n# Optimizer\nprint('using Adam optimizer')\noptimizer = optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr)\n \ncnn_image_size=(args.image_size,args.image_size)\n\nDataset = ImagePairDataset\ntrain_csv = 'train_pairs.csv'\n#val_pairs_nocoords.csv: for compute loss, with flip column in csv, no coordinates\n#val_pairs.csv: for compute pck, with coordinates\nval_nocoordinates_csv = 'val_pairs_nocoords.csv'\nval_csv = 'image_pairs/val_pairs.csv'\n\n\nnormalization_tnf = NormalizeImageDict(['source_image','target_image'])\nbatch_preprocessing_fn = BatchTensorToVars(use_cuda=use_cuda) \n\n# Dataset and dataloader\ndataset = Dataset(transform=normalization_tnf,\n\t dataset_image_path=args.dataset_image_path,\n\t dataset_csv_path=args.dataset_csv_path,\n dataset_csv_file = train_csv,\n output_size=cnn_image_size,\n )\n\ndataloader = DataLoader(dataset, batch_size=args.batch_size,\n shuffle=True, \n num_workers=0)\n\ndataset_val = Dataset(transform=normalization_tnf,\n dataset_image_path=args.dataset_image_path,\n dataset_csv_path=args.dataset_csv_path,\n dataset_csv_file=val_nocoordinates_csv,\n output_size=cnn_image_size)\n\n# compute val loss\ndataloader_val = DataLoader(dataset_val, batch_size=args.batch_size,\n shuffle=True, num_workers=4)\n\n# compute val pck\ndataloader_val_pck = pfpascal_val_dataloader(image_size=args.image_size, eval_dataset_path=args.dataset_image_path, csv_file=val_csv) #load pfpascal val dataset\n\n# Define checkpoint name\ncheckpoint_dir = os.path.join(args.result_model_dir,args.exp_name)\ncheckpoint_name = os.path.join(args.result_model_dir,args.exp_name,\n datetime.datetime.now().strftime(\"%Y-%m-%d_%H:%M\")+'_'+args.result_model_fn + '.pth.tar')\nlog_name = os.path.join(args.result_model_dir,args.exp_name, 'logmain_'+args.exp_name+'.txt')\nif not exists(dirname(log_name)):\n makedirs(dirname(log_name))\nprint('Checkpoint name: '+checkpoint_name)\n \n# Train\nbest_val_pck = float(\"-inf\")\n\nloss_fn = lambda model,batch: weak_loss(model, batch, normalization='softmax', scaleloss_weight=args.scaleloss_weight)\n\n# define epoch function\ndef process_epoch(mode,epoch,model,loss_fn,optimizer,dataloader,batch_preprocessing_fn,use_cuda=True,log_interval=50):\n epoch_loss = 0\n for batch_idx, batch in enumerate(dataloader):\n\n st = time.time()\n\n if mode=='train': \n optimizer.zero_grad()\n tnf_batch = batch_preprocessing_fn(batch)\n loss = loss_fn(model,tnf_batch)\n loss_np = loss.data.cpu().numpy()[0]\n #loss_np = loss.data.cpu().numpy()\n epoch_loss += loss_np\n if mode=='train':\n loss.backward()\n optimizer.step()\n else:\n loss=None\n if batch_idx % log_interval == 0:\n print(mode.capitalize()+' Epoch: {} [{}/{} ({:.0f}%)]\\t\\tLoss: {:.12f}\\t\\tcost time: {:.1f}'.format(\n epoch, batch_idx , len(dataloader),\n 100. * batch_idx / len(dataloader), loss_np,time.time()-st))\n epoch_loss /= len(dataloader)\n print(mode.capitalize()+' set: Average loss: {:.12f}'.format(epoch_loss))\n return epoch_loss\n\ntrain_loss = np.zeros(args.num_epochs)\nval_loss = np.zeros(args.num_epochs)\nval_pcks = np.zeros(args.num_epochs)\n\nmodel.module.FeatureExtraction.eval()\n\n\nprint('Starting training...')\nfor epoch in range(1, args.num_epochs+1):\n st = time.time()\n train_loss_curepoch = process_epoch('train',epoch,model,loss_fn,optimizer,dataloader,batch_preprocessing_fn,log_interval=1)\n time_train = time.time()-st\n\n st = time.time()\n\n val_loss_curepoch = process_epoch('val', epoch, model, loss_fn, optimizer, dataloader_val, batch_preprocessing_fn, log_interval=1)\n\n time_valloss = time.time()-st\n\n st = time.time()\n val_pck_curepoch = pfdataset_pck(dataloader=dataloader_val_pck,model=model,verbose=False)\n time_valpck = time.time()-st\n\n train_loss[epoch - 1] = train_loss_curepoch\n val_loss[epoch - 1] = val_loss_curepoch\n val_pcks[epoch-1] = val_pck_curepoch\n\n # remember best loss\n is_best = val_pcks[epoch - 1] > best_val_pck\n best_val_pck = max(val_pcks[epoch - 1], best_val_pck)\n save_checkpoint({\n 'epoch': epoch,\n 'args': args,\n 'state_dict': model.state_dict(),\n 'optimizer' : optimizer.state_dict(),\n 'train_loss': train_loss,\n 'val_loss': val_loss,\n 'val_pck': val_pcks,\n 'best_val_pck':best_val_pck,\n }, is_best,checkpoint_name,save_all_epochs=False)\n\n message = 'Epoch{}\\tTrain_loss{:.6f}\\tcost time{:.1f}\\tVal_loss{:.6f}\\tcost time{:.1f}\\tVal_pck{:.6f}\\tcost time{:.1f}\\n'.format\\\n (epoch, train_loss_curepoch, time_train, val_loss_curepoch, time_valloss,val_pck_curepoch,time_valpck,)\n print(message)\n with open(log_name, \"a\") as log_file:\n log_file.write('%s\\n' % message)\n\n\nprint('Done!')\n", "step-ids": [ 0, 2, 3, 4, 5 ] }
[ 0, 2, 3, 4, 5 ]
from tkinter import * root = Tk() root.title("Calculator") e = Entry(root, width = 50, borderwidth = 5) e.grid(row = 0, column = 0, columnspan = 4, padx = 10, pady = 20) def button_click(number): digit = e.get() e.delete(0, END) e.insert(0, str(digit) + str(number)) def button_add(): global first_num global math math = "addition" first_num = e.get() e.delete(0, END) def button_mul(): global first_num global math math = "multiplication" first_num = e.get() e.delete(0, END) def button_sub(): global first_num global math math = "subtraction" first_num = e.get() e.delete(0, END) def button_div(): global first_num global math math = "division" first_num = e.get() e.delete(0, END) def button_equal(): sec_num = e.get() e.delete(0, END) if math == "addition": e.insert(0, int(first_num) + int(sec_num)) if math == "multiplication": e.insert(0, int(first_num) * int(sec_num)) if math == "subtraction": e.insert(0, int(first_num) - int(sec_num)) if math == "division": e.insert(0, int(first_num) / int(sec_num)) def clear(): e.delete(0, END) #creating buttons button_1 = Button(root, text = "1", height = 5, width = 10,command = lambda:button_click(1)) button_2 = Button(root, text = "2", height = 5, width = 10, command = lambda:button_click(2)) button_3 = Button(root, text = "3", height = 5, width = 10, command = lambda:button_click(3)) button_4 = Button(root, text = "4", height = 5, width = 10, command = lambda:button_click(4)) button_5 = Button(root, text = "5", height = 5, width = 10, command = lambda:button_click(5)) button_6 = Button(root, text = "6", height = 5, width = 10, command = lambda:button_click(6)) button_7 = Button(root, text = "7", height = 5, width = 10, command = lambda:button_click(7)) button_8 = Button(root, text = "8", height = 5, width = 10, command = lambda:button_click(8)) button_9 = Button(root, text = "9", height = 5, width = 10, command = lambda:button_click(9)) button_0 = Button(root, text = "0", height = 5, width = 10, command = lambda:button_click(0)) button_add = Button(root, text = "+", height = 5, width = 10, bg = "#A1CAE2", command = button_add) button_mul = Button(root, text = "*", height = 5, width = 10, bg = "#A1CAE2", command = button_mul) button_sub = Button(root, text = "-", height = 5, width = 10, bg = "#A1CAE2", command = button_sub) button_div = Button(root, text = "/", height = 5, width = 10, bg = "#A1CAE2", command = button_div) button_equal = Button(root, text = "=", height = 5, width = 10, bg = "#A1CAE2", command = button_equal) button_clear = Button(root, text = "Clear", height = 5, width = 10, bg = "#A1CAE2", command = clear) #placing buttons button_1.grid(row = 3, column = 0) button_2.grid(row = 3, column = 1) button_3.grid(row = 3, column = 2) button_4.grid(row = 2, column = 0) button_5.grid(row = 2, column = 1) button_6.grid(row = 2, column = 2) button_7.grid(row = 1, column = 0) button_8.grid(row = 1, column = 1) button_9.grid(row = 1, column = 2) button_0.grid(row = 4, column = 0) button_add.grid(row = 4, column = 1) button_sub.grid(row = 1, column = 4) button_mul.grid(row = 2, column = 4) button_div.grid(row = 3, column = 4) button_equal.grid(row = 4, column = 2) button_clear.grid(row = 4, column = 4) root.mainloop()
normal
{ "blob_id": "59a75f78c7a146dcf55d43be90f71abce2bcf753", "index": 4934, "step-1": "<mask token>\n\n\ndef button_add():\n global first_num\n global math\n math = 'addition'\n first_num = e.get()\n e.delete(0, END)\n\n\n<mask token>\n\n\ndef button_sub():\n global first_num\n global math\n math = 'subtraction'\n first_num = e.get()\n e.delete(0, END)\n\n\ndef button_div():\n global first_num\n global math\n math = 'division'\n first_num = e.get()\n e.delete(0, END)\n\n\n<mask token>\n\n\ndef clear():\n e.delete(0, END)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef button_click(number):\n digit = e.get()\n e.delete(0, END)\n e.insert(0, str(digit) + str(number))\n\n\ndef button_add():\n global first_num\n global math\n math = 'addition'\n first_num = e.get()\n e.delete(0, END)\n\n\n<mask token>\n\n\ndef button_sub():\n global first_num\n global math\n math = 'subtraction'\n first_num = e.get()\n e.delete(0, END)\n\n\ndef button_div():\n global first_num\n global math\n math = 'division'\n first_num = e.get()\n e.delete(0, END)\n\n\n<mask token>\n\n\ndef clear():\n e.delete(0, END)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef button_click(number):\n digit = e.get()\n e.delete(0, END)\n e.insert(0, str(digit) + str(number))\n\n\ndef button_add():\n global first_num\n global math\n math = 'addition'\n first_num = e.get()\n e.delete(0, END)\n\n\ndef button_mul():\n global first_num\n global math\n math = 'multiplication'\n first_num = e.get()\n e.delete(0, END)\n\n\ndef button_sub():\n global first_num\n global math\n math = 'subtraction'\n first_num = e.get()\n e.delete(0, END)\n\n\ndef button_div():\n global first_num\n global math\n math = 'division'\n first_num = e.get()\n e.delete(0, END)\n\n\n<mask token>\n\n\ndef clear():\n e.delete(0, END)\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\ndef button_click(number):\n digit = e.get()\n e.delete(0, END)\n e.insert(0, str(digit) + str(number))\n\n\ndef button_add():\n global first_num\n global math\n math = 'addition'\n first_num = e.get()\n e.delete(0, END)\n\n\ndef button_mul():\n global first_num\n global math\n math = 'multiplication'\n first_num = e.get()\n e.delete(0, END)\n\n\ndef button_sub():\n global first_num\n global math\n math = 'subtraction'\n first_num = e.get()\n e.delete(0, END)\n\n\ndef button_div():\n global first_num\n global math\n math = 'division'\n first_num = e.get()\n e.delete(0, END)\n\n\ndef button_equal():\n sec_num = e.get()\n e.delete(0, END)\n if math == 'addition':\n e.insert(0, int(first_num) + int(sec_num))\n if math == 'multiplication':\n e.insert(0, int(first_num) * int(sec_num))\n if math == 'subtraction':\n e.insert(0, int(first_num) - int(sec_num))\n if math == 'division':\n e.insert(0, int(first_num) / int(sec_num))\n\n\ndef clear():\n e.delete(0, END)\n\n\n<mask token>\n", "step-5": "from tkinter import *\r\n\r\nroot = Tk()\r\nroot.title(\"Calculator\")\r\n\r\ne = Entry(root, width = 50, borderwidth = 5)\r\ne.grid(row = 0, column = 0, columnspan = 4, padx = 10, pady = 20)\r\n\r\ndef button_click(number):\r\n\tdigit = e.get()\r\n\te.delete(0, END)\r\n\te.insert(0, str(digit) + str(number))\r\n\r\ndef button_add():\r\n\tglobal first_num\r\n\tglobal math\r\n\tmath = \"addition\"\r\n\tfirst_num = e.get()\r\n\te.delete(0, END)\r\n\r\ndef button_mul():\r\n\tglobal first_num\r\n\tglobal math\r\n\tmath = \"multiplication\"\r\n\tfirst_num = e.get()\r\n\te.delete(0, END)\r\n\r\ndef button_sub():\r\n\tglobal first_num\r\n\tglobal math\r\n\tmath = \"subtraction\"\r\n\tfirst_num = e.get()\r\n\te.delete(0, END)\r\n\r\ndef button_div():\r\n\tglobal first_num\r\n\tglobal math\r\n\tmath = \"division\"\r\n\tfirst_num = e.get()\r\n\te.delete(0, END)\r\n\r\ndef button_equal():\t\r\n\tsec_num = e.get()\r\n\te.delete(0, END)\r\n\tif math == \"addition\":\r\n\t\te.insert(0, int(first_num) + int(sec_num))\r\n\tif math == \"multiplication\":\r\n\t\te.insert(0, int(first_num) * int(sec_num))\r\n\tif math == \"subtraction\":\r\n\t\te.insert(0, int(first_num) - int(sec_num))\r\n\tif math == \"division\":\r\n\t\te.insert(0, int(first_num) / int(sec_num))\r\n\r\ndef clear():\r\n\te.delete(0, END)\r\n\r\n\t\r\n#creating buttons\r\nbutton_1 = Button(root, text = \"1\", height = 5, width = 10,command = lambda:button_click(1))\r\nbutton_2 = Button(root, text = \"2\", height = 5, width = 10, command = lambda:button_click(2))\r\nbutton_3 = Button(root, text = \"3\", height = 5, width = 10, command = lambda:button_click(3))\r\nbutton_4 = Button(root, text = \"4\", height = 5, width = 10, command = lambda:button_click(4))\r\nbutton_5 = Button(root, text = \"5\", height = 5, width = 10, command = lambda:button_click(5))\r\nbutton_6 = Button(root, text = \"6\", height = 5, width = 10, command = lambda:button_click(6))\r\nbutton_7 = Button(root, text = \"7\", height = 5, width = 10, command = lambda:button_click(7))\r\nbutton_8 = Button(root, text = \"8\", height = 5, width = 10, command = lambda:button_click(8))\r\nbutton_9 = Button(root, text = \"9\", height = 5, width = 10, command = lambda:button_click(9))\r\nbutton_0 = Button(root, text = \"0\", height = 5, width = 10, command = lambda:button_click(0))\r\n\r\nbutton_add = Button(root, text = \"+\", height = 5, width = 10, bg = \"#A1CAE2\", command = button_add)\r\nbutton_mul = Button(root, text = \"*\", height = 5, width = 10, bg = \"#A1CAE2\", command = button_mul)\r\nbutton_sub = Button(root, text = \"-\", height = 5, width = 10, bg = \"#A1CAE2\", command = button_sub)\r\nbutton_div = Button(root, text = \"/\", height = 5, width = 10, bg = \"#A1CAE2\", command = button_div)\r\nbutton_equal = Button(root, text = \"=\", height = 5, width = 10, bg = \"#A1CAE2\", command = button_equal)\r\nbutton_clear = Button(root, text = \"Clear\", height = 5, width = 10, bg = \"#A1CAE2\", command = clear)\r\n\r\n#placing buttons\r\nbutton_1.grid(row = 3, column = 0)\r\nbutton_2.grid(row = 3, column = 1)\r\nbutton_3.grid(row = 3, column = 2)\r\nbutton_4.grid(row = 2, column = 0)\r\nbutton_5.grid(row = 2, column = 1)\r\nbutton_6.grid(row = 2, column = 2)\r\nbutton_7.grid(row = 1, column = 0)\r\nbutton_8.grid(row = 1, column = 1)\r\nbutton_9.grid(row = 1, column = 2)\r\nbutton_0.grid(row = 4, column = 0)\r\n\r\nbutton_add.grid(row = 4, column = 1)\r\nbutton_sub.grid(row = 1, column = 4)\r\nbutton_mul.grid(row = 2, column = 4)\r\nbutton_div.grid(row = 3, column = 4)\r\nbutton_equal.grid(row = 4, column = 2)\r\nbutton_clear.grid(row = 4, column = 4)\r\n\r\nroot.mainloop()", "step-ids": [ 4, 5, 6, 7, 11 ] }
[ 4, 5, 6, 7, 11 ]
import msvcrt import random import os def clear(): ''' It clears the screen.''' os.system('cls') def InitMatrix(): ''' It initializes the matrix as a board game.''' m = [[0 for i in range(4)] for j in range(4)] for i in range(2): x = random.randint(0, 3) y = random.randint(0, 3) while m[x][y] != 0: x = random.randint(0, 3) y = random.randint(0, 3) m[x][y] = 2 return m def ShowMatrix(): ''' It displays the matrix on the screen.''' for col in m: for elem in col: print("{:6d}".format(elem), end = " ") print() def MoveDown(): '''When the down key is pressed it computes to the bottom of the matrix the adjacent elements with the same value and moves the other elements in the same direction if there are empty cells.''' global movement for j in range(4): for i in range(3, -1, -1): x = i - 1 while x > -1: if m[i][j] != 0 and m[i][j] != m[x][j] and m[x][j] != 0: break elif m[x][j] == m[i][j] and m[i][j] != 0: aux = m[i][j] m[i][j] = m[x][j] + aux m[x][j] = 0 movement = True break elif m[i][j] == 0 and m[x][j] != 0: m[i][j] = m[x][j] m[x][j] = 0 movement = True x -= 1 def MoveUp(): '''It computes to the matrix upper side the adjacent elements with the same value and moves the other elements to the same side if there are empty cells when the up key is pressed.''' global movement for j in range(4): for i in range(3): x = i + 1 while x < 4: if m[i][j] != 0 and m[i][j] != m[x][j] and m[x][j] != 0: break elif m[x][j] == m[i][j] and m[i][j] != 0: aux = m[i][j] m[i][j] = m[x][j] + aux m[x][j] = 0 movement = True break elif m[i][j] == 0 and m[x][j] != 0: m[i][j] = m[x][j] m[x][j] = 0 movement = True x += 1 def MoveLeft(): '''It computes to the matrix left side the adjacent elements with the same value and moves the other elements to the same side if there are empty cells when the left key is pressed.''' global movement for i in range(4): for j in range(3): x = j + 1 while x < 4: if m[i][j] != 0 and m[i][j] != m[i][x] and m[i][x] != 0: break elif m[i][x] == m[i][j] and m[i][j] != 0: aux = m[i][j] m[i][j] = m[i][x] + aux m[i][x] = 0 movement = True break elif m[i][j] == 0 and m[i][x] != 0: m[i][j] = m[i][x] m[i][x] = 0 movement = True x += 1 def MoveRight(): ''' It computes to the matrix right side the adjacent elements with the same value and moves the other elements to the same side if there are empty cells when the right key is pressed.''' global movement for i in range(4): for j in range(3, -1, -1): x = j - 1 while x > -1: if m[i][j] != 0 and m[i][j] != m[i][x] and m[i][x] != 0: break elif m[i][x] == m[i][j] and m[i][j] != 0: aux = m[i][j] m[i][j] = m[i][x] + aux m[i][x] = 0 movement = True break elif m[i][j] == 0 and m[i][x] != 0: m[i][j] = m[i][x] m[i][x] = 0 movement = True x -= 1 def SupplyElem(): ''' It inserts a new element (2 or 4) in an random empty cell if at least the two adjacent elements have been computed or an element has been moved to a new cell.''' if movement == True: RandomElem() def RandomElem(): ''' It generates the position where the new element will be inserted.''' x = random.randint(0, 3) y = random.randint(0, 3) while m[x][y] != 0: x = random.randint(0, 3) y = random.randint(0, 3) m[x][y] = random.randrange(2, 5, 2) #=========================================================== m = InitMatrix() max_value = 2 while max_value <= 2048: movement = False clear() print("2048") ShowMatrix() keypress = ord(msvcrt.getch()) if keypress == 224: keypress = ord(msvcrt.getch()) if keypress == 75: MoveLeft() SupplyElem() if keypress == 72: MoveUp() SupplyElem() if keypress == 77: MoveRight() SupplyElem() if keypress == 80: MoveDown() SupplyElem() if keypress == 27: # ESC break min_value = min(map(min, m)) max_value = max(map(max, m)) if movement == False and min_value != 0: clear() print("\nYOU HAVE LOST!") print(f"\nSCORE: {max_value}") with open("Score.txt", "a") as scorefile: #don't forget to write the path of the directory where the Score file is stored scorefile.write(f" {str(max_value)}") with open("Score.txt", "r") as scorefile2: #don't forget to write the path of the directory where the Score file is stored score_read = scorefile2.read() list_score = score_read.split() list_score = [int(elem) for elem in list_score] print(f"\nHigh score: {max(list_score)}") quit() if max_value == 2048: print("\nYOU HAVE WON!") print(f"\nSCORE: {max_value}") with open("Score.txt", "a") as scorefile: #don't forget to write the path of the directory where the Score file is stored scorefile.write(f" {str(max_value)}") with open("Score.txt", "r") as scorefile2: #don't forget to write the path of the directory where the Score file is stored score_read = scorefile2.read() list_score = score_read.split() list_score = [int(elem) for elem in list_score] print(f"\nHigh score: {max(list_score)}") quit()
normal
{ "blob_id": "ab69f4d6afb96d86381bcf507d7810980446c6ea", "index": 6407, "step-1": "<mask token>\n\n\ndef MoveUp():\n \"\"\"It computes to the matrix upper side the adjacent elements with the same\n value and moves the other elements to the same side if there are empty cells\n when the up key is pressed.\"\"\"\n global movement\n for j in range(4):\n for i in range(3):\n x = i + 1\n while x < 4:\n if m[i][j] != 0 and m[i][j] != m[x][j] and m[x][j] != 0:\n break\n elif m[x][j] == m[i][j] and m[i][j] != 0:\n aux = m[i][j]\n m[i][j] = m[x][j] + aux\n m[x][j] = 0\n movement = True\n break\n elif m[i][j] == 0 and m[x][j] != 0:\n m[i][j] = m[x][j]\n m[x][j] = 0\n movement = True\n x += 1\n\n\ndef MoveLeft():\n \"\"\"It computes to the matrix left side the adjacent elements with the same\n value and moves the other elements to the same side if there are empty cells\n when the left key is pressed.\"\"\"\n global movement\n for i in range(4):\n for j in range(3):\n x = j + 1\n while x < 4:\n if m[i][j] != 0 and m[i][j] != m[i][x] and m[i][x] != 0:\n break\n elif m[i][x] == m[i][j] and m[i][j] != 0:\n aux = m[i][j]\n m[i][j] = m[i][x] + aux\n m[i][x] = 0\n movement = True\n break\n elif m[i][j] == 0 and m[i][x] != 0:\n m[i][j] = m[i][x]\n m[i][x] = 0\n movement = True\n x += 1\n\n\ndef MoveRight():\n \"\"\" It computes to the matrix right side the adjacent elements with the same\n value and moves the other elements to the same side if there are empty cells\n when the right key is pressed.\"\"\"\n global movement\n for i in range(4):\n for j in range(3, -1, -1):\n x = j - 1\n while x > -1:\n if m[i][j] != 0 and m[i][j] != m[i][x] and m[i][x] != 0:\n break\n elif m[i][x] == m[i][j] and m[i][j] != 0:\n aux = m[i][j]\n m[i][j] = m[i][x] + aux\n m[i][x] = 0\n movement = True\n break\n elif m[i][j] == 0 and m[i][x] != 0:\n m[i][j] = m[i][x]\n m[i][x] = 0\n movement = True\n x -= 1\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef InitMatrix():\n \"\"\" It initializes the matrix as a board game.\"\"\"\n m = [[(0) for i in range(4)] for j in range(4)]\n for i in range(2):\n x = random.randint(0, 3)\n y = random.randint(0, 3)\n while m[x][y] != 0:\n x = random.randint(0, 3)\n y = random.randint(0, 3)\n m[x][y] = 2\n return m\n\n\ndef ShowMatrix():\n \"\"\" It displays the matrix on the screen.\"\"\"\n for col in m:\n for elem in col:\n print('{:6d}'.format(elem), end=' ')\n print()\n\n\ndef MoveDown():\n \"\"\"When the down key is pressed it computes to the bottom of the matrix the\n adjacent elements with the same value and moves the other elements in the\n same direction if there are empty cells.\"\"\"\n global movement\n for j in range(4):\n for i in range(3, -1, -1):\n x = i - 1\n while x > -1:\n if m[i][j] != 0 and m[i][j] != m[x][j] and m[x][j] != 0:\n break\n elif m[x][j] == m[i][j] and m[i][j] != 0:\n aux = m[i][j]\n m[i][j] = m[x][j] + aux\n m[x][j] = 0\n movement = True\n break\n elif m[i][j] == 0 and m[x][j] != 0:\n m[i][j] = m[x][j]\n m[x][j] = 0\n movement = True\n x -= 1\n\n\ndef MoveUp():\n \"\"\"It computes to the matrix upper side the adjacent elements with the same\n value and moves the other elements to the same side if there are empty cells\n when the up key is pressed.\"\"\"\n global movement\n for j in range(4):\n for i in range(3):\n x = i + 1\n while x < 4:\n if m[i][j] != 0 and m[i][j] != m[x][j] and m[x][j] != 0:\n break\n elif m[x][j] == m[i][j] and m[i][j] != 0:\n aux = m[i][j]\n m[i][j] = m[x][j] + aux\n m[x][j] = 0\n movement = True\n break\n elif m[i][j] == 0 and m[x][j] != 0:\n m[i][j] = m[x][j]\n m[x][j] = 0\n movement = True\n x += 1\n\n\ndef MoveLeft():\n \"\"\"It computes to the matrix left side the adjacent elements with the same\n value and moves the other elements to the same side if there are empty cells\n when the left key is pressed.\"\"\"\n global movement\n for i in range(4):\n for j in range(3):\n x = j + 1\n while x < 4:\n if m[i][j] != 0 and m[i][j] != m[i][x] and m[i][x] != 0:\n break\n elif m[i][x] == m[i][j] and m[i][j] != 0:\n aux = m[i][j]\n m[i][j] = m[i][x] + aux\n m[i][x] = 0\n movement = True\n break\n elif m[i][j] == 0 and m[i][x] != 0:\n m[i][j] = m[i][x]\n m[i][x] = 0\n movement = True\n x += 1\n\n\ndef MoveRight():\n \"\"\" It computes to the matrix right side the adjacent elements with the same\n value and moves the other elements to the same side if there are empty cells\n when the right key is pressed.\"\"\"\n global movement\n for i in range(4):\n for j in range(3, -1, -1):\n x = j - 1\n while x > -1:\n if m[i][j] != 0 and m[i][j] != m[i][x] and m[i][x] != 0:\n break\n elif m[i][x] == m[i][j] and m[i][j] != 0:\n aux = m[i][j]\n m[i][j] = m[i][x] + aux\n m[i][x] = 0\n movement = True\n break\n elif m[i][j] == 0 and m[i][x] != 0:\n m[i][j] = m[i][x]\n m[i][x] = 0\n movement = True\n x -= 1\n\n\ndef SupplyElem():\n \"\"\" It inserts a new element (2 or 4) in an random empty cell if at least the two\n adjacent elements have been computed or an element has been moved to a new\n cell.\"\"\"\n if movement == True:\n RandomElem()\n\n\ndef RandomElem():\n \"\"\" It generates the position where the new element will be inserted.\"\"\"\n x = random.randint(0, 3)\n y = random.randint(0, 3)\n while m[x][y] != 0:\n x = random.randint(0, 3)\n y = random.randint(0, 3)\n m[x][y] = random.randrange(2, 5, 2)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef clear():\n \"\"\" It clears the screen.\"\"\"\n os.system('cls')\n\n\ndef InitMatrix():\n \"\"\" It initializes the matrix as a board game.\"\"\"\n m = [[(0) for i in range(4)] for j in range(4)]\n for i in range(2):\n x = random.randint(0, 3)\n y = random.randint(0, 3)\n while m[x][y] != 0:\n x = random.randint(0, 3)\n y = random.randint(0, 3)\n m[x][y] = 2\n return m\n\n\ndef ShowMatrix():\n \"\"\" It displays the matrix on the screen.\"\"\"\n for col in m:\n for elem in col:\n print('{:6d}'.format(elem), end=' ')\n print()\n\n\ndef MoveDown():\n \"\"\"When the down key is pressed it computes to the bottom of the matrix the\n adjacent elements with the same value and moves the other elements in the\n same direction if there are empty cells.\"\"\"\n global movement\n for j in range(4):\n for i in range(3, -1, -1):\n x = i - 1\n while x > -1:\n if m[i][j] != 0 and m[i][j] != m[x][j] and m[x][j] != 0:\n break\n elif m[x][j] == m[i][j] and m[i][j] != 0:\n aux = m[i][j]\n m[i][j] = m[x][j] + aux\n m[x][j] = 0\n movement = True\n break\n elif m[i][j] == 0 and m[x][j] != 0:\n m[i][j] = m[x][j]\n m[x][j] = 0\n movement = True\n x -= 1\n\n\ndef MoveUp():\n \"\"\"It computes to the matrix upper side the adjacent elements with the same\n value and moves the other elements to the same side if there are empty cells\n when the up key is pressed.\"\"\"\n global movement\n for j in range(4):\n for i in range(3):\n x = i + 1\n while x < 4:\n if m[i][j] != 0 and m[i][j] != m[x][j] and m[x][j] != 0:\n break\n elif m[x][j] == m[i][j] and m[i][j] != 0:\n aux = m[i][j]\n m[i][j] = m[x][j] + aux\n m[x][j] = 0\n movement = True\n break\n elif m[i][j] == 0 and m[x][j] != 0:\n m[i][j] = m[x][j]\n m[x][j] = 0\n movement = True\n x += 1\n\n\ndef MoveLeft():\n \"\"\"It computes to the matrix left side the adjacent elements with the same\n value and moves the other elements to the same side if there are empty cells\n when the left key is pressed.\"\"\"\n global movement\n for i in range(4):\n for j in range(3):\n x = j + 1\n while x < 4:\n if m[i][j] != 0 and m[i][j] != m[i][x] and m[i][x] != 0:\n break\n elif m[i][x] == m[i][j] and m[i][j] != 0:\n aux = m[i][j]\n m[i][j] = m[i][x] + aux\n m[i][x] = 0\n movement = True\n break\n elif m[i][j] == 0 and m[i][x] != 0:\n m[i][j] = m[i][x]\n m[i][x] = 0\n movement = True\n x += 1\n\n\ndef MoveRight():\n \"\"\" It computes to the matrix right side the adjacent elements with the same\n value and moves the other elements to the same side if there are empty cells\n when the right key is pressed.\"\"\"\n global movement\n for i in range(4):\n for j in range(3, -1, -1):\n x = j - 1\n while x > -1:\n if m[i][j] != 0 and m[i][j] != m[i][x] and m[i][x] != 0:\n break\n elif m[i][x] == m[i][j] and m[i][j] != 0:\n aux = m[i][j]\n m[i][j] = m[i][x] + aux\n m[i][x] = 0\n movement = True\n break\n elif m[i][j] == 0 and m[i][x] != 0:\n m[i][j] = m[i][x]\n m[i][x] = 0\n movement = True\n x -= 1\n\n\ndef SupplyElem():\n \"\"\" It inserts a new element (2 or 4) in an random empty cell if at least the two\n adjacent elements have been computed or an element has been moved to a new\n cell.\"\"\"\n if movement == True:\n RandomElem()\n\n\ndef RandomElem():\n \"\"\" It generates the position where the new element will be inserted.\"\"\"\n x = random.randint(0, 3)\n y = random.randint(0, 3)\n while m[x][y] != 0:\n x = random.randint(0, 3)\n y = random.randint(0, 3)\n m[x][y] = random.randrange(2, 5, 2)\n\n\n<mask token>\nwhile max_value <= 2048:\n movement = False\n clear()\n print('2048')\n ShowMatrix()\n keypress = ord(msvcrt.getch())\n if keypress == 224:\n keypress = ord(msvcrt.getch())\n if keypress == 75:\n MoveLeft()\n SupplyElem()\n if keypress == 72:\n MoveUp()\n SupplyElem()\n if keypress == 77:\n MoveRight()\n SupplyElem()\n if keypress == 80:\n MoveDown()\n SupplyElem()\n if keypress == 27:\n break\n min_value = min(map(min, m))\n max_value = max(map(max, m))\n if movement == False and min_value != 0:\n clear()\n print('\\nYOU HAVE LOST!')\n print(f'\\nSCORE: {max_value}')\n with open('Score.txt', 'a') as scorefile:\n scorefile.write(f' {str(max_value)}')\n with open('Score.txt', 'r') as scorefile2:\n score_read = scorefile2.read()\n list_score = score_read.split()\n list_score = [int(elem) for elem in list_score]\n print(f'\\nHigh score: {max(list_score)}')\n quit()\n if max_value == 2048:\n print('\\nYOU HAVE WON!')\n print(f'\\nSCORE: {max_value}')\n with open('Score.txt', 'a') as scorefile:\n scorefile.write(f' {str(max_value)}')\n with open('Score.txt', 'r') as scorefile2:\n score_read = scorefile2.read()\n list_score = score_read.split()\n list_score = [int(elem) for elem in list_score]\n print(f'\\nHigh score: {max(list_score)}')\n quit()\n", "step-4": "import msvcrt\nimport random\nimport os\n\n\ndef clear():\n \"\"\" It clears the screen.\"\"\"\n os.system('cls')\n\n\ndef InitMatrix():\n \"\"\" It initializes the matrix as a board game.\"\"\"\n m = [[(0) for i in range(4)] for j in range(4)]\n for i in range(2):\n x = random.randint(0, 3)\n y = random.randint(0, 3)\n while m[x][y] != 0:\n x = random.randint(0, 3)\n y = random.randint(0, 3)\n m[x][y] = 2\n return m\n\n\ndef ShowMatrix():\n \"\"\" It displays the matrix on the screen.\"\"\"\n for col in m:\n for elem in col:\n print('{:6d}'.format(elem), end=' ')\n print()\n\n\ndef MoveDown():\n \"\"\"When the down key is pressed it computes to the bottom of the matrix the\n adjacent elements with the same value and moves the other elements in the\n same direction if there are empty cells.\"\"\"\n global movement\n for j in range(4):\n for i in range(3, -1, -1):\n x = i - 1\n while x > -1:\n if m[i][j] != 0 and m[i][j] != m[x][j] and m[x][j] != 0:\n break\n elif m[x][j] == m[i][j] and m[i][j] != 0:\n aux = m[i][j]\n m[i][j] = m[x][j] + aux\n m[x][j] = 0\n movement = True\n break\n elif m[i][j] == 0 and m[x][j] != 0:\n m[i][j] = m[x][j]\n m[x][j] = 0\n movement = True\n x -= 1\n\n\ndef MoveUp():\n \"\"\"It computes to the matrix upper side the adjacent elements with the same\n value and moves the other elements to the same side if there are empty cells\n when the up key is pressed.\"\"\"\n global movement\n for j in range(4):\n for i in range(3):\n x = i + 1\n while x < 4:\n if m[i][j] != 0 and m[i][j] != m[x][j] and m[x][j] != 0:\n break\n elif m[x][j] == m[i][j] and m[i][j] != 0:\n aux = m[i][j]\n m[i][j] = m[x][j] + aux\n m[x][j] = 0\n movement = True\n break\n elif m[i][j] == 0 and m[x][j] != 0:\n m[i][j] = m[x][j]\n m[x][j] = 0\n movement = True\n x += 1\n\n\ndef MoveLeft():\n \"\"\"It computes to the matrix left side the adjacent elements with the same\n value and moves the other elements to the same side if there are empty cells\n when the left key is pressed.\"\"\"\n global movement\n for i in range(4):\n for j in range(3):\n x = j + 1\n while x < 4:\n if m[i][j] != 0 and m[i][j] != m[i][x] and m[i][x] != 0:\n break\n elif m[i][x] == m[i][j] and m[i][j] != 0:\n aux = m[i][j]\n m[i][j] = m[i][x] + aux\n m[i][x] = 0\n movement = True\n break\n elif m[i][j] == 0 and m[i][x] != 0:\n m[i][j] = m[i][x]\n m[i][x] = 0\n movement = True\n x += 1\n\n\ndef MoveRight():\n \"\"\" It computes to the matrix right side the adjacent elements with the same\n value and moves the other elements to the same side if there are empty cells\n when the right key is pressed.\"\"\"\n global movement\n for i in range(4):\n for j in range(3, -1, -1):\n x = j - 1\n while x > -1:\n if m[i][j] != 0 and m[i][j] != m[i][x] and m[i][x] != 0:\n break\n elif m[i][x] == m[i][j] and m[i][j] != 0:\n aux = m[i][j]\n m[i][j] = m[i][x] + aux\n m[i][x] = 0\n movement = True\n break\n elif m[i][j] == 0 and m[i][x] != 0:\n m[i][j] = m[i][x]\n m[i][x] = 0\n movement = True\n x -= 1\n\n\ndef SupplyElem():\n \"\"\" It inserts a new element (2 or 4) in an random empty cell if at least the two\n adjacent elements have been computed or an element has been moved to a new\n cell.\"\"\"\n if movement == True:\n RandomElem()\n\n\ndef RandomElem():\n \"\"\" It generates the position where the new element will be inserted.\"\"\"\n x = random.randint(0, 3)\n y = random.randint(0, 3)\n while m[x][y] != 0:\n x = random.randint(0, 3)\n y = random.randint(0, 3)\n m[x][y] = random.randrange(2, 5, 2)\n\n\nm = InitMatrix()\nmax_value = 2\nwhile max_value <= 2048:\n movement = False\n clear()\n print('2048')\n ShowMatrix()\n keypress = ord(msvcrt.getch())\n if keypress == 224:\n keypress = ord(msvcrt.getch())\n if keypress == 75:\n MoveLeft()\n SupplyElem()\n if keypress == 72:\n MoveUp()\n SupplyElem()\n if keypress == 77:\n MoveRight()\n SupplyElem()\n if keypress == 80:\n MoveDown()\n SupplyElem()\n if keypress == 27:\n break\n min_value = min(map(min, m))\n max_value = max(map(max, m))\n if movement == False and min_value != 0:\n clear()\n print('\\nYOU HAVE LOST!')\n print(f'\\nSCORE: {max_value}')\n with open('Score.txt', 'a') as scorefile:\n scorefile.write(f' {str(max_value)}')\n with open('Score.txt', 'r') as scorefile2:\n score_read = scorefile2.read()\n list_score = score_read.split()\n list_score = [int(elem) for elem in list_score]\n print(f'\\nHigh score: {max(list_score)}')\n quit()\n if max_value == 2048:\n print('\\nYOU HAVE WON!')\n print(f'\\nSCORE: {max_value}')\n with open('Score.txt', 'a') as scorefile:\n scorefile.write(f' {str(max_value)}')\n with open('Score.txt', 'r') as scorefile2:\n score_read = scorefile2.read()\n list_score = score_read.split()\n list_score = [int(elem) for elem in list_score]\n print(f'\\nHigh score: {max(list_score)}')\n quit()\n", "step-5": "import msvcrt\r\nimport random\r\nimport os\r\n\r\ndef clear():\r\n ''' It clears the screen.'''\r\n\r\n os.system('cls')\r\n\r\ndef InitMatrix():\r\n ''' It initializes the matrix as a board game.'''\r\n\r\n m = [[0 for i in range(4)] for j in range(4)]\r\n for i in range(2):\r\n x = random.randint(0, 3)\r\n y = random.randint(0, 3)\r\n while m[x][y] != 0:\r\n x = random.randint(0, 3)\r\n y = random.randint(0, 3)\r\n m[x][y] = 2\r\n\r\n return m\r\n\r\n\r\ndef ShowMatrix():\r\n ''' It displays the matrix on the screen.'''\r\n\r\n for col in m:\r\n for elem in col:\r\n print(\"{:6d}\".format(elem), end = \" \")\r\n print()\r\n\r\ndef MoveDown():\r\n '''When the down key is pressed it computes to the bottom of the matrix the\r\n adjacent elements with the same value and moves the other elements in the\r\n same direction if there are empty cells.'''\r\n\r\n global movement\r\n for j in range(4):\r\n for i in range(3, -1, -1):\r\n x = i - 1\r\n while x > -1:\r\n if m[i][j] != 0 and m[i][j] != m[x][j] and m[x][j] != 0:\r\n break\r\n elif m[x][j] == m[i][j] and m[i][j] != 0:\r\n aux = m[i][j]\r\n m[i][j] = m[x][j] + aux\r\n m[x][j] = 0\r\n movement = True\r\n break\r\n elif m[i][j] == 0 and m[x][j] != 0:\r\n m[i][j] = m[x][j]\r\n m[x][j] = 0\r\n movement = True\r\n x -= 1\r\n\r\n\r\ndef MoveUp():\r\n '''It computes to the matrix upper side the adjacent elements with the same\r\n value and moves the other elements to the same side if there are empty cells\r\n when the up key is pressed.'''\r\n\r\n global movement\r\n for j in range(4):\r\n for i in range(3):\r\n x = i + 1\r\n while x < 4:\r\n if m[i][j] != 0 and m[i][j] != m[x][j] and m[x][j] != 0:\r\n break\r\n elif m[x][j] == m[i][j] and m[i][j] != 0:\r\n aux = m[i][j]\r\n m[i][j] = m[x][j] + aux\r\n m[x][j] = 0\r\n movement = True\r\n break\r\n elif m[i][j] == 0 and m[x][j] != 0:\r\n m[i][j] = m[x][j]\r\n m[x][j] = 0\r\n movement = True\r\n x += 1\r\n\r\n\r\ndef MoveLeft():\r\n '''It computes to the matrix left side the adjacent elements with the same\r\n value and moves the other elements to the same side if there are empty cells\r\n when the left key is pressed.'''\r\n\r\n global movement\r\n for i in range(4):\r\n for j in range(3):\r\n x = j + 1\r\n while x < 4:\r\n if m[i][j] != 0 and m[i][j] != m[i][x] and m[i][x] != 0:\r\n break\r\n elif m[i][x] == m[i][j] and m[i][j] != 0:\r\n aux = m[i][j]\r\n m[i][j] = m[i][x] + aux\r\n m[i][x] = 0\r\n movement = True\r\n break\r\n elif m[i][j] == 0 and m[i][x] != 0:\r\n m[i][j] = m[i][x]\r\n m[i][x] = 0\r\n movement = True\r\n x += 1\r\n\r\n\r\ndef MoveRight():\r\n ''' It computes to the matrix right side the adjacent elements with the same\r\n value and moves the other elements to the same side if there are empty cells\r\n when the right key is pressed.'''\r\n\r\n global movement\r\n for i in range(4):\r\n for j in range(3, -1, -1):\r\n x = j - 1\r\n while x > -1:\r\n if m[i][j] != 0 and m[i][j] != m[i][x] and m[i][x] != 0:\r\n break\r\n elif m[i][x] == m[i][j] and m[i][j] != 0:\r\n aux = m[i][j]\r\n m[i][j] = m[i][x] + aux\r\n m[i][x] = 0\r\n movement = True\r\n break\r\n elif m[i][j] == 0 and m[i][x] != 0:\r\n m[i][j] = m[i][x]\r\n m[i][x] = 0\r\n movement = True\r\n x -= 1\r\n\r\ndef SupplyElem():\r\n ''' It inserts a new element (2 or 4) in an random empty cell if at least the two\r\n adjacent elements have been computed or an element has been moved to a new\r\n cell.'''\r\n\r\n if movement == True:\r\n RandomElem()\r\n\r\ndef RandomElem():\r\n ''' It generates the position where the new element will be inserted.'''\r\n\r\n x = random.randint(0, 3)\r\n y = random.randint(0, 3)\r\n while m[x][y] != 0:\r\n x = random.randint(0, 3)\r\n y = random.randint(0, 3)\r\n m[x][y] = random.randrange(2, 5, 2)\r\n\r\n#===========================================================\r\n\r\n\r\nm = InitMatrix()\r\nmax_value = 2\r\n\r\nwhile max_value <= 2048:\r\n\r\n movement = False\r\n clear()\r\n print(\"2048\")\r\n ShowMatrix()\r\n\r\n keypress = ord(msvcrt.getch())\r\n if keypress == 224:\r\n keypress = ord(msvcrt.getch())\r\n\r\n if keypress == 75:\r\n MoveLeft()\r\n SupplyElem()\r\n if keypress == 72:\r\n MoveUp()\r\n SupplyElem()\r\n if keypress == 77:\r\n MoveRight()\r\n SupplyElem()\r\n if keypress == 80:\r\n MoveDown()\r\n SupplyElem()\r\n if keypress == 27: # ESC\r\n break\r\n\r\n min_value = min(map(min, m))\r\n max_value = max(map(max, m))\r\n\r\n if movement == False and min_value != 0:\r\n clear()\r\n print(\"\\nYOU HAVE LOST!\")\r\n print(f\"\\nSCORE: {max_value}\")\r\n with open(\"Score.txt\", \"a\") as scorefile: #don't forget to write the path of the directory where the Score file is stored \r\n scorefile.write(f\" {str(max_value)}\")\r\n with open(\"Score.txt\", \"r\") as scorefile2: #don't forget to write the path of the directory where the Score file is stored \r\n score_read = scorefile2.read()\r\n list_score = score_read.split()\r\n list_score = [int(elem) for elem in list_score]\r\n print(f\"\\nHigh score: {max(list_score)}\")\r\n quit()\r\n\r\n if max_value == 2048:\r\n print(\"\\nYOU HAVE WON!\")\r\n print(f\"\\nSCORE: {max_value}\")\r\n with open(\"Score.txt\", \"a\") as scorefile: #don't forget to write the path of the directory where the Score file is stored \r\n scorefile.write(f\" {str(max_value)}\")\r\n with open(\"Score.txt\", \"r\") as scorefile2: #don't forget to write the path of the directory where the Score file is stored \r\n score_read = scorefile2.read()\r\n list_score = score_read.split()\r\n list_score = [int(elem) for elem in list_score]\r\n print(f\"\\nHigh score: {max(list_score)}\")\r\n quit()\r\n", "step-ids": [ 3, 8, 10, 12, 13 ] }
[ 3, 8, 10, 12, 13 ]
#!/bin/python3 def word_ladder(start_word, end_word, dictionary_file='words5.dict'): ''' Returns a list satisfying the following properties: 1. the first element is `start_word` 2. the last element is `end_word` 3. elements at index i and i+1 are `_adjacent` 4. all elements are entries in the `dictionary_file` file For example, running the command ``` word_ladder('stone','money') ``` may give the output ``` ['stone', 'shone', 'phone', 'phony', 'peony', 'penny', 'benny', 'bonny', 'boney', 'money'] ``` but the possible outputs are not unique, so you may also get the output ``` ['stone', 'shone', 'shote', 'shots', 'soots', 'hoots', 'hooty', 'hooey', 'honey', 'money'] ``` (We cannot use doctests here because the outputs are not unique.) Whenever it is impossible to generate a word ladder between the two words, the function returns `None`. HINT: See <https://github.com/mikeizbicki/cmc-csci046/issues/472> for a discussion about a common memory management bug that causes the generated word ladders to be too long in some cases. ''' def verify_word_ladder(ladder): ''' Returns True if each entry of the input list is adjacent to its neighbors; otherwise returns False. >>> verify_word_ladder(['stone', 'shone', 'phone', 'phony']) True >>> verify_word_ladder(['stone', 'shone', 'phony']) False ''' def _adjacent(word1, word2): ''' Returns True if the input words differ by only a single character; returns False otherwise. >>> _adjacent('phone','phony') True >>> _adjacent('stone','money') False '''
normal
{ "blob_id": "631323e79f4fb32611d7094af92cff8f923fa996", "index": 303, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef _adjacent(word1, word2):\n \"\"\"\n Returns True if the input words differ by only a single character;\n returns False otherwise.\n\n >>> _adjacent('phone','phony')\n True\n >>> _adjacent('stone','money')\n False\n \"\"\"\n", "step-3": "def word_ladder(start_word, end_word, dictionary_file='words5.dict'):\n \"\"\"\n Returns a list satisfying the following properties:\n\n 1. the first element is `start_word`\n 2. the last element is `end_word`\n 3. elements at index i and i+1 are `_adjacent`\n 4. all elements are entries in the `dictionary_file` file\n\n For example, running the command\n ```\n word_ladder('stone','money')\n ```\n may give the output\n ```\n ['stone', 'shone', 'phone', 'phony', 'peony', 'penny', 'benny', 'bonny', 'boney', 'money']\n ```\n but the possible outputs are not unique,\n so you may also get the output\n ```\n ['stone', 'shone', 'shote', 'shots', 'soots', 'hoots', 'hooty', 'hooey', 'honey', 'money']\n ```\n (We cannot use doctests here because the outputs are not unique.)\n\n Whenever it is impossible to generate a word ladder between the two words,\n the function returns `None`.\n\n HINT:\n See <https://github.com/mikeizbicki/cmc-csci046/issues/472> for a discussion about a common memory management bug that causes the generated word ladders to be too long in some cases.\n \"\"\"\n\n\n<mask token>\n\n\ndef _adjacent(word1, word2):\n \"\"\"\n Returns True if the input words differ by only a single character;\n returns False otherwise.\n\n >>> _adjacent('phone','phony')\n True\n >>> _adjacent('stone','money')\n False\n \"\"\"\n", "step-4": "def word_ladder(start_word, end_word, dictionary_file='words5.dict'):\n \"\"\"\n Returns a list satisfying the following properties:\n\n 1. the first element is `start_word`\n 2. the last element is `end_word`\n 3. elements at index i and i+1 are `_adjacent`\n 4. all elements are entries in the `dictionary_file` file\n\n For example, running the command\n ```\n word_ladder('stone','money')\n ```\n may give the output\n ```\n ['stone', 'shone', 'phone', 'phony', 'peony', 'penny', 'benny', 'bonny', 'boney', 'money']\n ```\n but the possible outputs are not unique,\n so you may also get the output\n ```\n ['stone', 'shone', 'shote', 'shots', 'soots', 'hoots', 'hooty', 'hooey', 'honey', 'money']\n ```\n (We cannot use doctests here because the outputs are not unique.)\n\n Whenever it is impossible to generate a word ladder between the two words,\n the function returns `None`.\n\n HINT:\n See <https://github.com/mikeizbicki/cmc-csci046/issues/472> for a discussion about a common memory management bug that causes the generated word ladders to be too long in some cases.\n \"\"\"\n\n\ndef verify_word_ladder(ladder):\n \"\"\"\n Returns True if each entry of the input list is adjacent to its neighbors;\n otherwise returns False.\n\n >>> verify_word_ladder(['stone', 'shone', 'phone', 'phony'])\n True\n >>> verify_word_ladder(['stone', 'shone', 'phony'])\n False\n \"\"\"\n\n\ndef _adjacent(word1, word2):\n \"\"\"\n Returns True if the input words differ by only a single character;\n returns False otherwise.\n\n >>> _adjacent('phone','phony')\n True\n >>> _adjacent('stone','money')\n False\n \"\"\"\n", "step-5": "#!/bin/python3\n\n\ndef word_ladder(start_word, end_word, dictionary_file='words5.dict'):\n '''\n Returns a list satisfying the following properties:\n\n 1. the first element is `start_word`\n 2. the last element is `end_word`\n 3. elements at index i and i+1 are `_adjacent`\n 4. all elements are entries in the `dictionary_file` file\n\n For example, running the command\n ```\n word_ladder('stone','money')\n ```\n may give the output\n ```\n ['stone', 'shone', 'phone', 'phony', 'peony', 'penny', 'benny', 'bonny', 'boney', 'money']\n ```\n but the possible outputs are not unique,\n so you may also get the output\n ```\n ['stone', 'shone', 'shote', 'shots', 'soots', 'hoots', 'hooty', 'hooey', 'honey', 'money']\n ```\n (We cannot use doctests here because the outputs are not unique.)\n\n Whenever it is impossible to generate a word ladder between the two words,\n the function returns `None`.\n\n HINT:\n See <https://github.com/mikeizbicki/cmc-csci046/issues/472> for a discussion about a common memory management bug that causes the generated word ladders to be too long in some cases.\n '''\n\n\ndef verify_word_ladder(ladder):\n '''\n Returns True if each entry of the input list is adjacent to its neighbors;\n otherwise returns False.\n\n >>> verify_word_ladder(['stone', 'shone', 'phone', 'phony'])\n True\n >>> verify_word_ladder(['stone', 'shone', 'phony'])\n False\n '''\n\n\ndef _adjacent(word1, word2):\n '''\n Returns True if the input words differ by only a single character;\n returns False otherwise.\n\n >>> _adjacent('phone','phony')\n True\n >>> _adjacent('stone','money')\n False\n '''\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def age_domain(url): try: w = whois.whois(url) if w: for l in w.expiration_date: d1 = datetime.date(l) print(d1) for l1 in w.creation_date: d2 = datetime.date(l1) print(d2) diff = (d1 - d2).days print(diff) if diff / 30 < 6: return 1 else: return 0 except: return -1 <|reserved_special_token_1|> from datetime import datetime import whois def age_domain(url): try: w = whois.whois(url) if w: for l in w.expiration_date: d1 = datetime.date(l) print(d1) for l1 in w.creation_date: d2 = datetime.date(l1) print(d2) diff = (d1 - d2).days print(diff) if diff / 30 < 6: return 1 else: return 0 except: return -1 <|reserved_special_token_1|> from datetime import datetime import whois def age_domain(url): try: w = whois.whois(url) if(w): for l in w.expiration_date: d1 = datetime.date(l) print(d1) for l1 in w.creation_date: d2 = datetime.date(l1) print(d2) diff = (d1 - d2).days print(diff) if ((diff / 30) < 6): return 1 else: return 0 except: return -1
flexible
{ "blob_id": "07d574060ded0d98734b4f184dcba7377b3a5480", "index": 685, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef age_domain(url):\n try:\n w = whois.whois(url)\n if w:\n for l in w.expiration_date:\n d1 = datetime.date(l)\n print(d1)\n for l1 in w.creation_date:\n d2 = datetime.date(l1)\n print(d2)\n diff = (d1 - d2).days\n print(diff)\n if diff / 30 < 6:\n return 1\n else:\n return 0\n except:\n return -1\n", "step-3": "from datetime import datetime\nimport whois\n\n\ndef age_domain(url):\n try:\n w = whois.whois(url)\n if w:\n for l in w.expiration_date:\n d1 = datetime.date(l)\n print(d1)\n for l1 in w.creation_date:\n d2 = datetime.date(l1)\n print(d2)\n diff = (d1 - d2).days\n print(diff)\n if diff / 30 < 6:\n return 1\n else:\n return 0\n except:\n return -1\n", "step-4": "from datetime import datetime\r\n\r\nimport whois\r\n\r\n\r\ndef age_domain(url):\r\n try:\r\n w = whois.whois(url)\r\n if(w):\r\n for l in w.expiration_date:\r\n d1 = datetime.date(l)\r\n print(d1)\r\n for l1 in w.creation_date:\r\n d2 = datetime.date(l1)\r\n print(d2)\r\n diff = (d1 - d2).days\r\n print(diff)\r\n if ((diff / 30) < 6):\r\n return 1\r\n else:\r\n return 0\r\n except:\r\n return -1\r\n\r\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> def getSyntheticData(n, d, k): mean = np.array([0] * d) alpha = 0.8 cov_diag = [(alpha ** i) for i in range(d)] covariance = np.diag(cov_diag) truth = np.sum(cov_diag[:k]) samples = np.random.multivariate_normal(mean, covariance, n) return [samples, covariance, truth] def oja_async(sample): sample = sample.reshape(d, 1) U = np.frombuffer(coef_shared) U = U.reshape(d, k) grad = np.dot(sample, np.dot(sample.T, U)) rate_shared[0] = rate_shared[0] + 1 U = U + learning_rate / rate_shared[0] * grad for i in range(d): for j in range(k): coef_shared[j + i * k] = U[i][j] U = np.linalg.qr(U)[0] if rate_shared[0] % T_freq == 0: error = truth - np.trace(np.dot(np.dot(U.T, covariance), U)) return [error, time()] <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def getSyntheticData(n, d, k): mean = np.array([0] * d) alpha = 0.8 cov_diag = [(alpha ** i) for i in range(d)] covariance = np.diag(cov_diag) truth = np.sum(cov_diag[:k]) samples = np.random.multivariate_normal(mean, covariance, n) return [samples, covariance, truth] def oja_async(sample): sample = sample.reshape(d, 1) U = np.frombuffer(coef_shared) U = U.reshape(d, k) grad = np.dot(sample, np.dot(sample.T, U)) rate_shared[0] = rate_shared[0] + 1 U = U + learning_rate / rate_shared[0] * grad for i in range(d): for j in range(k): coef_shared[j + i * k] = U[i][j] U = np.linalg.qr(U)[0] if rate_shared[0] % T_freq == 0: error = truth - np.trace(np.dot(np.dot(U.T, covariance), U)) return [error, time()] <|reserved_special_token_0|> def evaluate(model): data_train = data['train'] covariance_train = np.dot(data_train, data_train.T) / n truth_train = np.trace(covariance_train) error_train = truth_train - np.trace(np.dot(np.dot(model.T, covariance_train), model)) return error_train, error_train def ojaNormal(samples, k): errors = [] elapsed_times = [] start_time = time() U = np.random.randn(d, k) t = 0 for x in samples: t = t + 1 x = x.reshape(d, 1) U = U + np.dot(x, np.dot(x.T, U)) * learning_rate / t if t % T_freq == 0: U_proj = np.linalg.qr(U)[0] error = truth - np.trace(np.dot(np.dot(U_proj.T, covariance), U_proj)) errors.append(error) elapsed_times.append(time() - start_time) U_final = np.linalg.qr(U)[0] return [errors, elapsed_times] def plotEverything(errors_oja, times_oja, errors_hogwild_one, times_hogwild_one, errors_hogwild_two, times_hogwild_two, errors_hogwild_four, times_hogwild_four): plt.figure(0) plt.xlabel('Time (secs)') plt.ylabel('Error') plt.plot(times_oja, errors_oja) plt.plot(times_hogwild_one, errors_hogwild_one) plt.plot(times_hogwild_two, errors_hogwild_two) plt.plot(times_hogwild_four, errors_hogwild_four) plt.legend(('oja', 'hogwild, 1 process', 'hogwild 2 processes', 'hogwild, 4 processes')) plt.title('k = ' + str(k)) iterations_oja = range(1, len(errors_oja) + 1) iterations_hogwild_one = range(1, len(errors_hogwild_one) + 1) iterations_hogwild_two = range(1, len(errors_hogwild_two) + 1) iterations_hogwild_four = range(1, len(errors_hogwild_four) + 1) plt.figure(1) plt.xlabel('Iterations') plt.ylabel('Error') plt.plot(iterations_oja, errors_oja) plt.plot(iterations_hogwild_one, errors_hogwild_one) plt.plot(iterations_hogwild_two, errors_hogwild_two) plt.plot(iterations_hogwild_four, errors_hogwild_four) plt.legend(('oja', 'hogwild, 1 process', 'hogwild 2 processes', 'hogwild, 4 processes')) plt.title('k = ' + str(k)) plt.show() <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> d = 100 n = 100000 k = 10 learning_rate = 0.4 T_freq = 100 num_threads = 1 epochs = 1 Iterations = 10 def getSyntheticData(n, d, k): mean = np.array([0] * d) alpha = 0.8 cov_diag = [(alpha ** i) for i in range(d)] covariance = np.diag(cov_diag) truth = np.sum(cov_diag[:k]) samples = np.random.multivariate_normal(mean, covariance, n) return [samples, covariance, truth] def oja_async(sample): sample = sample.reshape(d, 1) U = np.frombuffer(coef_shared) U = U.reshape(d, k) grad = np.dot(sample, np.dot(sample.T, U)) rate_shared[0] = rate_shared[0] + 1 U = U + learning_rate / rate_shared[0] * grad for i in range(d): for j in range(k): coef_shared[j + i * k] = U[i][j] U = np.linalg.qr(U)[0] if rate_shared[0] % T_freq == 0: error = truth - np.trace(np.dot(np.dot(U.T, covariance), U)) return [error, time()] def hogwild(samples, k, num_threads): n = len(samples) d = len(samples[0]) st = time() p = Pool(num_threads) error_n_times = p.map(oja_async, samples) error_n_times_refined = [e_n_t for e_n_t in error_n_times if e_n_t != None] errors = [ent[0] for ent in error_n_times_refined] end_times = [ent[1] for ent in error_n_times_refined] times = [(et - st) for et in end_times] errors = [x for _, x in sorted(zip(times, errors))] times = sorted(times) n_t_freq = n / T_freq return [errors[:n_t_freq], times[:n_t_freq]] def evaluate(model): data_train = data['train'] covariance_train = np.dot(data_train, data_train.T) / n truth_train = np.trace(covariance_train) error_train = truth_train - np.trace(np.dot(np.dot(model.T, covariance_train), model)) return error_train, error_train def ojaNormal(samples, k): errors = [] elapsed_times = [] start_time = time() U = np.random.randn(d, k) t = 0 for x in samples: t = t + 1 x = x.reshape(d, 1) U = U + np.dot(x, np.dot(x.T, U)) * learning_rate / t if t % T_freq == 0: U_proj = np.linalg.qr(U)[0] error = truth - np.trace(np.dot(np.dot(U_proj.T, covariance), U_proj)) errors.append(error) elapsed_times.append(time() - start_time) U_final = np.linalg.qr(U)[0] return [errors, elapsed_times] def plotEverything(errors_oja, times_oja, errors_hogwild_one, times_hogwild_one, errors_hogwild_two, times_hogwild_two, errors_hogwild_four, times_hogwild_four): plt.figure(0) plt.xlabel('Time (secs)') plt.ylabel('Error') plt.plot(times_oja, errors_oja) plt.plot(times_hogwild_one, errors_hogwild_one) plt.plot(times_hogwild_two, errors_hogwild_two) plt.plot(times_hogwild_four, errors_hogwild_four) plt.legend(('oja', 'hogwild, 1 process', 'hogwild 2 processes', 'hogwild, 4 processes')) plt.title('k = ' + str(k)) iterations_oja = range(1, len(errors_oja) + 1) iterations_hogwild_one = range(1, len(errors_hogwild_one) + 1) iterations_hogwild_two = range(1, len(errors_hogwild_two) + 1) iterations_hogwild_four = range(1, len(errors_hogwild_four) + 1) plt.figure(1) plt.xlabel('Iterations') plt.ylabel('Error') plt.plot(iterations_oja, errors_oja) plt.plot(iterations_hogwild_one, errors_hogwild_one) plt.plot(iterations_hogwild_two, errors_hogwild_two) plt.plot(iterations_hogwild_four, errors_hogwild_four) plt.legend(('oja', 'hogwild, 1 process', 'hogwild 2 processes', 'hogwild, 4 processes')) plt.title('k = ' + str(k)) plt.show() [samples, covariance, truth] = getSyntheticData(n, d, k) total_samples = [] for i in range(epochs): total_samples.extend(samples) errors_oja_sum = [0] * n times_oja_sum = [0] * n errors_hogwild_sum_one = [0] * n times_hogwild_sum_one = [0] * n errors_hogwild_sum_two = [0] * n times_hogwild_sum_two = [0] * n errors_hogwild_sum_four = [0] * n times_hogwild_sum_four = [0] * n for t in range(Iterations): [errors_oja, times_oja] = ojaNormal(total_samples, k) errors_oja_sum = [(e_sum + e) for e_sum, e in zip(errors_oja_sum, errors_oja)] times_oja_sum = [(t_sum + t) for t_sum, t in zip(times_oja_sum, times_oja)] coef_shared = Array(c_double, np.random.randn(d, k).flat, lock=False) rate_shared = Array(c_double, [0], lock=False) [errors_hogwild_one, times_hogwild_one] = hogwild(total_samples, k, 1) coef_shared = Array(c_double, np.random.randn(d, k).flat, lock=False) rate_shared = Array(c_double, [0], lock=False) [errors_hogwild_two, times_hogwild_two] = hogwild(total_samples, k, 2) coef_shared = Array(c_double, np.random.randn(d, k).flat, lock=False) rate_shared = Array(c_double, [0], lock=False) [errors_hogwild_four, times_hogwild_four] = hogwild(total_samples, k, 4) errors_hogwild_sum_one = [(e_sum + e) for e_sum, e in zip( errors_hogwild_sum_one, errors_hogwild_one)] times_hogwild_sum_one = [(t_sum + t) for t_sum, t in zip( times_hogwild_sum_one, times_hogwild_one)] errors_hogwild_sum_two = [(e_sum + e) for e_sum, e in zip( errors_hogwild_sum_two, errors_hogwild_two)] times_hogwild_sum_two = [(t_sum + t) for t_sum, t in zip( times_hogwild_sum_two, times_hogwild_two)] errors_hogwild_sum_four = [(e_sum + e) for e_sum, e in zip( errors_hogwild_sum_four, errors_hogwild_four)] times_hogwild_sum_four = [(t_sum + t) for t_sum, t in zip( times_hogwild_sum_four, times_hogwild_four)] errors_oja_average = [(e / Iterations) for e in errors_oja_sum] times_oja_average = [(t / Iterations) for t in times_oja_sum] times_hogwild_average_one = [(t / Iterations) for t in times_hogwild_sum_one] errors_hogwild_average_one = [(e / Iterations) for e in errors_hogwild_sum_one] times_hogwild_average_two = [(t / Iterations) for t in times_hogwild_sum_two] errors_hogwild_average_two = [(e / Iterations) for e in errors_hogwild_sum_two] times_hogwild_average_four = [(t / Iterations) for t in times_hogwild_sum_four] errors_hogwild_average_four = [(e / Iterations) for e in errors_hogwild_sum_four] plotEverything(errors_oja_average, times_oja_average, errors_hogwild_average_one, times_hogwild_average_one, errors_hogwild_average_two, times_hogwild_average_two, errors_hogwild_average_four, times_hogwild_average_four) <|reserved_special_token_1|> import scipy.sparse from multiprocessing.sharedctypes import Array from ctypes import c_double import numpy as np from multiprocessing import Pool import matplotlib.pyplot as plt from time import time import scipy.io as sio import sys d = 100 n = 100000 k = 10 learning_rate = 0.4 T_freq = 100 num_threads = 1 epochs = 1 Iterations = 10 def getSyntheticData(n, d, k): mean = np.array([0] * d) alpha = 0.8 cov_diag = [(alpha ** i) for i in range(d)] covariance = np.diag(cov_diag) truth = np.sum(cov_diag[:k]) samples = np.random.multivariate_normal(mean, covariance, n) return [samples, covariance, truth] def oja_async(sample): sample = sample.reshape(d, 1) U = np.frombuffer(coef_shared) U = U.reshape(d, k) grad = np.dot(sample, np.dot(sample.T, U)) rate_shared[0] = rate_shared[0] + 1 U = U + learning_rate / rate_shared[0] * grad for i in range(d): for j in range(k): coef_shared[j + i * k] = U[i][j] U = np.linalg.qr(U)[0] if rate_shared[0] % T_freq == 0: error = truth - np.trace(np.dot(np.dot(U.T, covariance), U)) return [error, time()] def hogwild(samples, k, num_threads): n = len(samples) d = len(samples[0]) st = time() p = Pool(num_threads) error_n_times = p.map(oja_async, samples) error_n_times_refined = [e_n_t for e_n_t in error_n_times if e_n_t != None] errors = [ent[0] for ent in error_n_times_refined] end_times = [ent[1] for ent in error_n_times_refined] times = [(et - st) for et in end_times] errors = [x for _, x in sorted(zip(times, errors))] times = sorted(times) n_t_freq = n / T_freq return [errors[:n_t_freq], times[:n_t_freq]] def evaluate(model): data_train = data['train'] covariance_train = np.dot(data_train, data_train.T) / n truth_train = np.trace(covariance_train) error_train = truth_train - np.trace(np.dot(np.dot(model.T, covariance_train), model)) return error_train, error_train def ojaNormal(samples, k): errors = [] elapsed_times = [] start_time = time() U = np.random.randn(d, k) t = 0 for x in samples: t = t + 1 x = x.reshape(d, 1) U = U + np.dot(x, np.dot(x.T, U)) * learning_rate / t if t % T_freq == 0: U_proj = np.linalg.qr(U)[0] error = truth - np.trace(np.dot(np.dot(U_proj.T, covariance), U_proj)) errors.append(error) elapsed_times.append(time() - start_time) U_final = np.linalg.qr(U)[0] return [errors, elapsed_times] def plotEverything(errors_oja, times_oja, errors_hogwild_one, times_hogwild_one, errors_hogwild_two, times_hogwild_two, errors_hogwild_four, times_hogwild_four): plt.figure(0) plt.xlabel('Time (secs)') plt.ylabel('Error') plt.plot(times_oja, errors_oja) plt.plot(times_hogwild_one, errors_hogwild_one) plt.plot(times_hogwild_two, errors_hogwild_two) plt.plot(times_hogwild_four, errors_hogwild_four) plt.legend(('oja', 'hogwild, 1 process', 'hogwild 2 processes', 'hogwild, 4 processes')) plt.title('k = ' + str(k)) iterations_oja = range(1, len(errors_oja) + 1) iterations_hogwild_one = range(1, len(errors_hogwild_one) + 1) iterations_hogwild_two = range(1, len(errors_hogwild_two) + 1) iterations_hogwild_four = range(1, len(errors_hogwild_four) + 1) plt.figure(1) plt.xlabel('Iterations') plt.ylabel('Error') plt.plot(iterations_oja, errors_oja) plt.plot(iterations_hogwild_one, errors_hogwild_one) plt.plot(iterations_hogwild_two, errors_hogwild_two) plt.plot(iterations_hogwild_four, errors_hogwild_four) plt.legend(('oja', 'hogwild, 1 process', 'hogwild 2 processes', 'hogwild, 4 processes')) plt.title('k = ' + str(k)) plt.show() [samples, covariance, truth] = getSyntheticData(n, d, k) total_samples = [] for i in range(epochs): total_samples.extend(samples) errors_oja_sum = [0] * n times_oja_sum = [0] * n errors_hogwild_sum_one = [0] * n times_hogwild_sum_one = [0] * n errors_hogwild_sum_two = [0] * n times_hogwild_sum_two = [0] * n errors_hogwild_sum_four = [0] * n times_hogwild_sum_four = [0] * n for t in range(Iterations): [errors_oja, times_oja] = ojaNormal(total_samples, k) errors_oja_sum = [(e_sum + e) for e_sum, e in zip(errors_oja_sum, errors_oja)] times_oja_sum = [(t_sum + t) for t_sum, t in zip(times_oja_sum, times_oja)] coef_shared = Array(c_double, np.random.randn(d, k).flat, lock=False) rate_shared = Array(c_double, [0], lock=False) [errors_hogwild_one, times_hogwild_one] = hogwild(total_samples, k, 1) coef_shared = Array(c_double, np.random.randn(d, k).flat, lock=False) rate_shared = Array(c_double, [0], lock=False) [errors_hogwild_two, times_hogwild_two] = hogwild(total_samples, k, 2) coef_shared = Array(c_double, np.random.randn(d, k).flat, lock=False) rate_shared = Array(c_double, [0], lock=False) [errors_hogwild_four, times_hogwild_four] = hogwild(total_samples, k, 4) errors_hogwild_sum_one = [(e_sum + e) for e_sum, e in zip( errors_hogwild_sum_one, errors_hogwild_one)] times_hogwild_sum_one = [(t_sum + t) for t_sum, t in zip( times_hogwild_sum_one, times_hogwild_one)] errors_hogwild_sum_two = [(e_sum + e) for e_sum, e in zip( errors_hogwild_sum_two, errors_hogwild_two)] times_hogwild_sum_two = [(t_sum + t) for t_sum, t in zip( times_hogwild_sum_two, times_hogwild_two)] errors_hogwild_sum_four = [(e_sum + e) for e_sum, e in zip( errors_hogwild_sum_four, errors_hogwild_four)] times_hogwild_sum_four = [(t_sum + t) for t_sum, t in zip( times_hogwild_sum_four, times_hogwild_four)] errors_oja_average = [(e / Iterations) for e in errors_oja_sum] times_oja_average = [(t / Iterations) for t in times_oja_sum] times_hogwild_average_one = [(t / Iterations) for t in times_hogwild_sum_one] errors_hogwild_average_one = [(e / Iterations) for e in errors_hogwild_sum_one] times_hogwild_average_two = [(t / Iterations) for t in times_hogwild_sum_two] errors_hogwild_average_two = [(e / Iterations) for e in errors_hogwild_sum_two] times_hogwild_average_four = [(t / Iterations) for t in times_hogwild_sum_four] errors_hogwild_average_four = [(e / Iterations) for e in errors_hogwild_sum_four] plotEverything(errors_oja_average, times_oja_average, errors_hogwild_average_one, times_hogwild_average_one, errors_hogwild_average_two, times_hogwild_average_two, errors_hogwild_average_four, times_hogwild_average_four) <|reserved_special_token_1|> import scipy.sparse from multiprocessing.sharedctypes import Array from ctypes import c_double import numpy as np from multiprocessing import Pool import matplotlib.pyplot as plt from time import time import scipy.io as sio import sys # np.random.seed(1) d = 100 n = 100000 k=10 learning_rate = 0.4 T_freq = 100 num_threads = 1 epochs = 1 Iterations = 10 def getSyntheticData(n,d,k): mean = np.array([0] * d) alpha = 0.8 cov_diag = [alpha**i for i in range(d)] covariance = np.diag(cov_diag) truth = np.sum(cov_diag[:k]) samples = np.random.multivariate_normal(mean,covariance,n) return [samples,covariance,truth] def oja_async(sample): # print rate_shared[0] sample = sample.reshape(d,1) U = np.frombuffer(coef_shared) U = U.reshape(d,k) grad = np.dot(sample,np.dot(sample.T,U)) rate_shared[0] = rate_shared[0]+1 U = U + (learning_rate/rate_shared[0])*grad # U = U + (learning_rate/np.sqrt(rate_shared[0]))*grad for i in range(d): for j in range(k): coef_shared[j+i*k] = U[i][j] U= np.linalg.qr(U)[0] if rate_shared[0]%T_freq ==0: error = truth-np.trace(np.dot(np.dot(U.T,covariance),U)) return [error,time()] # else: # return None def hogwild(samples,k,num_threads): n = len(samples) d = len(samples[0]) st = time() # print num_threads p = Pool(num_threads) error_n_times = p.map(oja_async, samples) error_n_times_refined = [e_n_t for e_n_t in error_n_times if e_n_t!= None] # print error_n_times_refined; errors = [ent[0] for ent in error_n_times_refined] end_times = [ent[1] for ent in error_n_times_refined] times = [et - st for et in end_times] errors = [x for _,x in sorted(zip(times,errors))] times = sorted(times) n_t_freq = n/T_freq return [errors[:n_t_freq],times[:n_t_freq]] def evaluate(model): data_train = data["train"] # data_test = data["test"] covariance_train = np.dot(data_train,data_train.T)/n # covariance_test = np.dot(data_test,data_test.T)/n truth_train = np.trace(covariance_train) # truth_test = np.trace(covariance_test) # error_train = np.linalg.norm(data_train - np.dot(np.dot(model,model.T),data_train),"fro")/n # error_test = np.linalg.norm(data_test - np.dot(np.dot(model,model.T),data_test),"fro")/n error_train = truth_train - np.trace(np.dot(np.dot(model.T,covariance_train),model)) # error_test = truth_test - np.trace(np.dot(np.dot(model.T,covariance_test),model)) # return error_train, error_test return error_train, error_train def ojaNormal(samples,k): errors = [] elapsed_times = [] start_time = time() U = np.random.randn(d,k) # U = np.linalg.qr(U)[0] t = 0 for x in samples: t=t+1 x = x.reshape(d,1) U = U + (np.dot(x,np.dot(x.T,U)))*learning_rate/t if t%T_freq == 0: U_proj= np.linalg.qr(U)[0] # U = U_proj error = truth- np.trace(np.dot(np.dot(U_proj.T,covariance),U_proj)) errors.append(error) elapsed_times.append(time() - start_time) U_final = np.linalg.qr(U)[0] return [errors,elapsed_times] def plotEverything(errors_oja, times_oja,errors_hogwild_one, times_hogwild_one,errors_hogwild_two, times_hogwild_two,errors_hogwild_four, times_hogwild_four): plt.figure(0) plt.xlabel('Time (secs)') plt.ylabel('Error') plt.plot(times_oja,errors_oja) plt.plot(times_hogwild_one,errors_hogwild_one) plt.plot(times_hogwild_two,errors_hogwild_two) plt.plot(times_hogwild_four,errors_hogwild_four) plt.legend(("oja","hogwild, 1 process","hogwild 2 processes","hogwild, 4 processes")) # plt.legend(("oja","hogwild 2 processes","hogwild, 4 processes")) plt.title("k = "+str(k)) iterations_oja = range(1,len(errors_oja)+1) iterations_hogwild_one = range(1,len(errors_hogwild_one)+1) iterations_hogwild_two = range(1,len(errors_hogwild_two)+1) iterations_hogwild_four = range(1,len(errors_hogwild_four)+1) plt.figure(1) plt.xlabel('Iterations') plt.ylabel('Error') plt.plot(iterations_oja,errors_oja) plt.plot(iterations_hogwild_one,errors_hogwild_one) plt.plot(iterations_hogwild_two,errors_hogwild_two) plt.plot(iterations_hogwild_four,errors_hogwild_four) plt.legend(("oja","hogwild, 1 process","hogwild 2 processes","hogwild, 4 processes")) # plt.legend(("oja","hogwild 2 processes","hogwild, 4 processes")) plt.title("k = "+str(k)) plt.show() [samples,covariance,truth] = getSyntheticData(n,d,k) total_samples = [] for i in range(epochs): total_samples.extend(samples) errors_oja_sum = [0]*n times_oja_sum = [0]*n errors_hogwild_sum_one = [0]*n times_hogwild_sum_one = [0]*n errors_hogwild_sum_two = [0]*n times_hogwild_sum_two = [0]*n errors_hogwild_sum_four= [0]*n times_hogwild_sum_four = [0]*n for t in range(Iterations): [errors_oja, times_oja] = ojaNormal(total_samples,k) errors_oja_sum = [e_sum + e for (e_sum,e) in zip(errors_oja_sum,errors_oja)] times_oja_sum = [t_sum + t for (t_sum,t) in zip(times_oja_sum,times_oja)] coef_shared = Array(c_double, (np.random.randn(d,k).flat), lock=False) rate_shared = Array(c_double, [0], lock=False) [errors_hogwild_one, times_hogwild_one] = hogwild(total_samples,k,1) coef_shared = Array(c_double, (np.random.randn(d,k).flat), lock=False) rate_shared = Array(c_double, [0], lock=False) [errors_hogwild_two, times_hogwild_two] = hogwild(total_samples,k,2) coef_shared = Array(c_double, (np.random.randn(d,k).flat), lock=False) rate_shared = Array(c_double, [0], lock=False) [errors_hogwild_four, times_hogwild_four] = hogwild(total_samples,k,4) errors_hogwild_sum_one = [e_sum + e for (e_sum,e) in zip(errors_hogwild_sum_one,errors_hogwild_one)] times_hogwild_sum_one = [t_sum + t for (t_sum,t) in zip(times_hogwild_sum_one,times_hogwild_one)] errors_hogwild_sum_two = [e_sum + e for (e_sum,e) in zip(errors_hogwild_sum_two,errors_hogwild_two)] times_hogwild_sum_two = [t_sum + t for (t_sum,t) in zip(times_hogwild_sum_two,times_hogwild_two)] errors_hogwild_sum_four = [e_sum + e for (e_sum,e) in zip(errors_hogwild_sum_four,errors_hogwild_four)] times_hogwild_sum_four = [t_sum + t for (t_sum,t) in zip(times_hogwild_sum_four,times_hogwild_four)] errors_oja_average = [e/Iterations for e in errors_oja_sum] times_oja_average = [t/Iterations for t in times_oja_sum] times_hogwild_average_one = [t/Iterations for t in times_hogwild_sum_one] errors_hogwild_average_one = [e/Iterations for e in errors_hogwild_sum_one] times_hogwild_average_two = [t/Iterations for t in times_hogwild_sum_two] errors_hogwild_average_two = [e/Iterations for e in errors_hogwild_sum_two] times_hogwild_average_four = [t/Iterations for t in times_hogwild_sum_four] errors_hogwild_average_four = [e/Iterations for e in errors_hogwild_sum_four] plotEverything(errors_oja_average, times_oja_average,errors_hogwild_average_one, times_hogwild_average_one,errors_hogwild_average_two, times_hogwild_average_two,errors_hogwild_average_four, times_hogwild_average_four)
flexible
{ "blob_id": "bf04bf41f657a6ada4777fe5de98d6a68beda9d3", "index": 9769, "step-1": "<mask token>\n\n\ndef getSyntheticData(n, d, k):\n mean = np.array([0] * d)\n alpha = 0.8\n cov_diag = [(alpha ** i) for i in range(d)]\n covariance = np.diag(cov_diag)\n truth = np.sum(cov_diag[:k])\n samples = np.random.multivariate_normal(mean, covariance, n)\n return [samples, covariance, truth]\n\n\ndef oja_async(sample):\n sample = sample.reshape(d, 1)\n U = np.frombuffer(coef_shared)\n U = U.reshape(d, k)\n grad = np.dot(sample, np.dot(sample.T, U))\n rate_shared[0] = rate_shared[0] + 1\n U = U + learning_rate / rate_shared[0] * grad\n for i in range(d):\n for j in range(k):\n coef_shared[j + i * k] = U[i][j]\n U = np.linalg.qr(U)[0]\n if rate_shared[0] % T_freq == 0:\n error = truth - np.trace(np.dot(np.dot(U.T, covariance), U))\n return [error, time()]\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef getSyntheticData(n, d, k):\n mean = np.array([0] * d)\n alpha = 0.8\n cov_diag = [(alpha ** i) for i in range(d)]\n covariance = np.diag(cov_diag)\n truth = np.sum(cov_diag[:k])\n samples = np.random.multivariate_normal(mean, covariance, n)\n return [samples, covariance, truth]\n\n\ndef oja_async(sample):\n sample = sample.reshape(d, 1)\n U = np.frombuffer(coef_shared)\n U = U.reshape(d, k)\n grad = np.dot(sample, np.dot(sample.T, U))\n rate_shared[0] = rate_shared[0] + 1\n U = U + learning_rate / rate_shared[0] * grad\n for i in range(d):\n for j in range(k):\n coef_shared[j + i * k] = U[i][j]\n U = np.linalg.qr(U)[0]\n if rate_shared[0] % T_freq == 0:\n error = truth - np.trace(np.dot(np.dot(U.T, covariance), U))\n return [error, time()]\n\n\n<mask token>\n\n\ndef evaluate(model):\n data_train = data['train']\n covariance_train = np.dot(data_train, data_train.T) / n\n truth_train = np.trace(covariance_train)\n error_train = truth_train - np.trace(np.dot(np.dot(model.T,\n covariance_train), model))\n return error_train, error_train\n\n\ndef ojaNormal(samples, k):\n errors = []\n elapsed_times = []\n start_time = time()\n U = np.random.randn(d, k)\n t = 0\n for x in samples:\n t = t + 1\n x = x.reshape(d, 1)\n U = U + np.dot(x, np.dot(x.T, U)) * learning_rate / t\n if t % T_freq == 0:\n U_proj = np.linalg.qr(U)[0]\n error = truth - np.trace(np.dot(np.dot(U_proj.T, covariance),\n U_proj))\n errors.append(error)\n elapsed_times.append(time() - start_time)\n U_final = np.linalg.qr(U)[0]\n return [errors, elapsed_times]\n\n\ndef plotEverything(errors_oja, times_oja, errors_hogwild_one,\n times_hogwild_one, errors_hogwild_two, times_hogwild_two,\n errors_hogwild_four, times_hogwild_four):\n plt.figure(0)\n plt.xlabel('Time (secs)')\n plt.ylabel('Error')\n plt.plot(times_oja, errors_oja)\n plt.plot(times_hogwild_one, errors_hogwild_one)\n plt.plot(times_hogwild_two, errors_hogwild_two)\n plt.plot(times_hogwild_four, errors_hogwild_four)\n plt.legend(('oja', 'hogwild, 1 process', 'hogwild 2 processes',\n 'hogwild, 4 processes'))\n plt.title('k = ' + str(k))\n iterations_oja = range(1, len(errors_oja) + 1)\n iterations_hogwild_one = range(1, len(errors_hogwild_one) + 1)\n iterations_hogwild_two = range(1, len(errors_hogwild_two) + 1)\n iterations_hogwild_four = range(1, len(errors_hogwild_four) + 1)\n plt.figure(1)\n plt.xlabel('Iterations')\n plt.ylabel('Error')\n plt.plot(iterations_oja, errors_oja)\n plt.plot(iterations_hogwild_one, errors_hogwild_one)\n plt.plot(iterations_hogwild_two, errors_hogwild_two)\n plt.plot(iterations_hogwild_four, errors_hogwild_four)\n plt.legend(('oja', 'hogwild, 1 process', 'hogwild 2 processes',\n 'hogwild, 4 processes'))\n plt.title('k = ' + str(k))\n plt.show()\n\n\n<mask token>\n", "step-3": "<mask token>\nd = 100\nn = 100000\nk = 10\nlearning_rate = 0.4\nT_freq = 100\nnum_threads = 1\nepochs = 1\nIterations = 10\n\n\ndef getSyntheticData(n, d, k):\n mean = np.array([0] * d)\n alpha = 0.8\n cov_diag = [(alpha ** i) for i in range(d)]\n covariance = np.diag(cov_diag)\n truth = np.sum(cov_diag[:k])\n samples = np.random.multivariate_normal(mean, covariance, n)\n return [samples, covariance, truth]\n\n\ndef oja_async(sample):\n sample = sample.reshape(d, 1)\n U = np.frombuffer(coef_shared)\n U = U.reshape(d, k)\n grad = np.dot(sample, np.dot(sample.T, U))\n rate_shared[0] = rate_shared[0] + 1\n U = U + learning_rate / rate_shared[0] * grad\n for i in range(d):\n for j in range(k):\n coef_shared[j + i * k] = U[i][j]\n U = np.linalg.qr(U)[0]\n if rate_shared[0] % T_freq == 0:\n error = truth - np.trace(np.dot(np.dot(U.T, covariance), U))\n return [error, time()]\n\n\ndef hogwild(samples, k, num_threads):\n n = len(samples)\n d = len(samples[0])\n st = time()\n p = Pool(num_threads)\n error_n_times = p.map(oja_async, samples)\n error_n_times_refined = [e_n_t for e_n_t in error_n_times if e_n_t != None]\n errors = [ent[0] for ent in error_n_times_refined]\n end_times = [ent[1] for ent in error_n_times_refined]\n times = [(et - st) for et in end_times]\n errors = [x for _, x in sorted(zip(times, errors))]\n times = sorted(times)\n n_t_freq = n / T_freq\n return [errors[:n_t_freq], times[:n_t_freq]]\n\n\ndef evaluate(model):\n data_train = data['train']\n covariance_train = np.dot(data_train, data_train.T) / n\n truth_train = np.trace(covariance_train)\n error_train = truth_train - np.trace(np.dot(np.dot(model.T,\n covariance_train), model))\n return error_train, error_train\n\n\ndef ojaNormal(samples, k):\n errors = []\n elapsed_times = []\n start_time = time()\n U = np.random.randn(d, k)\n t = 0\n for x in samples:\n t = t + 1\n x = x.reshape(d, 1)\n U = U + np.dot(x, np.dot(x.T, U)) * learning_rate / t\n if t % T_freq == 0:\n U_proj = np.linalg.qr(U)[0]\n error = truth - np.trace(np.dot(np.dot(U_proj.T, covariance),\n U_proj))\n errors.append(error)\n elapsed_times.append(time() - start_time)\n U_final = np.linalg.qr(U)[0]\n return [errors, elapsed_times]\n\n\ndef plotEverything(errors_oja, times_oja, errors_hogwild_one,\n times_hogwild_one, errors_hogwild_two, times_hogwild_two,\n errors_hogwild_four, times_hogwild_four):\n plt.figure(0)\n plt.xlabel('Time (secs)')\n plt.ylabel('Error')\n plt.plot(times_oja, errors_oja)\n plt.plot(times_hogwild_one, errors_hogwild_one)\n plt.plot(times_hogwild_two, errors_hogwild_two)\n plt.plot(times_hogwild_four, errors_hogwild_four)\n plt.legend(('oja', 'hogwild, 1 process', 'hogwild 2 processes',\n 'hogwild, 4 processes'))\n plt.title('k = ' + str(k))\n iterations_oja = range(1, len(errors_oja) + 1)\n iterations_hogwild_one = range(1, len(errors_hogwild_one) + 1)\n iterations_hogwild_two = range(1, len(errors_hogwild_two) + 1)\n iterations_hogwild_four = range(1, len(errors_hogwild_four) + 1)\n plt.figure(1)\n plt.xlabel('Iterations')\n plt.ylabel('Error')\n plt.plot(iterations_oja, errors_oja)\n plt.plot(iterations_hogwild_one, errors_hogwild_one)\n plt.plot(iterations_hogwild_two, errors_hogwild_two)\n plt.plot(iterations_hogwild_four, errors_hogwild_four)\n plt.legend(('oja', 'hogwild, 1 process', 'hogwild 2 processes',\n 'hogwild, 4 processes'))\n plt.title('k = ' + str(k))\n plt.show()\n\n\n[samples, covariance, truth] = getSyntheticData(n, d, k)\ntotal_samples = []\nfor i in range(epochs):\n total_samples.extend(samples)\nerrors_oja_sum = [0] * n\ntimes_oja_sum = [0] * n\nerrors_hogwild_sum_one = [0] * n\ntimes_hogwild_sum_one = [0] * n\nerrors_hogwild_sum_two = [0] * n\ntimes_hogwild_sum_two = [0] * n\nerrors_hogwild_sum_four = [0] * n\ntimes_hogwild_sum_four = [0] * n\nfor t in range(Iterations):\n [errors_oja, times_oja] = ojaNormal(total_samples, k)\n errors_oja_sum = [(e_sum + e) for e_sum, e in zip(errors_oja_sum,\n errors_oja)]\n times_oja_sum = [(t_sum + t) for t_sum, t in zip(times_oja_sum, times_oja)]\n coef_shared = Array(c_double, np.random.randn(d, k).flat, lock=False)\n rate_shared = Array(c_double, [0], lock=False)\n [errors_hogwild_one, times_hogwild_one] = hogwild(total_samples, k, 1)\n coef_shared = Array(c_double, np.random.randn(d, k).flat, lock=False)\n rate_shared = Array(c_double, [0], lock=False)\n [errors_hogwild_two, times_hogwild_two] = hogwild(total_samples, k, 2)\n coef_shared = Array(c_double, np.random.randn(d, k).flat, lock=False)\n rate_shared = Array(c_double, [0], lock=False)\n [errors_hogwild_four, times_hogwild_four] = hogwild(total_samples, k, 4)\n errors_hogwild_sum_one = [(e_sum + e) for e_sum, e in zip(\n errors_hogwild_sum_one, errors_hogwild_one)]\n times_hogwild_sum_one = [(t_sum + t) for t_sum, t in zip(\n times_hogwild_sum_one, times_hogwild_one)]\n errors_hogwild_sum_two = [(e_sum + e) for e_sum, e in zip(\n errors_hogwild_sum_two, errors_hogwild_two)]\n times_hogwild_sum_two = [(t_sum + t) for t_sum, t in zip(\n times_hogwild_sum_two, times_hogwild_two)]\n errors_hogwild_sum_four = [(e_sum + e) for e_sum, e in zip(\n errors_hogwild_sum_four, errors_hogwild_four)]\n times_hogwild_sum_four = [(t_sum + t) for t_sum, t in zip(\n times_hogwild_sum_four, times_hogwild_four)]\nerrors_oja_average = [(e / Iterations) for e in errors_oja_sum]\ntimes_oja_average = [(t / Iterations) for t in times_oja_sum]\ntimes_hogwild_average_one = [(t / Iterations) for t in times_hogwild_sum_one]\nerrors_hogwild_average_one = [(e / Iterations) for e in errors_hogwild_sum_one]\ntimes_hogwild_average_two = [(t / Iterations) for t in times_hogwild_sum_two]\nerrors_hogwild_average_two = [(e / Iterations) for e in errors_hogwild_sum_two]\ntimes_hogwild_average_four = [(t / Iterations) for t in times_hogwild_sum_four]\nerrors_hogwild_average_four = [(e / Iterations) for e in\n errors_hogwild_sum_four]\nplotEverything(errors_oja_average, times_oja_average,\n errors_hogwild_average_one, times_hogwild_average_one,\n errors_hogwild_average_two, times_hogwild_average_two,\n errors_hogwild_average_four, times_hogwild_average_four)\n", "step-4": "import scipy.sparse\nfrom multiprocessing.sharedctypes import Array\nfrom ctypes import c_double\nimport numpy as np\nfrom multiprocessing import Pool\nimport matplotlib.pyplot as plt\nfrom time import time\nimport scipy.io as sio\nimport sys\nd = 100\nn = 100000\nk = 10\nlearning_rate = 0.4\nT_freq = 100\nnum_threads = 1\nepochs = 1\nIterations = 10\n\n\ndef getSyntheticData(n, d, k):\n mean = np.array([0] * d)\n alpha = 0.8\n cov_diag = [(alpha ** i) for i in range(d)]\n covariance = np.diag(cov_diag)\n truth = np.sum(cov_diag[:k])\n samples = np.random.multivariate_normal(mean, covariance, n)\n return [samples, covariance, truth]\n\n\ndef oja_async(sample):\n sample = sample.reshape(d, 1)\n U = np.frombuffer(coef_shared)\n U = U.reshape(d, k)\n grad = np.dot(sample, np.dot(sample.T, U))\n rate_shared[0] = rate_shared[0] + 1\n U = U + learning_rate / rate_shared[0] * grad\n for i in range(d):\n for j in range(k):\n coef_shared[j + i * k] = U[i][j]\n U = np.linalg.qr(U)[0]\n if rate_shared[0] % T_freq == 0:\n error = truth - np.trace(np.dot(np.dot(U.T, covariance), U))\n return [error, time()]\n\n\ndef hogwild(samples, k, num_threads):\n n = len(samples)\n d = len(samples[0])\n st = time()\n p = Pool(num_threads)\n error_n_times = p.map(oja_async, samples)\n error_n_times_refined = [e_n_t for e_n_t in error_n_times if e_n_t != None]\n errors = [ent[0] for ent in error_n_times_refined]\n end_times = [ent[1] for ent in error_n_times_refined]\n times = [(et - st) for et in end_times]\n errors = [x for _, x in sorted(zip(times, errors))]\n times = sorted(times)\n n_t_freq = n / T_freq\n return [errors[:n_t_freq], times[:n_t_freq]]\n\n\ndef evaluate(model):\n data_train = data['train']\n covariance_train = np.dot(data_train, data_train.T) / n\n truth_train = np.trace(covariance_train)\n error_train = truth_train - np.trace(np.dot(np.dot(model.T,\n covariance_train), model))\n return error_train, error_train\n\n\ndef ojaNormal(samples, k):\n errors = []\n elapsed_times = []\n start_time = time()\n U = np.random.randn(d, k)\n t = 0\n for x in samples:\n t = t + 1\n x = x.reshape(d, 1)\n U = U + np.dot(x, np.dot(x.T, U)) * learning_rate / t\n if t % T_freq == 0:\n U_proj = np.linalg.qr(U)[0]\n error = truth - np.trace(np.dot(np.dot(U_proj.T, covariance),\n U_proj))\n errors.append(error)\n elapsed_times.append(time() - start_time)\n U_final = np.linalg.qr(U)[0]\n return [errors, elapsed_times]\n\n\ndef plotEverything(errors_oja, times_oja, errors_hogwild_one,\n times_hogwild_one, errors_hogwild_two, times_hogwild_two,\n errors_hogwild_four, times_hogwild_four):\n plt.figure(0)\n plt.xlabel('Time (secs)')\n plt.ylabel('Error')\n plt.plot(times_oja, errors_oja)\n plt.plot(times_hogwild_one, errors_hogwild_one)\n plt.plot(times_hogwild_two, errors_hogwild_two)\n plt.plot(times_hogwild_four, errors_hogwild_four)\n plt.legend(('oja', 'hogwild, 1 process', 'hogwild 2 processes',\n 'hogwild, 4 processes'))\n plt.title('k = ' + str(k))\n iterations_oja = range(1, len(errors_oja) + 1)\n iterations_hogwild_one = range(1, len(errors_hogwild_one) + 1)\n iterations_hogwild_two = range(1, len(errors_hogwild_two) + 1)\n iterations_hogwild_four = range(1, len(errors_hogwild_four) + 1)\n plt.figure(1)\n plt.xlabel('Iterations')\n plt.ylabel('Error')\n plt.plot(iterations_oja, errors_oja)\n plt.plot(iterations_hogwild_one, errors_hogwild_one)\n plt.plot(iterations_hogwild_two, errors_hogwild_two)\n plt.plot(iterations_hogwild_four, errors_hogwild_four)\n plt.legend(('oja', 'hogwild, 1 process', 'hogwild 2 processes',\n 'hogwild, 4 processes'))\n plt.title('k = ' + str(k))\n plt.show()\n\n\n[samples, covariance, truth] = getSyntheticData(n, d, k)\ntotal_samples = []\nfor i in range(epochs):\n total_samples.extend(samples)\nerrors_oja_sum = [0] * n\ntimes_oja_sum = [0] * n\nerrors_hogwild_sum_one = [0] * n\ntimes_hogwild_sum_one = [0] * n\nerrors_hogwild_sum_two = [0] * n\ntimes_hogwild_sum_two = [0] * n\nerrors_hogwild_sum_four = [0] * n\ntimes_hogwild_sum_four = [0] * n\nfor t in range(Iterations):\n [errors_oja, times_oja] = ojaNormal(total_samples, k)\n errors_oja_sum = [(e_sum + e) for e_sum, e in zip(errors_oja_sum,\n errors_oja)]\n times_oja_sum = [(t_sum + t) for t_sum, t in zip(times_oja_sum, times_oja)]\n coef_shared = Array(c_double, np.random.randn(d, k).flat, lock=False)\n rate_shared = Array(c_double, [0], lock=False)\n [errors_hogwild_one, times_hogwild_one] = hogwild(total_samples, k, 1)\n coef_shared = Array(c_double, np.random.randn(d, k).flat, lock=False)\n rate_shared = Array(c_double, [0], lock=False)\n [errors_hogwild_two, times_hogwild_two] = hogwild(total_samples, k, 2)\n coef_shared = Array(c_double, np.random.randn(d, k).flat, lock=False)\n rate_shared = Array(c_double, [0], lock=False)\n [errors_hogwild_four, times_hogwild_four] = hogwild(total_samples, k, 4)\n errors_hogwild_sum_one = [(e_sum + e) for e_sum, e in zip(\n errors_hogwild_sum_one, errors_hogwild_one)]\n times_hogwild_sum_one = [(t_sum + t) for t_sum, t in zip(\n times_hogwild_sum_one, times_hogwild_one)]\n errors_hogwild_sum_two = [(e_sum + e) for e_sum, e in zip(\n errors_hogwild_sum_two, errors_hogwild_two)]\n times_hogwild_sum_two = [(t_sum + t) for t_sum, t in zip(\n times_hogwild_sum_two, times_hogwild_two)]\n errors_hogwild_sum_four = [(e_sum + e) for e_sum, e in zip(\n errors_hogwild_sum_four, errors_hogwild_four)]\n times_hogwild_sum_four = [(t_sum + t) for t_sum, t in zip(\n times_hogwild_sum_four, times_hogwild_four)]\nerrors_oja_average = [(e / Iterations) for e in errors_oja_sum]\ntimes_oja_average = [(t / Iterations) for t in times_oja_sum]\ntimes_hogwild_average_one = [(t / Iterations) for t in times_hogwild_sum_one]\nerrors_hogwild_average_one = [(e / Iterations) for e in errors_hogwild_sum_one]\ntimes_hogwild_average_two = [(t / Iterations) for t in times_hogwild_sum_two]\nerrors_hogwild_average_two = [(e / Iterations) for e in errors_hogwild_sum_two]\ntimes_hogwild_average_four = [(t / Iterations) for t in times_hogwild_sum_four]\nerrors_hogwild_average_four = [(e / Iterations) for e in\n errors_hogwild_sum_four]\nplotEverything(errors_oja_average, times_oja_average,\n errors_hogwild_average_one, times_hogwild_average_one,\n errors_hogwild_average_two, times_hogwild_average_two,\n errors_hogwild_average_four, times_hogwild_average_four)\n", "step-5": "import scipy.sparse\nfrom multiprocessing.sharedctypes import Array\nfrom ctypes import c_double\nimport numpy as np\nfrom multiprocessing import Pool\nimport matplotlib.pyplot as plt\nfrom time import time\nimport scipy.io as sio\nimport sys\n# np.random.seed(1)\n\n\n\nd = 100\nn = 100000\nk=10\nlearning_rate = 0.4\nT_freq = 100\nnum_threads = 1\nepochs = 1\nIterations = 10\n\ndef getSyntheticData(n,d,k):\n mean = np.array([0] * d)\n alpha = 0.8\n cov_diag = [alpha**i for i in range(d)]\n covariance = np.diag(cov_diag)\n truth = np.sum(cov_diag[:k]) \n samples = np.random.multivariate_normal(mean,covariance,n)\n return [samples,covariance,truth]\n\n\ndef oja_async(sample):\n # print rate_shared[0]\n sample = sample.reshape(d,1)\n U = np.frombuffer(coef_shared)\n U = U.reshape(d,k)\n grad = np.dot(sample,np.dot(sample.T,U))\n rate_shared[0] = rate_shared[0]+1\n U = U + (learning_rate/rate_shared[0])*grad\n # U = U + (learning_rate/np.sqrt(rate_shared[0]))*grad\n\n for i in range(d):\n for j in range(k):\n coef_shared[j+i*k] = U[i][j]\n\n U= np.linalg.qr(U)[0]\n if rate_shared[0]%T_freq ==0:\n error = truth-np.trace(np.dot(np.dot(U.T,covariance),U))\n return [error,time()]\n # else:\n # return None\n\ndef hogwild(samples,k,num_threads):\n n = len(samples)\n d = len(samples[0])\n\n st = time()\n # print num_threads\n p = Pool(num_threads) \n\n error_n_times = p.map(oja_async, samples)\n error_n_times_refined = [e_n_t for e_n_t in error_n_times if e_n_t!= None]\n # print error_n_times_refined;\n errors = [ent[0] for ent in error_n_times_refined]\n end_times = [ent[1] for ent in error_n_times_refined]\n times = [et - st for et in end_times]\n errors = [x for _,x in sorted(zip(times,errors))]\n times = sorted(times)\n\n n_t_freq = n/T_freq\n return [errors[:n_t_freq],times[:n_t_freq]]\n \n\n\ndef evaluate(model):\n data_train = data[\"train\"]\n# data_test = data[\"test\"]\n covariance_train = np.dot(data_train,data_train.T)/n\n# covariance_test = np.dot(data_test,data_test.T)/n\n truth_train = np.trace(covariance_train)\n# truth_test = np.trace(covariance_test)\n# error_train = np.linalg.norm(data_train - np.dot(np.dot(model,model.T),data_train),\"fro\")/n\n# error_test = np.linalg.norm(data_test - np.dot(np.dot(model,model.T),data_test),\"fro\")/n\n error_train = truth_train - np.trace(np.dot(np.dot(model.T,covariance_train),model))\n# error_test = truth_test - np.trace(np.dot(np.dot(model.T,covariance_test),model))\n# return error_train, error_test\n return error_train, error_train\n\ndef ojaNormal(samples,k):\n errors = []\n elapsed_times = []\n start_time = time()\n U = np.random.randn(d,k)\n # U = np.linalg.qr(U)[0]\n\n t = 0\n for x in samples:\n t=t+1\n x = x.reshape(d,1)\n U = U + (np.dot(x,np.dot(x.T,U)))*learning_rate/t\n if t%T_freq == 0:\n U_proj= np.linalg.qr(U)[0]\n # U = U_proj\n error = truth- np.trace(np.dot(np.dot(U_proj.T,covariance),U_proj))\n errors.append(error)\n elapsed_times.append(time() - start_time)\n\n U_final = np.linalg.qr(U)[0]\n return [errors,elapsed_times] \n\n\n\ndef plotEverything(errors_oja, times_oja,errors_hogwild_one, times_hogwild_one,errors_hogwild_two, times_hogwild_two,errors_hogwild_four, times_hogwild_four):\n plt.figure(0)\n plt.xlabel('Time (secs)')\n plt.ylabel('Error')\n plt.plot(times_oja,errors_oja)\n plt.plot(times_hogwild_one,errors_hogwild_one)\n plt.plot(times_hogwild_two,errors_hogwild_two)\n plt.plot(times_hogwild_four,errors_hogwild_four)\n plt.legend((\"oja\",\"hogwild, 1 process\",\"hogwild 2 processes\",\"hogwild, 4 processes\"))\n # plt.legend((\"oja\",\"hogwild 2 processes\",\"hogwild, 4 processes\"))\n plt.title(\"k = \"+str(k))\n\n iterations_oja = range(1,len(errors_oja)+1)\n iterations_hogwild_one = range(1,len(errors_hogwild_one)+1)\n iterations_hogwild_two = range(1,len(errors_hogwild_two)+1)\n iterations_hogwild_four = range(1,len(errors_hogwild_four)+1)\n plt.figure(1)\n plt.xlabel('Iterations')\n plt.ylabel('Error')\n plt.plot(iterations_oja,errors_oja)\n plt.plot(iterations_hogwild_one,errors_hogwild_one)\n plt.plot(iterations_hogwild_two,errors_hogwild_two)\n plt.plot(iterations_hogwild_four,errors_hogwild_four)\n plt.legend((\"oja\",\"hogwild, 1 process\",\"hogwild 2 processes\",\"hogwild, 4 processes\"))\n # plt.legend((\"oja\",\"hogwild 2 processes\",\"hogwild, 4 processes\"))\n plt.title(\"k = \"+str(k))\n plt.show()\n\n\n[samples,covariance,truth] = getSyntheticData(n,d,k)\ntotal_samples = []\n\nfor i in range(epochs):\n total_samples.extend(samples)\n\nerrors_oja_sum = [0]*n\ntimes_oja_sum = [0]*n\n\nerrors_hogwild_sum_one = [0]*n\ntimes_hogwild_sum_one = [0]*n\n\n\nerrors_hogwild_sum_two = [0]*n\ntimes_hogwild_sum_two = [0]*n\n\nerrors_hogwild_sum_four= [0]*n\ntimes_hogwild_sum_four = [0]*n\n\n\nfor t in range(Iterations):\n [errors_oja, times_oja] = ojaNormal(total_samples,k)\n\n errors_oja_sum = [e_sum + e for (e_sum,e) in zip(errors_oja_sum,errors_oja)]\n times_oja_sum = [t_sum + t for (t_sum,t) in zip(times_oja_sum,times_oja)]\n\n coef_shared = Array(c_double, \n (np.random.randn(d,k).flat),\n lock=False) \n rate_shared = Array(c_double, \n [0],\n lock=False) \n [errors_hogwild_one, times_hogwild_one] = hogwild(total_samples,k,1)\n\n coef_shared = Array(c_double, \n (np.random.randn(d,k).flat),\n lock=False) \n rate_shared = Array(c_double, \n [0],\n lock=False) \n [errors_hogwild_two, times_hogwild_two] = hogwild(total_samples,k,2)\n\n coef_shared = Array(c_double, \n (np.random.randn(d,k).flat),\n lock=False) \n rate_shared = Array(c_double, \n [0],\n lock=False) \n [errors_hogwild_four, times_hogwild_four] = hogwild(total_samples,k,4)\n\n\n errors_hogwild_sum_one = [e_sum + e for (e_sum,e) in zip(errors_hogwild_sum_one,errors_hogwild_one)]\n times_hogwild_sum_one = [t_sum + t for (t_sum,t) in zip(times_hogwild_sum_one,times_hogwild_one)]\n\n\n errors_hogwild_sum_two = [e_sum + e for (e_sum,e) in zip(errors_hogwild_sum_two,errors_hogwild_two)]\n times_hogwild_sum_two = [t_sum + t for (t_sum,t) in zip(times_hogwild_sum_two,times_hogwild_two)]\n\n errors_hogwild_sum_four = [e_sum + e for (e_sum,e) in zip(errors_hogwild_sum_four,errors_hogwild_four)]\n times_hogwild_sum_four = [t_sum + t for (t_sum,t) in zip(times_hogwild_sum_four,times_hogwild_four)]\n\nerrors_oja_average = [e/Iterations for e in errors_oja_sum]\ntimes_oja_average = [t/Iterations for t in times_oja_sum]\n\ntimes_hogwild_average_one = [t/Iterations for t in times_hogwild_sum_one]\nerrors_hogwild_average_one = [e/Iterations for e in errors_hogwild_sum_one]\n\ntimes_hogwild_average_two = [t/Iterations for t in times_hogwild_sum_two]\nerrors_hogwild_average_two = [e/Iterations for e in errors_hogwild_sum_two]\n\ntimes_hogwild_average_four = [t/Iterations for t in times_hogwild_sum_four]\nerrors_hogwild_average_four = [e/Iterations for e in errors_hogwild_sum_four]\nplotEverything(errors_oja_average, times_oja_average,errors_hogwild_average_one, times_hogwild_average_one,errors_hogwild_average_two, times_hogwild_average_two,errors_hogwild_average_four, times_hogwild_average_four)\n\n", "step-ids": [ 2, 5, 8, 9, 10 ] }
[ 2, 5, 8, 9, 10 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> parser.add_argument('-f', '-forward', required=True, help= 'forward sequencing files', nargs='+', action='store', dest='forward_files' ) parser.add_argument('-r', '-reverse', required=True, help= 'reverse sequencing files', nargs='+', action='store', dest='reverse_files' ) parser.add_argument('-s', '-segments', required=True, help= 'number of segments to split job into', action='store', dest= 'total_segments') parser.add_argument('-o', '-out', required=True, help= 'keyword for saving output files', action='store', dest='out') parser.add_argument('-c', '-cutoff', required=False, default=0, help= 'read count cutoff for barcodes to keep (default=0)', action='store', dest='cutoff') parser.add_argument('-b', '-barcode', required=False, default=31, help= 'length of barcode (default=31)', action='store', dest='barcode_length') parser.add_argument('-bq', '-bquality', required=False, default=53, help= 'ascii quality score cutoff for barcode (default=53)', action='store', dest='barcode_quality') parser.add_argument('-gdq', '-gdquality', required=False, default=55, help= 'ascii quality score cutoff for guide-donor (default=55)', action= 'store', dest='guide_donor_quality') <|reserved_special_token_0|> for file in args.forward_files: forward_lines.extend(gzip.open(file).readlines()) <|reserved_special_token_0|> for line in forward_quality: scores = [ord(i) for i in line[:BARCODE_LENGTH]] barcode_quality_scores.append(np.mean(scores)) <|reserved_special_token_0|> for line in forward_quality: scores = [ord(i) for i in line[BARCODE_LENGTH:]] forward_guide_donor_quality_scores.append(np.mean(scores)) <|reserved_special_token_0|> for file in args.reverse_files: reverse_lines.extend(gzip.open(file).readlines()) <|reserved_special_token_0|> for line in reverse_quality: scores = [ord(i) for i in line] reverse_guide_donor_quality_scores.append(np.mean(scores)) <|reserved_special_token_0|> if READ_COUNT_CUTOFF != 0: barcodes_to_keep = [key for key, count in Counter(barcodes).items() if count >= READ_COUNT_CUTOFF] keep_dict = {g: (True) for g in barcodes_to_keep} forward_sequence, reverse_sequence, barcodes = zip(*[(f, r, b) for f, r, b in zip(forward_sequence, reverse_sequence, barcodes) if b in keep_dict]) <|reserved_special_token_0|> pickle.dump(count_dict, pickle_out, protocol=2) pickle_out.close() <|reserved_special_token_0|> for segment in range(0, total_segments): start = int(LENGTH / total_segments * segment) if segment + 1 == total_segments: sub_barcodes_set = barcode_list[start:] else: stop = int(LENGTH / total_segments * (segment + 1)) sub_barcodes_set = barcode_list[start:stop] sub_barcodes_dict = {b: (True) for b in sub_barcodes_set} sub_forward, sub_reverse, sub_barcodes = zip(*[(f, r, b) for f, r, b in zip(forward_sequence, reverse_sequence, barcodes) if b in sub_barcodes_dict]) R1_dict, R2_dict = {}, {} for f, r, b in zip(sub_forward, sub_reverse, sub_barcodes): if b not in R1_dict and b not in R2_dict: R1_dict[b] = [f] R2_dict[b] = [r] else: R1_dict[b].append(f) R2_dict[b].append(r) pickle_out = open(OUTPUT_HEADER + '_' + str(segment) + '-' + str( total_segments) + '.R1_dict', 'wb') pickle.dump(R1_dict, pickle_out, protocol=2) pickle_out.close() pickle_out = open(OUTPUT_HEADER + '_' + str(segment) + '-' + str( total_segments) + '.R2_dict', 'wb') pickle.dump(R2_dict, pickle_out, protocol=2) pickle_out.close() <|reserved_special_token_1|> <|reserved_special_token_0|> parser = argparse.ArgumentParser() parser.add_argument('-f', '-forward', required=True, help= 'forward sequencing files', nargs='+', action='store', dest='forward_files' ) parser.add_argument('-r', '-reverse', required=True, help= 'reverse sequencing files', nargs='+', action='store', dest='reverse_files' ) parser.add_argument('-s', '-segments', required=True, help= 'number of segments to split job into', action='store', dest= 'total_segments') parser.add_argument('-o', '-out', required=True, help= 'keyword for saving output files', action='store', dest='out') parser.add_argument('-c', '-cutoff', required=False, default=0, help= 'read count cutoff for barcodes to keep (default=0)', action='store', dest='cutoff') parser.add_argument('-b', '-barcode', required=False, default=31, help= 'length of barcode (default=31)', action='store', dest='barcode_length') parser.add_argument('-bq', '-bquality', required=False, default=53, help= 'ascii quality score cutoff for barcode (default=53)', action='store', dest='barcode_quality') parser.add_argument('-gdq', '-gdquality', required=False, default=55, help= 'ascii quality score cutoff for guide-donor (default=55)', action= 'store', dest='guide_donor_quality') args = parser.parse_args() OUTPUT_HEADER = args.out READ_COUNT_CUTOFF = int(args.cutoff) BARCODE_LENGTH = int(args.barcode_length) BARCODE_QUALITY_CUTOFF = int(args.barcode_quality) GUIDE_DONOR_QUALITY_CUTOFF = int(args.guide_donor_quality) forward_lines = [] for file in args.forward_files: forward_lines.extend(gzip.open(file).readlines()) forward_sequence = [forward_lines[r] for r in range(1, len(forward_lines), 4)] forward_sequence = [l.decode('utf-8').replace('\n', '') for l in forward_sequence] forward_quality = [forward_lines[r] for r in range(3, len(forward_lines), 4)] forward_quality = [l.decode('utf-8').replace('\n', '') for l in forward_quality ] barcode_quality_scores = [] for line in forward_quality: scores = [ord(i) for i in line[:BARCODE_LENGTH]] barcode_quality_scores.append(np.mean(scores)) forward_guide_donor_quality_scores = [] for line in forward_quality: scores = [ord(i) for i in line[BARCODE_LENGTH:]] forward_guide_donor_quality_scores.append(np.mean(scores)) reverse_lines = [] for file in args.reverse_files: reverse_lines.extend(gzip.open(file).readlines()) reverse_sequence = [reverse_lines[r] for r in range(1, len(reverse_lines), 4)] reverse_sequence = [l.decode('utf-8').replace('\n', '') for l in reverse_sequence] reverse_quality = [reverse_lines[r] for r in range(3, len(reverse_lines), 4)] reverse_quality = [l.decode('utf-8').replace('\n', '') for l in reverse_quality ] reverse_guide_donor_quality_scores = [] for line in reverse_quality: scores = [ord(i) for i in line] reverse_guide_donor_quality_scores.append(np.mean(scores)) forward_sequence, reverse_sequence, barcodes = zip(*[(f, r, f[: BARCODE_LENGTH]) for f, r, fscore, fscore2, rscore in zip( forward_sequence, reverse_sequence, barcode_quality_scores, forward_guide_donor_quality_scores, reverse_guide_donor_quality_scores) if fscore >= BARCODE_QUALITY_CUTOFF and fscore2 >= GUIDE_DONOR_QUALITY_CUTOFF and rscore >= GUIDE_DONOR_QUALITY_CUTOFF]) if READ_COUNT_CUTOFF != 0: barcodes_to_keep = [key for key, count in Counter(barcodes).items() if count >= READ_COUNT_CUTOFF] keep_dict = {g: (True) for g in barcodes_to_keep} forward_sequence, reverse_sequence, barcodes = zip(*[(f, r, b) for f, r, b in zip(forward_sequence, reverse_sequence, barcodes) if b in keep_dict]) count_dict = dict(Counter(barcodes)) pickle_out = open(OUTPUT_HEADER + '.read_count_dict', 'wb') pickle.dump(count_dict, pickle_out, protocol=2) pickle_out.close() LENGTH = len(set(barcodes)) total_segments = int(args.total_segments) barcode_list = list(set(barcodes)) for segment in range(0, total_segments): start = int(LENGTH / total_segments * segment) if segment + 1 == total_segments: sub_barcodes_set = barcode_list[start:] else: stop = int(LENGTH / total_segments * (segment + 1)) sub_barcodes_set = barcode_list[start:stop] sub_barcodes_dict = {b: (True) for b in sub_barcodes_set} sub_forward, sub_reverse, sub_barcodes = zip(*[(f, r, b) for f, r, b in zip(forward_sequence, reverse_sequence, barcodes) if b in sub_barcodes_dict]) R1_dict, R2_dict = {}, {} for f, r, b in zip(sub_forward, sub_reverse, sub_barcodes): if b not in R1_dict and b not in R2_dict: R1_dict[b] = [f] R2_dict[b] = [r] else: R1_dict[b].append(f) R2_dict[b].append(r) pickle_out = open(OUTPUT_HEADER + '_' + str(segment) + '-' + str( total_segments) + '.R1_dict', 'wb') pickle.dump(R1_dict, pickle_out, protocol=2) pickle_out.close() pickle_out = open(OUTPUT_HEADER + '_' + str(segment) + '-' + str( total_segments) + '.R2_dict', 'wb') pickle.dump(R2_dict, pickle_out, protocol=2) pickle_out.close() <|reserved_special_token_1|> <|reserved_special_token_0|> from collections import Counter import argparse import gzip import numpy as np import pickle parser = argparse.ArgumentParser() parser.add_argument('-f', '-forward', required=True, help= 'forward sequencing files', nargs='+', action='store', dest='forward_files' ) parser.add_argument('-r', '-reverse', required=True, help= 'reverse sequencing files', nargs='+', action='store', dest='reverse_files' ) parser.add_argument('-s', '-segments', required=True, help= 'number of segments to split job into', action='store', dest= 'total_segments') parser.add_argument('-o', '-out', required=True, help= 'keyword for saving output files', action='store', dest='out') parser.add_argument('-c', '-cutoff', required=False, default=0, help= 'read count cutoff for barcodes to keep (default=0)', action='store', dest='cutoff') parser.add_argument('-b', '-barcode', required=False, default=31, help= 'length of barcode (default=31)', action='store', dest='barcode_length') parser.add_argument('-bq', '-bquality', required=False, default=53, help= 'ascii quality score cutoff for barcode (default=53)', action='store', dest='barcode_quality') parser.add_argument('-gdq', '-gdquality', required=False, default=55, help= 'ascii quality score cutoff for guide-donor (default=55)', action= 'store', dest='guide_donor_quality') args = parser.parse_args() OUTPUT_HEADER = args.out READ_COUNT_CUTOFF = int(args.cutoff) BARCODE_LENGTH = int(args.barcode_length) BARCODE_QUALITY_CUTOFF = int(args.barcode_quality) GUIDE_DONOR_QUALITY_CUTOFF = int(args.guide_donor_quality) forward_lines = [] for file in args.forward_files: forward_lines.extend(gzip.open(file).readlines()) forward_sequence = [forward_lines[r] for r in range(1, len(forward_lines), 4)] forward_sequence = [l.decode('utf-8').replace('\n', '') for l in forward_sequence] forward_quality = [forward_lines[r] for r in range(3, len(forward_lines), 4)] forward_quality = [l.decode('utf-8').replace('\n', '') for l in forward_quality ] barcode_quality_scores = [] for line in forward_quality: scores = [ord(i) for i in line[:BARCODE_LENGTH]] barcode_quality_scores.append(np.mean(scores)) forward_guide_donor_quality_scores = [] for line in forward_quality: scores = [ord(i) for i in line[BARCODE_LENGTH:]] forward_guide_donor_quality_scores.append(np.mean(scores)) reverse_lines = [] for file in args.reverse_files: reverse_lines.extend(gzip.open(file).readlines()) reverse_sequence = [reverse_lines[r] for r in range(1, len(reverse_lines), 4)] reverse_sequence = [l.decode('utf-8').replace('\n', '') for l in reverse_sequence] reverse_quality = [reverse_lines[r] for r in range(3, len(reverse_lines), 4)] reverse_quality = [l.decode('utf-8').replace('\n', '') for l in reverse_quality ] reverse_guide_donor_quality_scores = [] for line in reverse_quality: scores = [ord(i) for i in line] reverse_guide_donor_quality_scores.append(np.mean(scores)) forward_sequence, reverse_sequence, barcodes = zip(*[(f, r, f[: BARCODE_LENGTH]) for f, r, fscore, fscore2, rscore in zip( forward_sequence, reverse_sequence, barcode_quality_scores, forward_guide_donor_quality_scores, reverse_guide_donor_quality_scores) if fscore >= BARCODE_QUALITY_CUTOFF and fscore2 >= GUIDE_DONOR_QUALITY_CUTOFF and rscore >= GUIDE_DONOR_QUALITY_CUTOFF]) if READ_COUNT_CUTOFF != 0: barcodes_to_keep = [key for key, count in Counter(barcodes).items() if count >= READ_COUNT_CUTOFF] keep_dict = {g: (True) for g in barcodes_to_keep} forward_sequence, reverse_sequence, barcodes = zip(*[(f, r, b) for f, r, b in zip(forward_sequence, reverse_sequence, barcodes) if b in keep_dict]) count_dict = dict(Counter(barcodes)) pickle_out = open(OUTPUT_HEADER + '.read_count_dict', 'wb') pickle.dump(count_dict, pickle_out, protocol=2) pickle_out.close() LENGTH = len(set(barcodes)) total_segments = int(args.total_segments) barcode_list = list(set(barcodes)) for segment in range(0, total_segments): start = int(LENGTH / total_segments * segment) if segment + 1 == total_segments: sub_barcodes_set = barcode_list[start:] else: stop = int(LENGTH / total_segments * (segment + 1)) sub_barcodes_set = barcode_list[start:stop] sub_barcodes_dict = {b: (True) for b in sub_barcodes_set} sub_forward, sub_reverse, sub_barcodes = zip(*[(f, r, b) for f, r, b in zip(forward_sequence, reverse_sequence, barcodes) if b in sub_barcodes_dict]) R1_dict, R2_dict = {}, {} for f, r, b in zip(sub_forward, sub_reverse, sub_barcodes): if b not in R1_dict and b not in R2_dict: R1_dict[b] = [f] R2_dict[b] = [r] else: R1_dict[b].append(f) R2_dict[b].append(r) pickle_out = open(OUTPUT_HEADER + '_' + str(segment) + '-' + str( total_segments) + '.R1_dict', 'wb') pickle.dump(R1_dict, pickle_out, protocol=2) pickle_out.close() pickle_out = open(OUTPUT_HEADER + '_' + str(segment) + '-' + str( total_segments) + '.R2_dict', 'wb') pickle.dump(R2_dict, pickle_out, protocol=2) pickle_out.close() <|reserved_special_token_1|> """ Process pair-end reads of barcode-guide-donor Step 1 cassette to generate a library reference table mapping barcodes to features. Create dictionaries mapping barcodes to forward and reverse reads, split into sub-segments. R1_dict: map barcodes to corresponding R1 sequences. R2_dict: map barcodes to corresponding R2 sequences. read_count_dict: map each barcode to corresponding total number of reads. """ from collections import Counter import argparse import gzip import numpy as np import pickle parser = argparse.ArgumentParser() parser.add_argument('-f', '-forward', required=True, help="forward sequencing files", nargs='+', action='store', dest='forward_files') parser.add_argument('-r', '-reverse', required=True, help="reverse sequencing files", nargs='+', action='store', dest='reverse_files') parser.add_argument('-s', '-segments', required=True, help="number of segments to split job into", action='store', dest='total_segments') parser.add_argument('-o', '-out', required=True, help="keyword for saving output files", action='store', dest='out') parser.add_argument('-c', '-cutoff', required=False, default=0, help="read count cutoff for barcodes to keep (default=0)", action='store', dest='cutoff') parser.add_argument('-b', '-barcode', required=False, default=31, help="length of barcode (default=31)", action='store', dest='barcode_length') parser.add_argument('-bq', '-bquality', required=False, default=53, help="ascii quality score cutoff for barcode (default=53)", action='store', dest='barcode_quality') parser.add_argument('-gdq', '-gdquality', required=False, default=55, help="ascii quality score cutoff for guide-donor (default=55)", action='store', dest='guide_donor_quality') args = parser.parse_args() OUTPUT_HEADER = args.out READ_COUNT_CUTOFF = int(args.cutoff) BARCODE_LENGTH = int(args.barcode_length) BARCODE_QUALITY_CUTOFF = int(args.barcode_quality) GUIDE_DONOR_QUALITY_CUTOFF = int(args.guide_donor_quality) # Collect all sequencing reads from forward files. forward_lines = [] for file in args.forward_files: forward_lines.extend(gzip.open(file).readlines()) # Forward sequence. forward_sequence = [forward_lines[r] for r in range(1, len(forward_lines), 4)] forward_sequence = [l.decode('utf-8').replace("\n","") for l in forward_sequence] # Forward sequence quality scores. forward_quality = [forward_lines[r] for r in range(3, len(forward_lines), 4)] forward_quality = [l.decode('utf-8').replace("\n","") for l in forward_quality] barcode_quality_scores = [] # Barcode quality. for line in forward_quality: scores = [ord(i) for i in line[:BARCODE_LENGTH]] barcode_quality_scores.append(np.mean(scores)) forward_guide_donor_quality_scores = [] # Guide-donor quality. for line in forward_quality: scores = [ord(i) for i in line[BARCODE_LENGTH:]] forward_guide_donor_quality_scores.append(np.mean(scores)) # Collect all sequencing reads from reverse files. reverse_lines = [] for file in args.reverse_files: reverse_lines.extend(gzip.open(file).readlines()) # Reverse sequence. reverse_sequence = [reverse_lines[r] for r in range(1, len(reverse_lines), 4)] reverse_sequence = [l.decode('utf-8').replace("\n","") for l in reverse_sequence] # Reverse sequence base quality scores. reverse_quality = [reverse_lines[r] for r in range(3, len(reverse_lines), 4)] reverse_quality = [l.decode('utf-8').replace("\n","") for l in reverse_quality] reverse_guide_donor_quality_scores = [] for line in reverse_quality: scores = [ord(i) for i in line] reverse_guide_donor_quality_scores.append(np.mean(scores)) # Filter out low quality barcodes and low quality guide-donor sequences. forward_sequence, reverse_sequence, barcodes = zip(*[(f, r, f[:BARCODE_LENGTH]) for f, r, fscore, fscore2, rscore in zip(forward_sequence, reverse_sequence, barcode_quality_scores, forward_guide_donor_quality_scores, reverse_guide_donor_quality_scores) if (fscore >= BARCODE_QUALITY_CUTOFF) and (fscore2 >= GUIDE_DONOR_QUALITY_CUTOFF) and (rscore >= GUIDE_DONOR_QUALITY_CUTOFF)]) if (READ_COUNT_CUTOFF != 0): # optional choice to remove low read barcodes from annotations. barcodes_to_keep = [key for key, count in Counter(barcodes).items() if count >= READ_COUNT_CUTOFF] keep_dict = {g: True for g in barcodes_to_keep} forward_sequence, reverse_sequence, barcodes = zip(*[(f, r, b) for f, r, b in zip(forward_sequence, reverse_sequence, barcodes) if b in keep_dict]) # Store barcode read count dictionary for later use. count_dict = dict(Counter(barcodes)) pickle_out = open(OUTPUT_HEADER + ".read_count_dict", "wb") pickle.dump(count_dict, pickle_out, protocol=2) pickle_out.close() # Divide up barcodes into specified number of segments for parallel analysis. LENGTH = len(set(barcodes)) total_segments = int(args.total_segments) barcode_list = list(set(barcodes)) for segment in range(0, total_segments): start = int((LENGTH/total_segments)*segment) # determine start and end position of segment. if (segment+1 == total_segments): sub_barcodes_set = barcode_list[start:] else: stop = int((LENGTH/total_segments)*(segment+1)) sub_barcodes_set = barcode_list[start:stop] sub_barcodes_dict = {b: True for b in sub_barcodes_set} sub_forward, sub_reverse, sub_barcodes = zip(*[(f, r, b) for f, r, b in zip(forward_sequence, reverse_sequence, barcodes) if b in sub_barcodes_dict]) R1_dict, R2_dict = {}, {} # store reads by barcode into R1 and R2 dictionaries. for f, r, b in zip(sub_forward, sub_reverse, sub_barcodes): if (b not in R1_dict) and (b not in R2_dict): R1_dict[b] = [f] R2_dict[b] = [r] else: R1_dict[b].append(f) R2_dict[b].append(r) pickle_out = open(OUTPUT_HEADER + "_" + str(segment) + "-" + str(total_segments) + ".R1_dict", "wb") pickle.dump(R1_dict, pickle_out, protocol=2) pickle_out.close() pickle_out = open(OUTPUT_HEADER + "_" + str(segment) + "-" + str(total_segments) + ".R2_dict", "wb") pickle.dump(R2_dict, pickle_out, protocol=2) pickle_out.close()
flexible
{ "blob_id": "9206e4c4eff8ca64266ce53705e88069912b80d8", "index": 1526, "step-1": "<mask token>\n", "step-2": "<mask token>\nparser.add_argument('-f', '-forward', required=True, help=\n 'forward sequencing files', nargs='+', action='store', dest='forward_files'\n )\nparser.add_argument('-r', '-reverse', required=True, help=\n 'reverse sequencing files', nargs='+', action='store', dest='reverse_files'\n )\nparser.add_argument('-s', '-segments', required=True, help=\n 'number of segments to split job into', action='store', dest=\n 'total_segments')\nparser.add_argument('-o', '-out', required=True, help=\n 'keyword for saving output files', action='store', dest='out')\nparser.add_argument('-c', '-cutoff', required=False, default=0, help=\n 'read count cutoff for barcodes to keep (default=0)', action='store',\n dest='cutoff')\nparser.add_argument('-b', '-barcode', required=False, default=31, help=\n 'length of barcode (default=31)', action='store', dest='barcode_length')\nparser.add_argument('-bq', '-bquality', required=False, default=53, help=\n 'ascii quality score cutoff for barcode (default=53)', action='store',\n dest='barcode_quality')\nparser.add_argument('-gdq', '-gdquality', required=False, default=55, help=\n 'ascii quality score cutoff for guide-donor (default=55)', action=\n 'store', dest='guide_donor_quality')\n<mask token>\nfor file in args.forward_files:\n forward_lines.extend(gzip.open(file).readlines())\n<mask token>\nfor line in forward_quality:\n scores = [ord(i) for i in line[:BARCODE_LENGTH]]\n barcode_quality_scores.append(np.mean(scores))\n<mask token>\nfor line in forward_quality:\n scores = [ord(i) for i in line[BARCODE_LENGTH:]]\n forward_guide_donor_quality_scores.append(np.mean(scores))\n<mask token>\nfor file in args.reverse_files:\n reverse_lines.extend(gzip.open(file).readlines())\n<mask token>\nfor line in reverse_quality:\n scores = [ord(i) for i in line]\n reverse_guide_donor_quality_scores.append(np.mean(scores))\n<mask token>\nif READ_COUNT_CUTOFF != 0:\n barcodes_to_keep = [key for key, count in Counter(barcodes).items() if \n count >= READ_COUNT_CUTOFF]\n keep_dict = {g: (True) for g in barcodes_to_keep}\n forward_sequence, reverse_sequence, barcodes = zip(*[(f, r, b) for f, r,\n b in zip(forward_sequence, reverse_sequence, barcodes) if b in\n keep_dict])\n<mask token>\npickle.dump(count_dict, pickle_out, protocol=2)\npickle_out.close()\n<mask token>\nfor segment in range(0, total_segments):\n start = int(LENGTH / total_segments * segment)\n if segment + 1 == total_segments:\n sub_barcodes_set = barcode_list[start:]\n else:\n stop = int(LENGTH / total_segments * (segment + 1))\n sub_barcodes_set = barcode_list[start:stop]\n sub_barcodes_dict = {b: (True) for b in sub_barcodes_set}\n sub_forward, sub_reverse, sub_barcodes = zip(*[(f, r, b) for f, r, b in\n zip(forward_sequence, reverse_sequence, barcodes) if b in\n sub_barcodes_dict])\n R1_dict, R2_dict = {}, {}\n for f, r, b in zip(sub_forward, sub_reverse, sub_barcodes):\n if b not in R1_dict and b not in R2_dict:\n R1_dict[b] = [f]\n R2_dict[b] = [r]\n else:\n R1_dict[b].append(f)\n R2_dict[b].append(r)\n pickle_out = open(OUTPUT_HEADER + '_' + str(segment) + '-' + str(\n total_segments) + '.R1_dict', 'wb')\n pickle.dump(R1_dict, pickle_out, protocol=2)\n pickle_out.close()\n pickle_out = open(OUTPUT_HEADER + '_' + str(segment) + '-' + str(\n total_segments) + '.R2_dict', 'wb')\n pickle.dump(R2_dict, pickle_out, protocol=2)\n pickle_out.close()\n", "step-3": "<mask token>\nparser = argparse.ArgumentParser()\nparser.add_argument('-f', '-forward', required=True, help=\n 'forward sequencing files', nargs='+', action='store', dest='forward_files'\n )\nparser.add_argument('-r', '-reverse', required=True, help=\n 'reverse sequencing files', nargs='+', action='store', dest='reverse_files'\n )\nparser.add_argument('-s', '-segments', required=True, help=\n 'number of segments to split job into', action='store', dest=\n 'total_segments')\nparser.add_argument('-o', '-out', required=True, help=\n 'keyword for saving output files', action='store', dest='out')\nparser.add_argument('-c', '-cutoff', required=False, default=0, help=\n 'read count cutoff for barcodes to keep (default=0)', action='store',\n dest='cutoff')\nparser.add_argument('-b', '-barcode', required=False, default=31, help=\n 'length of barcode (default=31)', action='store', dest='barcode_length')\nparser.add_argument('-bq', '-bquality', required=False, default=53, help=\n 'ascii quality score cutoff for barcode (default=53)', action='store',\n dest='barcode_quality')\nparser.add_argument('-gdq', '-gdquality', required=False, default=55, help=\n 'ascii quality score cutoff for guide-donor (default=55)', action=\n 'store', dest='guide_donor_quality')\nargs = parser.parse_args()\nOUTPUT_HEADER = args.out\nREAD_COUNT_CUTOFF = int(args.cutoff)\nBARCODE_LENGTH = int(args.barcode_length)\nBARCODE_QUALITY_CUTOFF = int(args.barcode_quality)\nGUIDE_DONOR_QUALITY_CUTOFF = int(args.guide_donor_quality)\nforward_lines = []\nfor file in args.forward_files:\n forward_lines.extend(gzip.open(file).readlines())\nforward_sequence = [forward_lines[r] for r in range(1, len(forward_lines), 4)]\nforward_sequence = [l.decode('utf-8').replace('\\n', '') for l in\n forward_sequence]\nforward_quality = [forward_lines[r] for r in range(3, len(forward_lines), 4)]\nforward_quality = [l.decode('utf-8').replace('\\n', '') for l in forward_quality\n ]\nbarcode_quality_scores = []\nfor line in forward_quality:\n scores = [ord(i) for i in line[:BARCODE_LENGTH]]\n barcode_quality_scores.append(np.mean(scores))\nforward_guide_donor_quality_scores = []\nfor line in forward_quality:\n scores = [ord(i) for i in line[BARCODE_LENGTH:]]\n forward_guide_donor_quality_scores.append(np.mean(scores))\nreverse_lines = []\nfor file in args.reverse_files:\n reverse_lines.extend(gzip.open(file).readlines())\nreverse_sequence = [reverse_lines[r] for r in range(1, len(reverse_lines), 4)]\nreverse_sequence = [l.decode('utf-8').replace('\\n', '') for l in\n reverse_sequence]\nreverse_quality = [reverse_lines[r] for r in range(3, len(reverse_lines), 4)]\nreverse_quality = [l.decode('utf-8').replace('\\n', '') for l in reverse_quality\n ]\nreverse_guide_donor_quality_scores = []\nfor line in reverse_quality:\n scores = [ord(i) for i in line]\n reverse_guide_donor_quality_scores.append(np.mean(scores))\nforward_sequence, reverse_sequence, barcodes = zip(*[(f, r, f[:\n BARCODE_LENGTH]) for f, r, fscore, fscore2, rscore in zip(\n forward_sequence, reverse_sequence, barcode_quality_scores,\n forward_guide_donor_quality_scores, reverse_guide_donor_quality_scores) if\n fscore >= BARCODE_QUALITY_CUTOFF and fscore2 >=\n GUIDE_DONOR_QUALITY_CUTOFF and rscore >= GUIDE_DONOR_QUALITY_CUTOFF])\nif READ_COUNT_CUTOFF != 0:\n barcodes_to_keep = [key for key, count in Counter(barcodes).items() if \n count >= READ_COUNT_CUTOFF]\n keep_dict = {g: (True) for g in barcodes_to_keep}\n forward_sequence, reverse_sequence, barcodes = zip(*[(f, r, b) for f, r,\n b in zip(forward_sequence, reverse_sequence, barcodes) if b in\n keep_dict])\ncount_dict = dict(Counter(barcodes))\npickle_out = open(OUTPUT_HEADER + '.read_count_dict', 'wb')\npickle.dump(count_dict, pickle_out, protocol=2)\npickle_out.close()\nLENGTH = len(set(barcodes))\ntotal_segments = int(args.total_segments)\nbarcode_list = list(set(barcodes))\nfor segment in range(0, total_segments):\n start = int(LENGTH / total_segments * segment)\n if segment + 1 == total_segments:\n sub_barcodes_set = barcode_list[start:]\n else:\n stop = int(LENGTH / total_segments * (segment + 1))\n sub_barcodes_set = barcode_list[start:stop]\n sub_barcodes_dict = {b: (True) for b in sub_barcodes_set}\n sub_forward, sub_reverse, sub_barcodes = zip(*[(f, r, b) for f, r, b in\n zip(forward_sequence, reverse_sequence, barcodes) if b in\n sub_barcodes_dict])\n R1_dict, R2_dict = {}, {}\n for f, r, b in zip(sub_forward, sub_reverse, sub_barcodes):\n if b not in R1_dict and b not in R2_dict:\n R1_dict[b] = [f]\n R2_dict[b] = [r]\n else:\n R1_dict[b].append(f)\n R2_dict[b].append(r)\n pickle_out = open(OUTPUT_HEADER + '_' + str(segment) + '-' + str(\n total_segments) + '.R1_dict', 'wb')\n pickle.dump(R1_dict, pickle_out, protocol=2)\n pickle_out.close()\n pickle_out = open(OUTPUT_HEADER + '_' + str(segment) + '-' + str(\n total_segments) + '.R2_dict', 'wb')\n pickle.dump(R2_dict, pickle_out, protocol=2)\n pickle_out.close()\n", "step-4": "<mask token>\nfrom collections import Counter\nimport argparse\nimport gzip\nimport numpy as np\nimport pickle\nparser = argparse.ArgumentParser()\nparser.add_argument('-f', '-forward', required=True, help=\n 'forward sequencing files', nargs='+', action='store', dest='forward_files'\n )\nparser.add_argument('-r', '-reverse', required=True, help=\n 'reverse sequencing files', nargs='+', action='store', dest='reverse_files'\n )\nparser.add_argument('-s', '-segments', required=True, help=\n 'number of segments to split job into', action='store', dest=\n 'total_segments')\nparser.add_argument('-o', '-out', required=True, help=\n 'keyword for saving output files', action='store', dest='out')\nparser.add_argument('-c', '-cutoff', required=False, default=0, help=\n 'read count cutoff for barcodes to keep (default=0)', action='store',\n dest='cutoff')\nparser.add_argument('-b', '-barcode', required=False, default=31, help=\n 'length of barcode (default=31)', action='store', dest='barcode_length')\nparser.add_argument('-bq', '-bquality', required=False, default=53, help=\n 'ascii quality score cutoff for barcode (default=53)', action='store',\n dest='barcode_quality')\nparser.add_argument('-gdq', '-gdquality', required=False, default=55, help=\n 'ascii quality score cutoff for guide-donor (default=55)', action=\n 'store', dest='guide_donor_quality')\nargs = parser.parse_args()\nOUTPUT_HEADER = args.out\nREAD_COUNT_CUTOFF = int(args.cutoff)\nBARCODE_LENGTH = int(args.barcode_length)\nBARCODE_QUALITY_CUTOFF = int(args.barcode_quality)\nGUIDE_DONOR_QUALITY_CUTOFF = int(args.guide_donor_quality)\nforward_lines = []\nfor file in args.forward_files:\n forward_lines.extend(gzip.open(file).readlines())\nforward_sequence = [forward_lines[r] for r in range(1, len(forward_lines), 4)]\nforward_sequence = [l.decode('utf-8').replace('\\n', '') for l in\n forward_sequence]\nforward_quality = [forward_lines[r] for r in range(3, len(forward_lines), 4)]\nforward_quality = [l.decode('utf-8').replace('\\n', '') for l in forward_quality\n ]\nbarcode_quality_scores = []\nfor line in forward_quality:\n scores = [ord(i) for i in line[:BARCODE_LENGTH]]\n barcode_quality_scores.append(np.mean(scores))\nforward_guide_donor_quality_scores = []\nfor line in forward_quality:\n scores = [ord(i) for i in line[BARCODE_LENGTH:]]\n forward_guide_donor_quality_scores.append(np.mean(scores))\nreverse_lines = []\nfor file in args.reverse_files:\n reverse_lines.extend(gzip.open(file).readlines())\nreverse_sequence = [reverse_lines[r] for r in range(1, len(reverse_lines), 4)]\nreverse_sequence = [l.decode('utf-8').replace('\\n', '') for l in\n reverse_sequence]\nreverse_quality = [reverse_lines[r] for r in range(3, len(reverse_lines), 4)]\nreverse_quality = [l.decode('utf-8').replace('\\n', '') for l in reverse_quality\n ]\nreverse_guide_donor_quality_scores = []\nfor line in reverse_quality:\n scores = [ord(i) for i in line]\n reverse_guide_donor_quality_scores.append(np.mean(scores))\nforward_sequence, reverse_sequence, barcodes = zip(*[(f, r, f[:\n BARCODE_LENGTH]) for f, r, fscore, fscore2, rscore in zip(\n forward_sequence, reverse_sequence, barcode_quality_scores,\n forward_guide_donor_quality_scores, reverse_guide_donor_quality_scores) if\n fscore >= BARCODE_QUALITY_CUTOFF and fscore2 >=\n GUIDE_DONOR_QUALITY_CUTOFF and rscore >= GUIDE_DONOR_QUALITY_CUTOFF])\nif READ_COUNT_CUTOFF != 0:\n barcodes_to_keep = [key for key, count in Counter(barcodes).items() if \n count >= READ_COUNT_CUTOFF]\n keep_dict = {g: (True) for g in barcodes_to_keep}\n forward_sequence, reverse_sequence, barcodes = zip(*[(f, r, b) for f, r,\n b in zip(forward_sequence, reverse_sequence, barcodes) if b in\n keep_dict])\ncount_dict = dict(Counter(barcodes))\npickle_out = open(OUTPUT_HEADER + '.read_count_dict', 'wb')\npickle.dump(count_dict, pickle_out, protocol=2)\npickle_out.close()\nLENGTH = len(set(barcodes))\ntotal_segments = int(args.total_segments)\nbarcode_list = list(set(barcodes))\nfor segment in range(0, total_segments):\n start = int(LENGTH / total_segments * segment)\n if segment + 1 == total_segments:\n sub_barcodes_set = barcode_list[start:]\n else:\n stop = int(LENGTH / total_segments * (segment + 1))\n sub_barcodes_set = barcode_list[start:stop]\n sub_barcodes_dict = {b: (True) for b in sub_barcodes_set}\n sub_forward, sub_reverse, sub_barcodes = zip(*[(f, r, b) for f, r, b in\n zip(forward_sequence, reverse_sequence, barcodes) if b in\n sub_barcodes_dict])\n R1_dict, R2_dict = {}, {}\n for f, r, b in zip(sub_forward, sub_reverse, sub_barcodes):\n if b not in R1_dict and b not in R2_dict:\n R1_dict[b] = [f]\n R2_dict[b] = [r]\n else:\n R1_dict[b].append(f)\n R2_dict[b].append(r)\n pickle_out = open(OUTPUT_HEADER + '_' + str(segment) + '-' + str(\n total_segments) + '.R1_dict', 'wb')\n pickle.dump(R1_dict, pickle_out, protocol=2)\n pickle_out.close()\n pickle_out = open(OUTPUT_HEADER + '_' + str(segment) + '-' + str(\n total_segments) + '.R2_dict', 'wb')\n pickle.dump(R2_dict, pickle_out, protocol=2)\n pickle_out.close()\n", "step-5": "\"\"\"\nProcess pair-end reads of barcode-guide-donor Step 1 cassette to generate a library reference table mapping barcodes to features.\nCreate dictionaries mapping barcodes to forward and reverse reads, split into sub-segments.\n\nR1_dict: map barcodes to corresponding R1 sequences.\nR2_dict: map barcodes to corresponding R2 sequences.\nread_count_dict: map each barcode to corresponding total number of reads.\n\n\"\"\"\n\nfrom collections import Counter\nimport argparse\nimport gzip\nimport numpy as np\nimport pickle\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-f', '-forward', required=True, help=\"forward sequencing files\", nargs='+', action='store', dest='forward_files')\nparser.add_argument('-r', '-reverse', required=True, help=\"reverse sequencing files\", nargs='+', action='store', dest='reverse_files')\nparser.add_argument('-s', '-segments', required=True, help=\"number of segments to split job into\", action='store', dest='total_segments')\nparser.add_argument('-o', '-out', required=True, help=\"keyword for saving output files\", action='store', dest='out')\nparser.add_argument('-c', '-cutoff', required=False, default=0, help=\"read count cutoff for barcodes to keep (default=0)\", action='store', dest='cutoff')\nparser.add_argument('-b', '-barcode', required=False, default=31, help=\"length of barcode (default=31)\", action='store', dest='barcode_length')\nparser.add_argument('-bq', '-bquality', required=False, default=53, help=\"ascii quality score cutoff for barcode (default=53)\", action='store', dest='barcode_quality')\nparser.add_argument('-gdq', '-gdquality', required=False, default=55, help=\"ascii quality score cutoff for guide-donor (default=55)\", action='store', dest='guide_donor_quality')\n\nargs = parser.parse_args()\n\nOUTPUT_HEADER = args.out\nREAD_COUNT_CUTOFF = int(args.cutoff)\nBARCODE_LENGTH = int(args.barcode_length)\nBARCODE_QUALITY_CUTOFF = int(args.barcode_quality)\nGUIDE_DONOR_QUALITY_CUTOFF = int(args.guide_donor_quality)\n\n# Collect all sequencing reads from forward files.\nforward_lines = []\nfor file in args.forward_files:\n\tforward_lines.extend(gzip.open(file).readlines())\n\n# Forward sequence.\nforward_sequence = [forward_lines[r] for r in range(1, len(forward_lines), 4)]\nforward_sequence = [l.decode('utf-8').replace(\"\\n\",\"\") for l in forward_sequence]\n\n# Forward sequence quality scores.\nforward_quality = [forward_lines[r] for r in range(3, len(forward_lines), 4)]\nforward_quality = [l.decode('utf-8').replace(\"\\n\",\"\") for l in forward_quality]\n\nbarcode_quality_scores = [] # Barcode quality.\nfor line in forward_quality:\n scores = [ord(i) for i in line[:BARCODE_LENGTH]]\n barcode_quality_scores.append(np.mean(scores))\n\nforward_guide_donor_quality_scores = [] # Guide-donor quality.\nfor line in forward_quality:\n scores = [ord(i) for i in line[BARCODE_LENGTH:]]\n forward_guide_donor_quality_scores.append(np.mean(scores))\n\n# Collect all sequencing reads from reverse files.\nreverse_lines = []\nfor file in args.reverse_files:\n\treverse_lines.extend(gzip.open(file).readlines())\n\n# Reverse sequence.\nreverse_sequence = [reverse_lines[r] for r in range(1, len(reverse_lines), 4)]\nreverse_sequence = [l.decode('utf-8').replace(\"\\n\",\"\") for l in reverse_sequence]\n\n# Reverse sequence base quality scores.\nreverse_quality = [reverse_lines[r] for r in range(3, len(reverse_lines), 4)]\nreverse_quality = [l.decode('utf-8').replace(\"\\n\",\"\") for l in reverse_quality]\n\nreverse_guide_donor_quality_scores = []\nfor line in reverse_quality:\n scores = [ord(i) for i in line]\n reverse_guide_donor_quality_scores.append(np.mean(scores))\n\n# Filter out low quality barcodes and low quality guide-donor sequences.\nforward_sequence, reverse_sequence, barcodes = zip(*[(f, r, f[:BARCODE_LENGTH]) for f, r, fscore, fscore2, rscore\n in zip(forward_sequence, reverse_sequence, barcode_quality_scores, forward_guide_donor_quality_scores, reverse_guide_donor_quality_scores) \n if (fscore >= BARCODE_QUALITY_CUTOFF) and (fscore2 >= GUIDE_DONOR_QUALITY_CUTOFF) and (rscore >= GUIDE_DONOR_QUALITY_CUTOFF)])\n\nif (READ_COUNT_CUTOFF != 0): # optional choice to remove low read barcodes from annotations.\n\tbarcodes_to_keep = [key for key, count in Counter(barcodes).items() if count >= READ_COUNT_CUTOFF]\n\tkeep_dict = {g: True for g in barcodes_to_keep}\n\tforward_sequence, reverse_sequence, barcodes = zip(*[(f, r, b) for f, r, b \n\t\tin zip(forward_sequence, reverse_sequence, barcodes) if b in keep_dict])\n\n# Store barcode read count dictionary for later use. \ncount_dict = dict(Counter(barcodes))\npickle_out = open(OUTPUT_HEADER + \".read_count_dict\", \"wb\")\npickle.dump(count_dict, pickle_out, protocol=2)\npickle_out.close()\n\n# Divide up barcodes into specified number of segments for parallel analysis.\nLENGTH = len(set(barcodes))\ntotal_segments = int(args.total_segments)\n\nbarcode_list = list(set(barcodes))\nfor segment in range(0, total_segments):\n\tstart = int((LENGTH/total_segments)*segment) # determine start and end position of segment.\n\tif (segment+1 == total_segments):\n\t\tsub_barcodes_set = barcode_list[start:]\n\telse:\n\t\tstop = int((LENGTH/total_segments)*(segment+1))\n\t\tsub_barcodes_set = barcode_list[start:stop]\n\tsub_barcodes_dict = {b: True for b in sub_barcodes_set}\n\n\tsub_forward, sub_reverse, sub_barcodes = zip(*[(f, r, b) for f, r, b \n\t\tin zip(forward_sequence, reverse_sequence, barcodes) if b in sub_barcodes_dict])\n\n\tR1_dict, R2_dict = {}, {} # store reads by barcode into R1 and R2 dictionaries.\n\tfor f, r, b in zip(sub_forward, sub_reverse, sub_barcodes):\n\t\tif (b not in R1_dict) and (b not in R2_dict):\n\t\t\tR1_dict[b] = [f]\n\t\t\tR2_dict[b] = [r]\n\t\telse:\n\t\t\tR1_dict[b].append(f)\n\t\t\tR2_dict[b].append(r)\n\n\tpickle_out = open(OUTPUT_HEADER + \"_\" + str(segment) + \"-\" + str(total_segments) + \".R1_dict\", \"wb\")\n\tpickle.dump(R1_dict, pickle_out, protocol=2)\n\tpickle_out.close()\n\n\tpickle_out = open(OUTPUT_HEADER + \"_\" + str(segment) + \"-\" + str(total_segments) + \".R2_dict\", \"wb\")\n\tpickle.dump(R2_dict, pickle_out, protocol=2)\n\tpickle_out.close()", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> @app.route('/') def index(): return greetings <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> @app.route('/') def index(): return greetings @app.route('/play', methods=['POST']) def play(): global text text = request.data.decode('utf-8') os.system('./play.sh "' + text + '"') return jsonify({'played': True, 'text': text}), 201 @app.route('/replay') def replay(): global text os.system('./replay.sh') return jsonify({'replayed': True, 'text': text}), 200 if __name__ == '__main__': app.run(host='0.0.0.0', debug=True) <|reserved_special_token_1|> <|reserved_special_token_0|> app = Flask(__name__) text = '' greetings = "'/play' and '/replay'\n" @app.route('/') def index(): return greetings @app.route('/play', methods=['POST']) def play(): global text text = request.data.decode('utf-8') os.system('./play.sh "' + text + '"') return jsonify({'played': True, 'text': text}), 201 @app.route('/replay') def replay(): global text os.system('./replay.sh') return jsonify({'replayed': True, 'text': text}), 200 if __name__ == '__main__': app.run(host='0.0.0.0', debug=True) <|reserved_special_token_1|> from flask import Flask, jsonify, request import subprocess import os app = Flask(__name__) text = '' greetings = "'/play' and '/replay'\n" @app.route('/') def index(): return greetings @app.route('/play', methods=['POST']) def play(): global text text = request.data.decode('utf-8') os.system('./play.sh "' + text + '"') return jsonify({'played': True, 'text': text}), 201 @app.route('/replay') def replay(): global text os.system('./replay.sh') return jsonify({'replayed': True, 'text': text}), 200 if __name__ == '__main__': app.run(host='0.0.0.0', debug=True) <|reserved_special_token_1|> #!/bin/python from flask import Flask, jsonify, request import subprocess import os app = Flask(__name__) text = "" greetings = "'/play' and '/replay'\n" @app.route('/') def index(): return greetings @app.route('/play', methods=['POST']) def play(): global text text = request.data.decode('utf-8') os.system('./play.sh "' + text + '"') return jsonify({'played': True, "text" : text}), 201 @app.route('/replay') def replay(): global text os.system('./replay.sh') return jsonify({'replayed': True, "text" : text}), 200 if __name__ == '__main__': app.run(host='0.0.0.0', debug=True)
flexible
{ "blob_id": "956e63bf06255df4a36b5fa97aa62c0ed805c3f3", "index": 9452, "step-1": "<mask token>\n\n\n@app.route('/')\ndef index():\n return greetings\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\n@app.route('/')\ndef index():\n return greetings\n\n\n@app.route('/play', methods=['POST'])\ndef play():\n global text\n text = request.data.decode('utf-8')\n os.system('./play.sh \"' + text + '\"')\n return jsonify({'played': True, 'text': text}), 201\n\n\n@app.route('/replay')\ndef replay():\n global text\n os.system('./replay.sh')\n return jsonify({'replayed': True, 'text': text}), 200\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=True)\n", "step-3": "<mask token>\napp = Flask(__name__)\ntext = ''\ngreetings = \"'/play' and '/replay'\\n\"\n\n\n@app.route('/')\ndef index():\n return greetings\n\n\n@app.route('/play', methods=['POST'])\ndef play():\n global text\n text = request.data.decode('utf-8')\n os.system('./play.sh \"' + text + '\"')\n return jsonify({'played': True, 'text': text}), 201\n\n\n@app.route('/replay')\ndef replay():\n global text\n os.system('./replay.sh')\n return jsonify({'replayed': True, 'text': text}), 200\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=True)\n", "step-4": "from flask import Flask, jsonify, request\nimport subprocess\nimport os\napp = Flask(__name__)\ntext = ''\ngreetings = \"'/play' and '/replay'\\n\"\n\n\n@app.route('/')\ndef index():\n return greetings\n\n\n@app.route('/play', methods=['POST'])\ndef play():\n global text\n text = request.data.decode('utf-8')\n os.system('./play.sh \"' + text + '\"')\n return jsonify({'played': True, 'text': text}), 201\n\n\n@app.route('/replay')\ndef replay():\n global text\n os.system('./replay.sh')\n return jsonify({'replayed': True, 'text': text}), 200\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=True)\n", "step-5": "#!/bin/python\nfrom flask import Flask, jsonify, request\nimport subprocess\nimport os\n\napp = Flask(__name__)\n\ntext = \"\"\ngreetings = \"'/play' and '/replay'\\n\"\n\n@app.route('/')\ndef index():\n return greetings\n\n@app.route('/play', methods=['POST'])\ndef play():\n global text\n text = request.data.decode('utf-8') \n os.system('./play.sh \"' + text + '\"')\n return jsonify({'played': True, \"text\" : text}), 201\n\n@app.route('/replay')\ndef replay():\n global text\n os.system('./replay.sh')\n return jsonify({'replayed': True, \"text\" : text}), 200\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', debug=True)\n", "step-ids": [ 1, 4, 5, 6, 7 ] }
[ 1, 4, 5, 6, 7 ]
#!/usr/bin/python3 # -*- coding: utf-8 -*- # # Copyright 2021 Opensource ICT Solutions B.V. # https://oicts.com # #version: 1.0.0 #date: 06-11-2021 import requests import json import sys url = 'http://<URL>/zabbix/api_jsonrpc.php?' token = '<TOKEN>' headers = {'Content-Type': 'application/json'} hostname = sys.argv[1] def main(): hostid = hostid_get(token) itemid_array = itemid_get(hostid,token) update(itemid_array,token) def hostid_get(token): payload = {} payload['jsonrpc'] = '2.0' payload['method'] = 'host.get' payload['params'] = {} payload['params']['output'] = ['hostid'] payload['params']['filter'] = {} payload['params']['filter']['host'] = hostname payload['auth'] = token payload['id'] = 1 #Doing the request request = requests.post(url, data=json.dumps(payload), headers=headers) data = request.json() hostid = data["result"][0]["hostid"] return hostid def itemid_get(hostid,token): payload = {} payload['jsonrpc'] = '2.0' payload['method'] = 'item.get' payload['params'] = {} payload['params']['output'] = 'itemid' payload['params']['filter'] = {} payload['params']['filter']['host'] = hostname payload['params']['filter']['type'] = "0", "1", "3", "5", "8", "9", "10", "11", "12", "13", "14", "15", "16", "19", "20", "21" payload['auth'] = token payload['id'] = 1 # print(json.dumps(payload)) request = requests.post(url, data=json.dumps(payload), headers=headers) data = request.json() # print(data) itemid_array = [] for itemid in data['result']: itemid_array.append(str(itemid['itemid'])) return itemid_array def update(itemid_array,token): payload = {} payload['jsonrpc'] = '2.0' payload['method'] = 'task.create' payload['params'] = [] for itemid in itemid_array: request = {} request['type'] = '6' request['request'] = {} request['request']['itemid'] = itemid payload['params'].append(request) payload['auth'] = token payload['id'] = 1 #print("payload = " + json.dumps(payload)) request = requests.post(url, data=json.dumps(payload), headers=headers) data = request.json() json_string = json.dumps(data) print(json_string) if __name__ == '__main__': # Call to main main()
normal
{ "blob_id": "18d7c486b9070a1c607ba2ba5876309246013182", "index": 4651, "step-1": "<mask token>\n\n\ndef main():\n hostid = hostid_get(token)\n itemid_array = itemid_get(hostid, token)\n update(itemid_array, token)\n\n\ndef hostid_get(token):\n payload = {}\n payload['jsonrpc'] = '2.0'\n payload['method'] = 'host.get'\n payload['params'] = {}\n payload['params']['output'] = ['hostid']\n payload['params']['filter'] = {}\n payload['params']['filter']['host'] = hostname\n payload['auth'] = token\n payload['id'] = 1\n request = requests.post(url, data=json.dumps(payload), headers=headers)\n data = request.json()\n hostid = data['result'][0]['hostid']\n return hostid\n\n\ndef itemid_get(hostid, token):\n payload = {}\n payload['jsonrpc'] = '2.0'\n payload['method'] = 'item.get'\n payload['params'] = {}\n payload['params']['output'] = 'itemid'\n payload['params']['filter'] = {}\n payload['params']['filter']['host'] = hostname\n payload['params']['filter']['type'] = ('0', '1', '3', '5', '8', '9',\n '10', '11', '12', '13', '14', '15', '16', '19', '20', '21')\n payload['auth'] = token\n payload['id'] = 1\n request = requests.post(url, data=json.dumps(payload), headers=headers)\n data = request.json()\n itemid_array = []\n for itemid in data['result']:\n itemid_array.append(str(itemid['itemid']))\n return itemid_array\n\n\ndef update(itemid_array, token):\n payload = {}\n payload['jsonrpc'] = '2.0'\n payload['method'] = 'task.create'\n payload['params'] = []\n for itemid in itemid_array:\n request = {}\n request['type'] = '6'\n request['request'] = {}\n request['request']['itemid'] = itemid\n payload['params'].append(request)\n payload['auth'] = token\n payload['id'] = 1\n request = requests.post(url, data=json.dumps(payload), headers=headers)\n data = request.json()\n json_string = json.dumps(data)\n print(json_string)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef main():\n hostid = hostid_get(token)\n itemid_array = itemid_get(hostid, token)\n update(itemid_array, token)\n\n\ndef hostid_get(token):\n payload = {}\n payload['jsonrpc'] = '2.0'\n payload['method'] = 'host.get'\n payload['params'] = {}\n payload['params']['output'] = ['hostid']\n payload['params']['filter'] = {}\n payload['params']['filter']['host'] = hostname\n payload['auth'] = token\n payload['id'] = 1\n request = requests.post(url, data=json.dumps(payload), headers=headers)\n data = request.json()\n hostid = data['result'][0]['hostid']\n return hostid\n\n\ndef itemid_get(hostid, token):\n payload = {}\n payload['jsonrpc'] = '2.0'\n payload['method'] = 'item.get'\n payload['params'] = {}\n payload['params']['output'] = 'itemid'\n payload['params']['filter'] = {}\n payload['params']['filter']['host'] = hostname\n payload['params']['filter']['type'] = ('0', '1', '3', '5', '8', '9',\n '10', '11', '12', '13', '14', '15', '16', '19', '20', '21')\n payload['auth'] = token\n payload['id'] = 1\n request = requests.post(url, data=json.dumps(payload), headers=headers)\n data = request.json()\n itemid_array = []\n for itemid in data['result']:\n itemid_array.append(str(itemid['itemid']))\n return itemid_array\n\n\ndef update(itemid_array, token):\n payload = {}\n payload['jsonrpc'] = '2.0'\n payload['method'] = 'task.create'\n payload['params'] = []\n for itemid in itemid_array:\n request = {}\n request['type'] = '6'\n request['request'] = {}\n request['request']['itemid'] = itemid\n payload['params'].append(request)\n payload['auth'] = token\n payload['id'] = 1\n request = requests.post(url, data=json.dumps(payload), headers=headers)\n data = request.json()\n json_string = json.dumps(data)\n print(json_string)\n\n\nif __name__ == '__main__':\n main()\n", "step-3": "<mask token>\nurl = 'http://<URL>/zabbix/api_jsonrpc.php?'\ntoken = '<TOKEN>'\nheaders = {'Content-Type': 'application/json'}\nhostname = sys.argv[1]\n\n\ndef main():\n hostid = hostid_get(token)\n itemid_array = itemid_get(hostid, token)\n update(itemid_array, token)\n\n\ndef hostid_get(token):\n payload = {}\n payload['jsonrpc'] = '2.0'\n payload['method'] = 'host.get'\n payload['params'] = {}\n payload['params']['output'] = ['hostid']\n payload['params']['filter'] = {}\n payload['params']['filter']['host'] = hostname\n payload['auth'] = token\n payload['id'] = 1\n request = requests.post(url, data=json.dumps(payload), headers=headers)\n data = request.json()\n hostid = data['result'][0]['hostid']\n return hostid\n\n\ndef itemid_get(hostid, token):\n payload = {}\n payload['jsonrpc'] = '2.0'\n payload['method'] = 'item.get'\n payload['params'] = {}\n payload['params']['output'] = 'itemid'\n payload['params']['filter'] = {}\n payload['params']['filter']['host'] = hostname\n payload['params']['filter']['type'] = ('0', '1', '3', '5', '8', '9',\n '10', '11', '12', '13', '14', '15', '16', '19', '20', '21')\n payload['auth'] = token\n payload['id'] = 1\n request = requests.post(url, data=json.dumps(payload), headers=headers)\n data = request.json()\n itemid_array = []\n for itemid in data['result']:\n itemid_array.append(str(itemid['itemid']))\n return itemid_array\n\n\ndef update(itemid_array, token):\n payload = {}\n payload['jsonrpc'] = '2.0'\n payload['method'] = 'task.create'\n payload['params'] = []\n for itemid in itemid_array:\n request = {}\n request['type'] = '6'\n request['request'] = {}\n request['request']['itemid'] = itemid\n payload['params'].append(request)\n payload['auth'] = token\n payload['id'] = 1\n request = requests.post(url, data=json.dumps(payload), headers=headers)\n data = request.json()\n json_string = json.dumps(data)\n print(json_string)\n\n\nif __name__ == '__main__':\n main()\n", "step-4": "import requests\nimport json\nimport sys\nurl = 'http://<URL>/zabbix/api_jsonrpc.php?'\ntoken = '<TOKEN>'\nheaders = {'Content-Type': 'application/json'}\nhostname = sys.argv[1]\n\n\ndef main():\n hostid = hostid_get(token)\n itemid_array = itemid_get(hostid, token)\n update(itemid_array, token)\n\n\ndef hostid_get(token):\n payload = {}\n payload['jsonrpc'] = '2.0'\n payload['method'] = 'host.get'\n payload['params'] = {}\n payload['params']['output'] = ['hostid']\n payload['params']['filter'] = {}\n payload['params']['filter']['host'] = hostname\n payload['auth'] = token\n payload['id'] = 1\n request = requests.post(url, data=json.dumps(payload), headers=headers)\n data = request.json()\n hostid = data['result'][0]['hostid']\n return hostid\n\n\ndef itemid_get(hostid, token):\n payload = {}\n payload['jsonrpc'] = '2.0'\n payload['method'] = 'item.get'\n payload['params'] = {}\n payload['params']['output'] = 'itemid'\n payload['params']['filter'] = {}\n payload['params']['filter']['host'] = hostname\n payload['params']['filter']['type'] = ('0', '1', '3', '5', '8', '9',\n '10', '11', '12', '13', '14', '15', '16', '19', '20', '21')\n payload['auth'] = token\n payload['id'] = 1\n request = requests.post(url, data=json.dumps(payload), headers=headers)\n data = request.json()\n itemid_array = []\n for itemid in data['result']:\n itemid_array.append(str(itemid['itemid']))\n return itemid_array\n\n\ndef update(itemid_array, token):\n payload = {}\n payload['jsonrpc'] = '2.0'\n payload['method'] = 'task.create'\n payload['params'] = []\n for itemid in itemid_array:\n request = {}\n request['type'] = '6'\n request['request'] = {}\n request['request']['itemid'] = itemid\n payload['params'].append(request)\n payload['auth'] = token\n payload['id'] = 1\n request = requests.post(url, data=json.dumps(payload), headers=headers)\n data = request.json()\n json_string = json.dumps(data)\n print(json_string)\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n#\n# Copyright 2021 Opensource ICT Solutions B.V.\n# https://oicts.com\n#\n#version: 1.0.0\n#date: 06-11-2021\n\n\nimport requests\nimport json\nimport sys\n\nurl = 'http://<URL>/zabbix/api_jsonrpc.php?'\ntoken = '<TOKEN>'\n\nheaders = {'Content-Type': 'application/json'}\n\nhostname = sys.argv[1]\n\ndef main():\n hostid = hostid_get(token)\n itemid_array = itemid_get(hostid,token)\n update(itemid_array,token)\n\ndef hostid_get(token):\n payload = {}\n payload['jsonrpc'] = '2.0'\n payload['method'] = 'host.get'\n payload['params'] = {}\n payload['params']['output'] = ['hostid']\n payload['params']['filter'] = {}\n payload['params']['filter']['host'] = hostname\n payload['auth'] = token\n payload['id'] = 1\n\n\n #Doing the request\n request = requests.post(url, data=json.dumps(payload), headers=headers)\n data = request.json()\n\n hostid = data[\"result\"][0][\"hostid\"]\n return hostid\n\ndef itemid_get(hostid,token):\n payload = {}\n payload['jsonrpc'] = '2.0'\n payload['method'] = 'item.get'\n payload['params'] = {}\n payload['params']['output'] = 'itemid'\n payload['params']['filter'] = {}\n payload['params']['filter']['host'] = hostname\n payload['params']['filter']['type'] = \"0\", \"1\", \"3\", \"5\", \"8\", \"9\", \"10\", \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"19\", \"20\", \"21\"\n payload['auth'] = token\n payload['id'] = 1\n\n# print(json.dumps(payload))\n request = requests.post(url, data=json.dumps(payload), headers=headers)\n data = request.json()\n\n# print(data)\n\n itemid_array = []\n for itemid in data['result']:\n itemid_array.append(str(itemid['itemid']))\n return itemid_array\n\ndef update(itemid_array,token):\n payload = {}\n payload['jsonrpc'] = '2.0'\n payload['method'] = 'task.create'\n payload['params'] = []\n for itemid in itemid_array:\n request = {}\n request['type'] = '6'\n request['request'] = {}\n request['request']['itemid'] = itemid\n payload['params'].append(request)\n payload['auth'] = token\n payload['id'] = 1\n\n #print(\"payload = \" + json.dumps(payload))\n request = requests.post(url, data=json.dumps(payload), headers=headers)\n data = request.json()\n json_string = json.dumps(data)\n\n print(json_string)\n\nif __name__ == '__main__':\n # Call to main\n main()\n", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def ponger(pipe, response): while True: msg = pipe.recv() print(f'{getpid()} receiving: {msg}') sleep(1) pipe.send(response) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def ponger(pipe, response): while True: msg = pipe.recv() print(f'{getpid()} receiving: {msg}') sleep(1) pipe.send(response) if __name__ == '__main__': ping_conn, pong_conn = Pipe() Process(target=ponger, args=(ping_conn, 'ping')).start() Process(target=ponger, args=(pong_conn, 'pong')).start() ping_conn.send('ping') <|reserved_special_token_1|> from multiprocessing import Process, Pipe from time import sleep from os import getpid def ponger(pipe, response): while True: msg = pipe.recv() print(f'{getpid()} receiving: {msg}') sleep(1) pipe.send(response) if __name__ == '__main__': ping_conn, pong_conn = Pipe() Process(target=ponger, args=(ping_conn, 'ping')).start() Process(target=ponger, args=(pong_conn, 'pong')).start() ping_conn.send('ping') <|reserved_special_token_1|> from multiprocessing import Process, Pipe from time import sleep from os import getpid def ponger(pipe, response): while True: msg = pipe.recv() print(f"{getpid()} receiving: {msg}") sleep(1) pipe.send(response) if __name__ == '__main__': ping_conn, pong_conn = Pipe() Process(target=ponger, args=(ping_conn, 'ping')).start() Process(target=ponger, args=(pong_conn, 'pong')).start() ping_conn.send('ping')
flexible
{ "blob_id": "aac9960dafc9e8d3a5670251fcc54eb8e34d4458", "index": 9282, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef ponger(pipe, response):\n while True:\n msg = pipe.recv()\n print(f'{getpid()} receiving: {msg}')\n sleep(1)\n pipe.send(response)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef ponger(pipe, response):\n while True:\n msg = pipe.recv()\n print(f'{getpid()} receiving: {msg}')\n sleep(1)\n pipe.send(response)\n\n\nif __name__ == '__main__':\n ping_conn, pong_conn = Pipe()\n Process(target=ponger, args=(ping_conn, 'ping')).start()\n Process(target=ponger, args=(pong_conn, 'pong')).start()\n ping_conn.send('ping')\n", "step-4": "from multiprocessing import Process, Pipe\nfrom time import sleep\nfrom os import getpid\n\n\ndef ponger(pipe, response):\n while True:\n msg = pipe.recv()\n print(f'{getpid()} receiving: {msg}')\n sleep(1)\n pipe.send(response)\n\n\nif __name__ == '__main__':\n ping_conn, pong_conn = Pipe()\n Process(target=ponger, args=(ping_conn, 'ping')).start()\n Process(target=ponger, args=(pong_conn, 'pong')).start()\n ping_conn.send('ping')\n", "step-5": "from multiprocessing import Process, Pipe\nfrom time import sleep\nfrom os import getpid\n\n\ndef ponger(pipe, response):\n while True:\n msg = pipe.recv()\n print(f\"{getpid()} receiving: {msg}\")\n sleep(1)\n pipe.send(response)\n\n\nif __name__ == '__main__':\n ping_conn, pong_conn = Pipe()\n\n Process(target=ponger, args=(ping_conn, 'ping')).start()\n Process(target=ponger, args=(pong_conn, 'pong')).start()\n\n ping_conn.send('ping')\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import torch.nn as nn class RNN_instruction_encoder(nn.Module): def __init__(self, vocab_size, word_vec_dim, hidden_size, n_layers, input_dropout_p=0, dropout_p=0, bidirectional=True, variable_lengths=True, word2vec=None, fix_embeddings=False, rnn_cell='lstm'): super(RNN_instruction_encoder, self).__init__() assert rnn_cell in ['lstm', 'gru'] self.variable_lengths = variable_lengths if word2vec is not None: assert word2vec.size(0) == vocab_size self.word_vec_dim = word2vec.size(1) self.embedding = nn.Embedding(vocab_size, self.word_vec_dim) self.embedding.weight = nn.Parameter(word2vec) else: self.word_vec_dim = word_vec_dim self.embedding = nn.Embedding(vocab_size, word_vec_dim) if fix_embeddings: self.embedding.weight.requires_grad = False if rnn_cell == 'lstm': self.rnn = nn.LSTM(self.word_vec_dim, hidden_size, n_layers, batch_first=True, bidirectional=bidirectional, dropout= dropout_p) elif rnn_cell == 'gru': self.rnn = nn.GRU(self.word_vec_dim, hidden_size, n_layers, batch_first=True, bidirectional=bidirectional, dropout= dropout_p) self.input_dropout = nn.Dropout(p=input_dropout_p) self.bidirectional = bidirectional self.n_layers = n_layers self.hidden_size = hidden_size self.rnn_cell = rnn_cell def forward(self, input_seq, input_lengths=None): embedded = self.embedding(input_seq) embedded = self.input_dropout(embedded) if self.variable_lengths: embedded = nn.utils.rnn.pack_padded_sequence(embedded, input_lengths, batch_first=True, enforce_sorted=False) output, hidden = self.rnn(embedded) if self.variable_lengths: output, _ = nn.utils.rnn.pad_packed_sequence(output, batch_first=True) return output, hidden
normal
{ "blob_id": "16106250548ef60b475b009116cfeb7a25101637", "index": 7727, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass RNN_instruction_encoder(nn.Module):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass RNN_instruction_encoder(nn.Module):\n\n def __init__(self, vocab_size, word_vec_dim, hidden_size, n_layers,\n input_dropout_p=0, dropout_p=0, bidirectional=True,\n variable_lengths=True, word2vec=None, fix_embeddings=False,\n rnn_cell='lstm'):\n super(RNN_instruction_encoder, self).__init__()\n assert rnn_cell in ['lstm', 'gru']\n self.variable_lengths = variable_lengths\n if word2vec is not None:\n assert word2vec.size(0) == vocab_size\n self.word_vec_dim = word2vec.size(1)\n self.embedding = nn.Embedding(vocab_size, self.word_vec_dim)\n self.embedding.weight = nn.Parameter(word2vec)\n else:\n self.word_vec_dim = word_vec_dim\n self.embedding = nn.Embedding(vocab_size, word_vec_dim)\n if fix_embeddings:\n self.embedding.weight.requires_grad = False\n if rnn_cell == 'lstm':\n self.rnn = nn.LSTM(self.word_vec_dim, hidden_size, n_layers,\n batch_first=True, bidirectional=bidirectional, dropout=\n dropout_p)\n elif rnn_cell == 'gru':\n self.rnn = nn.GRU(self.word_vec_dim, hidden_size, n_layers,\n batch_first=True, bidirectional=bidirectional, dropout=\n dropout_p)\n self.input_dropout = nn.Dropout(p=input_dropout_p)\n self.bidirectional = bidirectional\n self.n_layers = n_layers\n self.hidden_size = hidden_size\n self.rnn_cell = rnn_cell\n\n def forward(self, input_seq, input_lengths=None):\n embedded = self.embedding(input_seq)\n embedded = self.input_dropout(embedded)\n if self.variable_lengths:\n embedded = nn.utils.rnn.pack_padded_sequence(embedded,\n input_lengths, batch_first=True, enforce_sorted=False)\n output, hidden = self.rnn(embedded)\n if self.variable_lengths:\n output, _ = nn.utils.rnn.pad_packed_sequence(output,\n batch_first=True)\n return output, hidden\n", "step-4": "import torch.nn as nn\n\n\nclass RNN_instruction_encoder(nn.Module):\n\n def __init__(self, vocab_size, word_vec_dim, hidden_size, n_layers,\n input_dropout_p=0, dropout_p=0, bidirectional=True,\n variable_lengths=True, word2vec=None, fix_embeddings=False,\n rnn_cell='lstm'):\n super(RNN_instruction_encoder, self).__init__()\n assert rnn_cell in ['lstm', 'gru']\n self.variable_lengths = variable_lengths\n if word2vec is not None:\n assert word2vec.size(0) == vocab_size\n self.word_vec_dim = word2vec.size(1)\n self.embedding = nn.Embedding(vocab_size, self.word_vec_dim)\n self.embedding.weight = nn.Parameter(word2vec)\n else:\n self.word_vec_dim = word_vec_dim\n self.embedding = nn.Embedding(vocab_size, word_vec_dim)\n if fix_embeddings:\n self.embedding.weight.requires_grad = False\n if rnn_cell == 'lstm':\n self.rnn = nn.LSTM(self.word_vec_dim, hidden_size, n_layers,\n batch_first=True, bidirectional=bidirectional, dropout=\n dropout_p)\n elif rnn_cell == 'gru':\n self.rnn = nn.GRU(self.word_vec_dim, hidden_size, n_layers,\n batch_first=True, bidirectional=bidirectional, dropout=\n dropout_p)\n self.input_dropout = nn.Dropout(p=input_dropout_p)\n self.bidirectional = bidirectional\n self.n_layers = n_layers\n self.hidden_size = hidden_size\n self.rnn_cell = rnn_cell\n\n def forward(self, input_seq, input_lengths=None):\n embedded = self.embedding(input_seq)\n embedded = self.input_dropout(embedded)\n if self.variable_lengths:\n embedded = nn.utils.rnn.pack_padded_sequence(embedded,\n input_lengths, batch_first=True, enforce_sorted=False)\n output, hidden = self.rnn(embedded)\n if self.variable_lengths:\n output, _ = nn.utils.rnn.pad_packed_sequence(output,\n batch_first=True)\n return output, hidden\n", "step-5": null, "step-ids": [ 0, 1, 3, 4 ] }
[ 0, 1, 3, 4 ]
<|reserved_special_token_0|> class Schedule: def __init__(self, start, end, name, other): self.start = self.str_convert(start) self.end = self.str_convert(end) self.name = name self.other = other self.array = self.create_array() <|reserved_special_token_0|> <|reserved_special_token_0|> @staticmethod def calculate_num_blocks(start, end): total_hrs = end.hour - start.hour total_mins = end.minute - start.minute num_half_hr = int(total_mins / 30) num_blocks = 2 * total_hrs + num_half_hr return num_blocks def prep_visualize(self): print('\n######### VISUALIZING WEEK: ' + self.name + ' #########') print(self.start, '-', self.end, '\n') num_blocks = self.calculate_num_blocks(self.start, self.end) days = ['S', 'M', 'T', 'W', 'R', 'F', 'S'] times = [] dtdt = datetime.datetime.combine(datetime.date(1, 1, 1), self.start) for i in range(num_blocks): num_blocks_i = datetime.timedelta(minutes=30 * i) combined = (dtdt + num_blocks_i).time() times.append(combined.strftime('%H:%M')) return days, times def visualize(self): days, times = self.prep_visualize() print('#####', end=' ') for d in days: print('(' + d + ') ', end='') print('#####') for t in range(len(times)): print(times[t], end=' ') for d in range(7): slot = self.array[d][t] if slot is True: slot = ' ' elif slot is False: slot = ' x ' print(slot, end=' ') print(times[t]) print() <|reserved_special_token_0|> class ExSchedule(Schedule): def __init__(self, start, end, num_members, list_membs): Schedule.__init__(self, start, end, 'ExSched', None) self.num_members = num_members self.list_membs = list_membs self.exarray = self.create_exarray() def create_exarray(self): num_blocks = Schedule.calculate_num_blocks(self.start, self.end) return [[[(True) for z in range(self.num_members)] for x in range( num_blocks)] for y in range(7)] def visualize(self): days, times = Schedule.prep_visualize(self) print('Members: ' + self.list_membs[:-2]) print('##### ', end='') for d in days: num_spaces = len(self.exarray[0][1]) - 1 left_half = int(num_spaces / 2) right_half = num_spaces - left_half print('(', end='') print(''.join([' ' for x in range(left_half)]), end=d) print(''.join([' ' for x in range(right_half)]), end=')') print(' #####') for i in range(len(times)): print(times[i], end=' ') for d in range(len(self.exarray)): array = self.exarray[d][i] print('[', end='') for memb_avail in array: print('-', end='') if memb_avail is True else print('*', end='') print(']', end='') print(' ', end=times[i] + '\n') <|reserved_special_token_1|> <|reserved_special_token_0|> class Schedule: def __init__(self, start, end, name, other): self.start = self.str_convert(start) self.end = self.str_convert(end) self.name = name self.other = other self.array = self.create_array() <|reserved_special_token_0|> <|reserved_special_token_0|> @staticmethod def calculate_num_blocks(start, end): total_hrs = end.hour - start.hour total_mins = end.minute - start.minute num_half_hr = int(total_mins / 30) num_blocks = 2 * total_hrs + num_half_hr return num_blocks def prep_visualize(self): print('\n######### VISUALIZING WEEK: ' + self.name + ' #########') print(self.start, '-', self.end, '\n') num_blocks = self.calculate_num_blocks(self.start, self.end) days = ['S', 'M', 'T', 'W', 'R', 'F', 'S'] times = [] dtdt = datetime.datetime.combine(datetime.date(1, 1, 1), self.start) for i in range(num_blocks): num_blocks_i = datetime.timedelta(minutes=30 * i) combined = (dtdt + num_blocks_i).time() times.append(combined.strftime('%H:%M')) return days, times def visualize(self): days, times = self.prep_visualize() print('#####', end=' ') for d in days: print('(' + d + ') ', end='') print('#####') for t in range(len(times)): print(times[t], end=' ') for d in range(7): slot = self.array[d][t] if slot is True: slot = ' ' elif slot is False: slot = ' x ' print(slot, end=' ') print(times[t]) print() def print_other(self): print(self.name + '\t ', self.other.replace('\n', '; ')) class ExSchedule(Schedule): def __init__(self, start, end, num_members, list_membs): Schedule.__init__(self, start, end, 'ExSched', None) self.num_members = num_members self.list_membs = list_membs self.exarray = self.create_exarray() def create_exarray(self): num_blocks = Schedule.calculate_num_blocks(self.start, self.end) return [[[(True) for z in range(self.num_members)] for x in range( num_blocks)] for y in range(7)] def visualize(self): days, times = Schedule.prep_visualize(self) print('Members: ' + self.list_membs[:-2]) print('##### ', end='') for d in days: num_spaces = len(self.exarray[0][1]) - 1 left_half = int(num_spaces / 2) right_half = num_spaces - left_half print('(', end='') print(''.join([' ' for x in range(left_half)]), end=d) print(''.join([' ' for x in range(right_half)]), end=')') print(' #####') for i in range(len(times)): print(times[i], end=' ') for d in range(len(self.exarray)): array = self.exarray[d][i] print('[', end='') for memb_avail in array: print('-', end='') if memb_avail is True else print('*', end='') print(']', end='') print(' ', end=times[i] + '\n') <|reserved_special_token_1|> <|reserved_special_token_0|> class Schedule: def __init__(self, start, end, name, other): self.start = self.str_convert(start) self.end = self.str_convert(end) self.name = name self.other = other self.array = self.create_array() def str_convert(self, str_time): if isinstance(str_time, str): str_time = datetime.datetime.strptime(str_time, '%H:%M') return datetime.time(str_time.hour, str_time.minute) return str_time def create_array(self): num_blocks = self.calculate_num_blocks(self.start, self.end) return [[(True) for x in range(num_blocks)] for y in range(7)] @staticmethod def calculate_num_blocks(start, end): total_hrs = end.hour - start.hour total_mins = end.minute - start.minute num_half_hr = int(total_mins / 30) num_blocks = 2 * total_hrs + num_half_hr return num_blocks def prep_visualize(self): print('\n######### VISUALIZING WEEK: ' + self.name + ' #########') print(self.start, '-', self.end, '\n') num_blocks = self.calculate_num_blocks(self.start, self.end) days = ['S', 'M', 'T', 'W', 'R', 'F', 'S'] times = [] dtdt = datetime.datetime.combine(datetime.date(1, 1, 1), self.start) for i in range(num_blocks): num_blocks_i = datetime.timedelta(minutes=30 * i) combined = (dtdt + num_blocks_i).time() times.append(combined.strftime('%H:%M')) return days, times def visualize(self): days, times = self.prep_visualize() print('#####', end=' ') for d in days: print('(' + d + ') ', end='') print('#####') for t in range(len(times)): print(times[t], end=' ') for d in range(7): slot = self.array[d][t] if slot is True: slot = ' ' elif slot is False: slot = ' x ' print(slot, end=' ') print(times[t]) print() def print_other(self): print(self.name + '\t ', self.other.replace('\n', '; ')) class ExSchedule(Schedule): def __init__(self, start, end, num_members, list_membs): Schedule.__init__(self, start, end, 'ExSched', None) self.num_members = num_members self.list_membs = list_membs self.exarray = self.create_exarray() def create_exarray(self): num_blocks = Schedule.calculate_num_blocks(self.start, self.end) return [[[(True) for z in range(self.num_members)] for x in range( num_blocks)] for y in range(7)] def visualize(self): days, times = Schedule.prep_visualize(self) print('Members: ' + self.list_membs[:-2]) print('##### ', end='') for d in days: num_spaces = len(self.exarray[0][1]) - 1 left_half = int(num_spaces / 2) right_half = num_spaces - left_half print('(', end='') print(''.join([' ' for x in range(left_half)]), end=d) print(''.join([' ' for x in range(right_half)]), end=')') print(' #####') for i in range(len(times)): print(times[i], end=' ') for d in range(len(self.exarray)): array = self.exarray[d][i] print('[', end='') for memb_avail in array: print('-', end='') if memb_avail is True else print('*', end='') print(']', end='') print(' ', end=times[i] + '\n') <|reserved_special_token_1|> import datetime class Schedule: def __init__(self, start, end, name, other): self.start = self.str_convert(start) self.end = self.str_convert(end) self.name = name self.other = other self.array = self.create_array() def str_convert(self, str_time): if isinstance(str_time, str): str_time = datetime.datetime.strptime(str_time, '%H:%M') return datetime.time(str_time.hour, str_time.minute) return str_time def create_array(self): num_blocks = self.calculate_num_blocks(self.start, self.end) return [[(True) for x in range(num_blocks)] for y in range(7)] @staticmethod def calculate_num_blocks(start, end): total_hrs = end.hour - start.hour total_mins = end.minute - start.minute num_half_hr = int(total_mins / 30) num_blocks = 2 * total_hrs + num_half_hr return num_blocks def prep_visualize(self): print('\n######### VISUALIZING WEEK: ' + self.name + ' #########') print(self.start, '-', self.end, '\n') num_blocks = self.calculate_num_blocks(self.start, self.end) days = ['S', 'M', 'T', 'W', 'R', 'F', 'S'] times = [] dtdt = datetime.datetime.combine(datetime.date(1, 1, 1), self.start) for i in range(num_blocks): num_blocks_i = datetime.timedelta(minutes=30 * i) combined = (dtdt + num_blocks_i).time() times.append(combined.strftime('%H:%M')) return days, times def visualize(self): days, times = self.prep_visualize() print('#####', end=' ') for d in days: print('(' + d + ') ', end='') print('#####') for t in range(len(times)): print(times[t], end=' ') for d in range(7): slot = self.array[d][t] if slot is True: slot = ' ' elif slot is False: slot = ' x ' print(slot, end=' ') print(times[t]) print() def print_other(self): print(self.name + '\t ', self.other.replace('\n', '; ')) class ExSchedule(Schedule): def __init__(self, start, end, num_members, list_membs): Schedule.__init__(self, start, end, 'ExSched', None) self.num_members = num_members self.list_membs = list_membs self.exarray = self.create_exarray() def create_exarray(self): num_blocks = Schedule.calculate_num_blocks(self.start, self.end) return [[[(True) for z in range(self.num_members)] for x in range( num_blocks)] for y in range(7)] def visualize(self): days, times = Schedule.prep_visualize(self) print('Members: ' + self.list_membs[:-2]) print('##### ', end='') for d in days: num_spaces = len(self.exarray[0][1]) - 1 left_half = int(num_spaces / 2) right_half = num_spaces - left_half print('(', end='') print(''.join([' ' for x in range(left_half)]), end=d) print(''.join([' ' for x in range(right_half)]), end=')') print(' #####') for i in range(len(times)): print(times[i], end=' ') for d in range(len(self.exarray)): array = self.exarray[d][i] print('[', end='') for memb_avail in array: print('-', end='') if memb_avail is True else print('*', end='') print(']', end='') print(' ', end=times[i] + '\n') <|reserved_special_token_1|> import datetime class Schedule: def __init__(self, start, end, name, other): # Constructor self.start = self.str_convert(start) # Schedule start time (ex. 9:00) self.end = self.str_convert(end) # Schedule end time (ex. 22:00) self.name = name # Schedule name (ex. member name, final schedule, etc) self.other = other # Schedule exceptions/"other" self.array = self.create_array() # Schedule array (2D array of days of week (7) x half hour blocks) def str_convert(self, str_time): # Converts start/end time to datettime if entered as string if isinstance(str_time, str): str_time = datetime.datetime.strptime(str_time, '%H:%M') return datetime.time(str_time.hour, str_time.minute) return str_time def create_array(self): # Generate array from number of (30 minute) blocks num_blocks = self.calculate_num_blocks(self.start, self.end) return [[True for x in range(num_blocks)] for y in range(7)] @staticmethod def calculate_num_blocks(start, end): # Determining size of array: get difference total_hrs = end.hour - start.hour total_mins = end.minute - start.minute # Determining size of array: in 30 min blocks (rounded) num_half_hr = int(total_mins/30) num_blocks = 2 * total_hrs + num_half_hr return num_blocks # def get_time def prep_visualize(self): # Banner print("\n######### VISUALIZING WEEK: " + self.name + " #########") print(self.start, "-", self.end, "\n") num_blocks = self.calculate_num_blocks(self.start, self.end) days = ["S", "M", "T", "W", "R", "F", "S" ] times = [] # Fill times column (from datetime obj) # Convert to datetime.datetime object, add timedelta, convert back - arbitrary datetime.date(1, 1, 1) dtdt = datetime.datetime.combine(datetime.date(1, 1, 1), self.start) for i in range(num_blocks): num_blocks_i = datetime.timedelta(minutes=30*i) combined = (dtdt + num_blocks_i).time() times.append(combined.strftime("%H:%M")) return days, times def visualize(self): days, times = self.prep_visualize() # HEADER: print("#####", end=" ") for d in days: print("(" + d + ") ", end="") print("#####") # SCHEDULE: for t in range(len(times)): print(times[t], end=" ") for d in range(7): slot = self.array[d][t] if slot is True: slot = " " elif slot is False: slot = " x " print(slot, end=" ") print(times[t]) print() def print_other(self): print(self.name + "\t ", self.other.replace("\n", "; ")) class ExSchedule(Schedule): def __init__(self, start, end, num_members, list_membs): Schedule.__init__(self, start, end, "ExSched", None) self.num_members = num_members self.list_membs = list_membs self.exarray = self.create_exarray() def create_exarray(self): num_blocks = Schedule.calculate_num_blocks(self.start, self.end) return [[[True for z in range(self.num_members)] for x in range(num_blocks)] for y in range(7)] def visualize(self): days, times = Schedule.prep_visualize(self) print("Members: "+ self.list_membs[:-2]) # HEADER: print("##### ", end="") # print(days) # print(times) for d in days: num_spaces = len(self.exarray[0][1]) - 1 left_half = int(num_spaces / 2) right_half = num_spaces - left_half print("(", end="") print(''.join([" " for x in range(left_half)]), end=d) print(''.join([" " for x in range(right_half)]), end=")") print(" #####") # SCHEDULE: for i in range(len(times)): # i: 0-26 (9:00) = m: 0-26 ([T,T,T]) print(times[i], end=" ") for d in range(len(self.exarray)): # d: 0-6 (sun) array = self.exarray[d][i] print("[", end="") for memb_avail in array: print("-", end="") if memb_avail is True else print("*", end="") print("]", end="") print(" ", end=times[i]+"\n")
flexible
{ "blob_id": "f56978d5738c2f8cb4ed5ce4f11d3aae6a9689b1", "index": 4604, "step-1": "<mask token>\n\n\nclass Schedule:\n\n def __init__(self, start, end, name, other):\n self.start = self.str_convert(start)\n self.end = self.str_convert(end)\n self.name = name\n self.other = other\n self.array = self.create_array()\n <mask token>\n <mask token>\n\n @staticmethod\n def calculate_num_blocks(start, end):\n total_hrs = end.hour - start.hour\n total_mins = end.minute - start.minute\n num_half_hr = int(total_mins / 30)\n num_blocks = 2 * total_hrs + num_half_hr\n return num_blocks\n\n def prep_visualize(self):\n print('\\n######### VISUALIZING WEEK: ' + self.name + ' #########')\n print(self.start, '-', self.end, '\\n')\n num_blocks = self.calculate_num_blocks(self.start, self.end)\n days = ['S', 'M', 'T', 'W', 'R', 'F', 'S']\n times = []\n dtdt = datetime.datetime.combine(datetime.date(1, 1, 1), self.start)\n for i in range(num_blocks):\n num_blocks_i = datetime.timedelta(minutes=30 * i)\n combined = (dtdt + num_blocks_i).time()\n times.append(combined.strftime('%H:%M'))\n return days, times\n\n def visualize(self):\n days, times = self.prep_visualize()\n print('#####', end=' ')\n for d in days:\n print('(' + d + ') ', end='')\n print('#####')\n for t in range(len(times)):\n print(times[t], end=' ')\n for d in range(7):\n slot = self.array[d][t]\n if slot is True:\n slot = ' '\n elif slot is False:\n slot = ' x '\n print(slot, end=' ')\n print(times[t])\n print()\n <mask token>\n\n\nclass ExSchedule(Schedule):\n\n def __init__(self, start, end, num_members, list_membs):\n Schedule.__init__(self, start, end, 'ExSched', None)\n self.num_members = num_members\n self.list_membs = list_membs\n self.exarray = self.create_exarray()\n\n def create_exarray(self):\n num_blocks = Schedule.calculate_num_blocks(self.start, self.end)\n return [[[(True) for z in range(self.num_members)] for x in range(\n num_blocks)] for y in range(7)]\n\n def visualize(self):\n days, times = Schedule.prep_visualize(self)\n print('Members: ' + self.list_membs[:-2])\n print('##### ', end='')\n for d in days:\n num_spaces = len(self.exarray[0][1]) - 1\n left_half = int(num_spaces / 2)\n right_half = num_spaces - left_half\n print('(', end='')\n print(''.join([' ' for x in range(left_half)]), end=d)\n print(''.join([' ' for x in range(right_half)]), end=')')\n print(' #####')\n for i in range(len(times)):\n print(times[i], end=' ')\n for d in range(len(self.exarray)):\n array = self.exarray[d][i]\n print('[', end='')\n for memb_avail in array:\n print('-', end='') if memb_avail is True else print('*',\n end='')\n print(']', end='')\n print(' ', end=times[i] + '\\n')\n", "step-2": "<mask token>\n\n\nclass Schedule:\n\n def __init__(self, start, end, name, other):\n self.start = self.str_convert(start)\n self.end = self.str_convert(end)\n self.name = name\n self.other = other\n self.array = self.create_array()\n <mask token>\n <mask token>\n\n @staticmethod\n def calculate_num_blocks(start, end):\n total_hrs = end.hour - start.hour\n total_mins = end.minute - start.minute\n num_half_hr = int(total_mins / 30)\n num_blocks = 2 * total_hrs + num_half_hr\n return num_blocks\n\n def prep_visualize(self):\n print('\\n######### VISUALIZING WEEK: ' + self.name + ' #########')\n print(self.start, '-', self.end, '\\n')\n num_blocks = self.calculate_num_blocks(self.start, self.end)\n days = ['S', 'M', 'T', 'W', 'R', 'F', 'S']\n times = []\n dtdt = datetime.datetime.combine(datetime.date(1, 1, 1), self.start)\n for i in range(num_blocks):\n num_blocks_i = datetime.timedelta(minutes=30 * i)\n combined = (dtdt + num_blocks_i).time()\n times.append(combined.strftime('%H:%M'))\n return days, times\n\n def visualize(self):\n days, times = self.prep_visualize()\n print('#####', end=' ')\n for d in days:\n print('(' + d + ') ', end='')\n print('#####')\n for t in range(len(times)):\n print(times[t], end=' ')\n for d in range(7):\n slot = self.array[d][t]\n if slot is True:\n slot = ' '\n elif slot is False:\n slot = ' x '\n print(slot, end=' ')\n print(times[t])\n print()\n\n def print_other(self):\n print(self.name + '\\t ', self.other.replace('\\n', '; '))\n\n\nclass ExSchedule(Schedule):\n\n def __init__(self, start, end, num_members, list_membs):\n Schedule.__init__(self, start, end, 'ExSched', None)\n self.num_members = num_members\n self.list_membs = list_membs\n self.exarray = self.create_exarray()\n\n def create_exarray(self):\n num_blocks = Schedule.calculate_num_blocks(self.start, self.end)\n return [[[(True) for z in range(self.num_members)] for x in range(\n num_blocks)] for y in range(7)]\n\n def visualize(self):\n days, times = Schedule.prep_visualize(self)\n print('Members: ' + self.list_membs[:-2])\n print('##### ', end='')\n for d in days:\n num_spaces = len(self.exarray[0][1]) - 1\n left_half = int(num_spaces / 2)\n right_half = num_spaces - left_half\n print('(', end='')\n print(''.join([' ' for x in range(left_half)]), end=d)\n print(''.join([' ' for x in range(right_half)]), end=')')\n print(' #####')\n for i in range(len(times)):\n print(times[i], end=' ')\n for d in range(len(self.exarray)):\n array = self.exarray[d][i]\n print('[', end='')\n for memb_avail in array:\n print('-', end='') if memb_avail is True else print('*',\n end='')\n print(']', end='')\n print(' ', end=times[i] + '\\n')\n", "step-3": "<mask token>\n\n\nclass Schedule:\n\n def __init__(self, start, end, name, other):\n self.start = self.str_convert(start)\n self.end = self.str_convert(end)\n self.name = name\n self.other = other\n self.array = self.create_array()\n\n def str_convert(self, str_time):\n if isinstance(str_time, str):\n str_time = datetime.datetime.strptime(str_time, '%H:%M')\n return datetime.time(str_time.hour, str_time.minute)\n return str_time\n\n def create_array(self):\n num_blocks = self.calculate_num_blocks(self.start, self.end)\n return [[(True) for x in range(num_blocks)] for y in range(7)]\n\n @staticmethod\n def calculate_num_blocks(start, end):\n total_hrs = end.hour - start.hour\n total_mins = end.minute - start.minute\n num_half_hr = int(total_mins / 30)\n num_blocks = 2 * total_hrs + num_half_hr\n return num_blocks\n\n def prep_visualize(self):\n print('\\n######### VISUALIZING WEEK: ' + self.name + ' #########')\n print(self.start, '-', self.end, '\\n')\n num_blocks = self.calculate_num_blocks(self.start, self.end)\n days = ['S', 'M', 'T', 'W', 'R', 'F', 'S']\n times = []\n dtdt = datetime.datetime.combine(datetime.date(1, 1, 1), self.start)\n for i in range(num_blocks):\n num_blocks_i = datetime.timedelta(minutes=30 * i)\n combined = (dtdt + num_blocks_i).time()\n times.append(combined.strftime('%H:%M'))\n return days, times\n\n def visualize(self):\n days, times = self.prep_visualize()\n print('#####', end=' ')\n for d in days:\n print('(' + d + ') ', end='')\n print('#####')\n for t in range(len(times)):\n print(times[t], end=' ')\n for d in range(7):\n slot = self.array[d][t]\n if slot is True:\n slot = ' '\n elif slot is False:\n slot = ' x '\n print(slot, end=' ')\n print(times[t])\n print()\n\n def print_other(self):\n print(self.name + '\\t ', self.other.replace('\\n', '; '))\n\n\nclass ExSchedule(Schedule):\n\n def __init__(self, start, end, num_members, list_membs):\n Schedule.__init__(self, start, end, 'ExSched', None)\n self.num_members = num_members\n self.list_membs = list_membs\n self.exarray = self.create_exarray()\n\n def create_exarray(self):\n num_blocks = Schedule.calculate_num_blocks(self.start, self.end)\n return [[[(True) for z in range(self.num_members)] for x in range(\n num_blocks)] for y in range(7)]\n\n def visualize(self):\n days, times = Schedule.prep_visualize(self)\n print('Members: ' + self.list_membs[:-2])\n print('##### ', end='')\n for d in days:\n num_spaces = len(self.exarray[0][1]) - 1\n left_half = int(num_spaces / 2)\n right_half = num_spaces - left_half\n print('(', end='')\n print(''.join([' ' for x in range(left_half)]), end=d)\n print(''.join([' ' for x in range(right_half)]), end=')')\n print(' #####')\n for i in range(len(times)):\n print(times[i], end=' ')\n for d in range(len(self.exarray)):\n array = self.exarray[d][i]\n print('[', end='')\n for memb_avail in array:\n print('-', end='') if memb_avail is True else print('*',\n end='')\n print(']', end='')\n print(' ', end=times[i] + '\\n')\n", "step-4": "import datetime\n\n\nclass Schedule:\n\n def __init__(self, start, end, name, other):\n self.start = self.str_convert(start)\n self.end = self.str_convert(end)\n self.name = name\n self.other = other\n self.array = self.create_array()\n\n def str_convert(self, str_time):\n if isinstance(str_time, str):\n str_time = datetime.datetime.strptime(str_time, '%H:%M')\n return datetime.time(str_time.hour, str_time.minute)\n return str_time\n\n def create_array(self):\n num_blocks = self.calculate_num_blocks(self.start, self.end)\n return [[(True) for x in range(num_blocks)] for y in range(7)]\n\n @staticmethod\n def calculate_num_blocks(start, end):\n total_hrs = end.hour - start.hour\n total_mins = end.minute - start.minute\n num_half_hr = int(total_mins / 30)\n num_blocks = 2 * total_hrs + num_half_hr\n return num_blocks\n\n def prep_visualize(self):\n print('\\n######### VISUALIZING WEEK: ' + self.name + ' #########')\n print(self.start, '-', self.end, '\\n')\n num_blocks = self.calculate_num_blocks(self.start, self.end)\n days = ['S', 'M', 'T', 'W', 'R', 'F', 'S']\n times = []\n dtdt = datetime.datetime.combine(datetime.date(1, 1, 1), self.start)\n for i in range(num_blocks):\n num_blocks_i = datetime.timedelta(minutes=30 * i)\n combined = (dtdt + num_blocks_i).time()\n times.append(combined.strftime('%H:%M'))\n return days, times\n\n def visualize(self):\n days, times = self.prep_visualize()\n print('#####', end=' ')\n for d in days:\n print('(' + d + ') ', end='')\n print('#####')\n for t in range(len(times)):\n print(times[t], end=' ')\n for d in range(7):\n slot = self.array[d][t]\n if slot is True:\n slot = ' '\n elif slot is False:\n slot = ' x '\n print(slot, end=' ')\n print(times[t])\n print()\n\n def print_other(self):\n print(self.name + '\\t ', self.other.replace('\\n', '; '))\n\n\nclass ExSchedule(Schedule):\n\n def __init__(self, start, end, num_members, list_membs):\n Schedule.__init__(self, start, end, 'ExSched', None)\n self.num_members = num_members\n self.list_membs = list_membs\n self.exarray = self.create_exarray()\n\n def create_exarray(self):\n num_blocks = Schedule.calculate_num_blocks(self.start, self.end)\n return [[[(True) for z in range(self.num_members)] for x in range(\n num_blocks)] for y in range(7)]\n\n def visualize(self):\n days, times = Schedule.prep_visualize(self)\n print('Members: ' + self.list_membs[:-2])\n print('##### ', end='')\n for d in days:\n num_spaces = len(self.exarray[0][1]) - 1\n left_half = int(num_spaces / 2)\n right_half = num_spaces - left_half\n print('(', end='')\n print(''.join([' ' for x in range(left_half)]), end=d)\n print(''.join([' ' for x in range(right_half)]), end=')')\n print(' #####')\n for i in range(len(times)):\n print(times[i], end=' ')\n for d in range(len(self.exarray)):\n array = self.exarray[d][i]\n print('[', end='')\n for memb_avail in array:\n print('-', end='') if memb_avail is True else print('*',\n end='')\n print(']', end='')\n print(' ', end=times[i] + '\\n')\n", "step-5": "import datetime\n\nclass Schedule:\n def __init__(self, start, end, name, other): # Constructor\n self.start = self.str_convert(start) # Schedule start time (ex. 9:00)\n self.end = self.str_convert(end) # Schedule end time (ex. 22:00)\n self.name = name # Schedule name (ex. member name, final schedule, etc)\n self.other = other # Schedule exceptions/\"other\"\n self.array = self.create_array() # Schedule array (2D array of days of week (7) x half hour blocks)\n\n def str_convert(self, str_time):\n # Converts start/end time to datettime if entered as string\n if isinstance(str_time, str):\n str_time = datetime.datetime.strptime(str_time, '%H:%M')\n return datetime.time(str_time.hour, str_time.minute)\n return str_time\n\n def create_array(self):\n # Generate array from number of (30 minute) blocks\n num_blocks = self.calculate_num_blocks(self.start, self.end)\n return [[True for x in range(num_blocks)] for y in range(7)]\n\n @staticmethod\n def calculate_num_blocks(start, end):\n # Determining size of array: get difference\n total_hrs = end.hour - start.hour\n total_mins = end.minute - start.minute\n\n # Determining size of array: in 30 min blocks (rounded)\n num_half_hr = int(total_mins/30)\n num_blocks = 2 * total_hrs + num_half_hr\n\n return num_blocks\n\n # def get_time\n\n def prep_visualize(self):\n # Banner\n print(\"\\n######### VISUALIZING WEEK: \" + self.name + \" #########\")\n print(self.start, \"-\", self.end, \"\\n\")\n\n num_blocks = self.calculate_num_blocks(self.start, self.end)\n days = [\"S\", \"M\", \"T\", \"W\", \"R\", \"F\", \"S\" ]\n times = []\n\n # Fill times column (from datetime obj)\n # Convert to datetime.datetime object, add timedelta, convert back - arbitrary datetime.date(1, 1, 1)\n dtdt = datetime.datetime.combine(datetime.date(1, 1, 1), self.start)\n for i in range(num_blocks):\n num_blocks_i = datetime.timedelta(minutes=30*i)\n combined = (dtdt + num_blocks_i).time()\n times.append(combined.strftime(\"%H:%M\"))\n\n return days, times\n\n def visualize(self):\n days, times = self.prep_visualize()\n\n # HEADER:\n print(\"#####\", end=\" \")\n for d in days: print(\"(\" + d + \") \", end=\"\")\n print(\"#####\")\n\n # SCHEDULE:\n for t in range(len(times)):\n print(times[t], end=\" \")\n for d in range(7):\n slot = self.array[d][t]\n if slot is True: slot = \" \"\n elif slot is False: slot = \" x \"\n print(slot, end=\" \")\n print(times[t])\n print()\n\n def print_other(self): \n print(self.name + \"\\t \", self.other.replace(\"\\n\", \"; \"))\n\n\nclass ExSchedule(Schedule):\n def __init__(self, start, end, num_members, list_membs):\n Schedule.__init__(self, start, end, \"ExSched\", None)\n self.num_members = num_members\n self.list_membs = list_membs\n self.exarray = self.create_exarray()\n\n def create_exarray(self):\n num_blocks = Schedule.calculate_num_blocks(self.start, self.end)\n return [[[True for z in range(self.num_members)] for x in range(num_blocks)] for y in range(7)]\n\n def visualize(self):\n days, times = Schedule.prep_visualize(self)\n print(\"Members: \"+ self.list_membs[:-2])\n\n # HEADER:\n print(\"##### \", end=\"\")\n # print(days)\n # print(times)\n for d in days:\n num_spaces = len(self.exarray[0][1]) - 1\n left_half = int(num_spaces / 2)\n right_half = num_spaces - left_half\n\n print(\"(\", end=\"\")\n print(''.join([\" \" for x in range(left_half)]), end=d)\n print(''.join([\" \" for x in range(right_half)]), end=\")\")\n print(\" #####\")\n\n # SCHEDULE:\n for i in range(len(times)): # i: 0-26 (9:00) = m: 0-26 ([T,T,T])\n print(times[i], end=\" \")\n for d in range(len(self.exarray)): # d: 0-6 (sun)\n array = self.exarray[d][i]\n print(\"[\", end=\"\")\n for memb_avail in array:\n print(\"-\", end=\"\") if memb_avail is True else print(\"*\", end=\"\")\n print(\"]\", end=\"\")\n print(\" \", end=times[i]+\"\\n\")\n", "step-ids": [ 9, 10, 12, 13, 14 ] }
[ 9, 10, 12, 13, 14 ]
import json import logging import numpy as np from python_speech_features import mfcc from format_converters import get_segment from schemas import * from chains.mfcc import Mfcc logger = logging.getLogger() class MfccLocal(Mfcc): """ MfccLocal computes Mfcc features for each phoneme from the sample that are not blacklisted based on phoneme label that is received from Phoneme chain. It subclasses Formants to not repeat the sample_layer logic which is valid also in this context """ abstract_class = False @staticmethod def sample_result_filename(out_sample_path): return f'{out_sample_path[:-5]}_mfcc_result.json' @staticmethod def filenames_to_skip_sample(out_sample_path): return [f'{out_sample_path[:-5]}_mfcc_result.csv'] @staticmethod def serialize_to_json(mfcc_result): """ :param mfcc_result: list of mfcc measurements with necessary metadata :return: serialized object of proper schema """ mfcc_schema = MfccLocalSchema() mfcc_dict = {'mfcc_info': mfcc_result} return mfcc_schema.dumps(mfcc_dict) def compute_mfcc(self, segments_path, phonemes_result_path): """ :param segments_path: path to the input wav :param phonemes_result_path: path to phonemes results that is required by the Local version of the Mfcc :return: computed list of mfcc features with all required metadata """ wav = get_segment(segments_path, 'wav') frequency = wav.frame_rate phoneme_len = self.process_settings.get("phoneme_len", 2048) ignore_shorter_phonemes = self.process_settings.get("ignore_shorter_phonemes", True) mfcc_nfft = self.process_settings.get("mfcc_nfft", 2048) mfcc_winstep = self.process_settings.get("mfcc_winstep", 0.1) with open(phonemes_result_path, 'r') as f: schema = DecoderOutputSchema() json_file = json.load(f) phonemes_result = schema.load(json_file) phonemes_info = [info for info in phonemes_result['segment_info'] if info['word'] not in self.blacklisted_phonemes] mfcc_result = [] for info in phonemes_info: start, stop = (1000 * info['start'], 1000 * info['end']) segment = np.array(wav[start:stop].get_array_of_samples()) if ignore_shorter_phonemes and segment.size < phoneme_len: continue mfcc_features = mfcc(segment, samplerate=frequency, nfft=mfcc_nfft, winstep=mfcc_winstep) for i in range(len(mfcc_features)): ith_mfcc = np.array(mfcc_features[i, :]) ith_mfcc_result_row = {'i': i, 'length': len(mfcc_features), 'mfcc': ith_mfcc, **info} mfcc_result.append(ith_mfcc_result_row) return mfcc_result
normal
{ "blob_id": "44214492dd7283da4b9a77bd2a1fa9d9c0643ff2", "index": 1188, "step-1": "<mask token>\n\n\nclass MfccLocal(Mfcc):\n <mask token>\n abstract_class = False\n\n @staticmethod\n def sample_result_filename(out_sample_path):\n return f'{out_sample_path[:-5]}_mfcc_result.json'\n\n @staticmethod\n def filenames_to_skip_sample(out_sample_path):\n return [f'{out_sample_path[:-5]}_mfcc_result.csv']\n\n @staticmethod\n def serialize_to_json(mfcc_result):\n \"\"\"\n :param mfcc_result: list of mfcc measurements with\n necessary metadata\n :return: serialized object of proper schema\n \"\"\"\n mfcc_schema = MfccLocalSchema()\n mfcc_dict = {'mfcc_info': mfcc_result}\n return mfcc_schema.dumps(mfcc_dict)\n\n def compute_mfcc(self, segments_path, phonemes_result_path):\n \"\"\"\n\n :param segments_path: path to the input wav\n :param phonemes_result_path: path to phonemes results\n that is required by the Local version of the Mfcc\n :return: computed list of mfcc features with all required metadata\n \"\"\"\n wav = get_segment(segments_path, 'wav')\n frequency = wav.frame_rate\n phoneme_len = self.process_settings.get('phoneme_len', 2048)\n ignore_shorter_phonemes = self.process_settings.get(\n 'ignore_shorter_phonemes', True)\n mfcc_nfft = self.process_settings.get('mfcc_nfft', 2048)\n mfcc_winstep = self.process_settings.get('mfcc_winstep', 0.1)\n with open(phonemes_result_path, 'r') as f:\n schema = DecoderOutputSchema()\n json_file = json.load(f)\n phonemes_result = schema.load(json_file)\n phonemes_info = [info for info in phonemes_result[\n 'segment_info'] if info['word'] not in self.\n blacklisted_phonemes]\n mfcc_result = []\n for info in phonemes_info:\n start, stop = 1000 * info['start'], 1000 * info['end']\n segment = np.array(wav[start:stop].get_array_of_samples())\n if ignore_shorter_phonemes and segment.size < phoneme_len:\n continue\n mfcc_features = mfcc(segment, samplerate=frequency, nfft=\n mfcc_nfft, winstep=mfcc_winstep)\n for i in range(len(mfcc_features)):\n ith_mfcc = np.array(mfcc_features[i, :])\n ith_mfcc_result_row = {'i': i, 'length': len(mfcc_features),\n 'mfcc': ith_mfcc, **info}\n mfcc_result.append(ith_mfcc_result_row)\n return mfcc_result\n", "step-2": "<mask token>\n\n\nclass MfccLocal(Mfcc):\n \"\"\"\n MfccLocal computes Mfcc features for each phoneme from the sample\n that are not blacklisted based on phoneme label that is\n received from Phoneme chain.\n\n It subclasses Formants to not repeat the sample_layer logic\n which is valid also in this context\n \"\"\"\n abstract_class = False\n\n @staticmethod\n def sample_result_filename(out_sample_path):\n return f'{out_sample_path[:-5]}_mfcc_result.json'\n\n @staticmethod\n def filenames_to_skip_sample(out_sample_path):\n return [f'{out_sample_path[:-5]}_mfcc_result.csv']\n\n @staticmethod\n def serialize_to_json(mfcc_result):\n \"\"\"\n :param mfcc_result: list of mfcc measurements with\n necessary metadata\n :return: serialized object of proper schema\n \"\"\"\n mfcc_schema = MfccLocalSchema()\n mfcc_dict = {'mfcc_info': mfcc_result}\n return mfcc_schema.dumps(mfcc_dict)\n\n def compute_mfcc(self, segments_path, phonemes_result_path):\n \"\"\"\n\n :param segments_path: path to the input wav\n :param phonemes_result_path: path to phonemes results\n that is required by the Local version of the Mfcc\n :return: computed list of mfcc features with all required metadata\n \"\"\"\n wav = get_segment(segments_path, 'wav')\n frequency = wav.frame_rate\n phoneme_len = self.process_settings.get('phoneme_len', 2048)\n ignore_shorter_phonemes = self.process_settings.get(\n 'ignore_shorter_phonemes', True)\n mfcc_nfft = self.process_settings.get('mfcc_nfft', 2048)\n mfcc_winstep = self.process_settings.get('mfcc_winstep', 0.1)\n with open(phonemes_result_path, 'r') as f:\n schema = DecoderOutputSchema()\n json_file = json.load(f)\n phonemes_result = schema.load(json_file)\n phonemes_info = [info for info in phonemes_result[\n 'segment_info'] if info['word'] not in self.\n blacklisted_phonemes]\n mfcc_result = []\n for info in phonemes_info:\n start, stop = 1000 * info['start'], 1000 * info['end']\n segment = np.array(wav[start:stop].get_array_of_samples())\n if ignore_shorter_phonemes and segment.size < phoneme_len:\n continue\n mfcc_features = mfcc(segment, samplerate=frequency, nfft=\n mfcc_nfft, winstep=mfcc_winstep)\n for i in range(len(mfcc_features)):\n ith_mfcc = np.array(mfcc_features[i, :])\n ith_mfcc_result_row = {'i': i, 'length': len(mfcc_features),\n 'mfcc': ith_mfcc, **info}\n mfcc_result.append(ith_mfcc_result_row)\n return mfcc_result\n", "step-3": "<mask token>\nlogger = logging.getLogger()\n\n\nclass MfccLocal(Mfcc):\n \"\"\"\n MfccLocal computes Mfcc features for each phoneme from the sample\n that are not blacklisted based on phoneme label that is\n received from Phoneme chain.\n\n It subclasses Formants to not repeat the sample_layer logic\n which is valid also in this context\n \"\"\"\n abstract_class = False\n\n @staticmethod\n def sample_result_filename(out_sample_path):\n return f'{out_sample_path[:-5]}_mfcc_result.json'\n\n @staticmethod\n def filenames_to_skip_sample(out_sample_path):\n return [f'{out_sample_path[:-5]}_mfcc_result.csv']\n\n @staticmethod\n def serialize_to_json(mfcc_result):\n \"\"\"\n :param mfcc_result: list of mfcc measurements with\n necessary metadata\n :return: serialized object of proper schema\n \"\"\"\n mfcc_schema = MfccLocalSchema()\n mfcc_dict = {'mfcc_info': mfcc_result}\n return mfcc_schema.dumps(mfcc_dict)\n\n def compute_mfcc(self, segments_path, phonemes_result_path):\n \"\"\"\n\n :param segments_path: path to the input wav\n :param phonemes_result_path: path to phonemes results\n that is required by the Local version of the Mfcc\n :return: computed list of mfcc features with all required metadata\n \"\"\"\n wav = get_segment(segments_path, 'wav')\n frequency = wav.frame_rate\n phoneme_len = self.process_settings.get('phoneme_len', 2048)\n ignore_shorter_phonemes = self.process_settings.get(\n 'ignore_shorter_phonemes', True)\n mfcc_nfft = self.process_settings.get('mfcc_nfft', 2048)\n mfcc_winstep = self.process_settings.get('mfcc_winstep', 0.1)\n with open(phonemes_result_path, 'r') as f:\n schema = DecoderOutputSchema()\n json_file = json.load(f)\n phonemes_result = schema.load(json_file)\n phonemes_info = [info for info in phonemes_result[\n 'segment_info'] if info['word'] not in self.\n blacklisted_phonemes]\n mfcc_result = []\n for info in phonemes_info:\n start, stop = 1000 * info['start'], 1000 * info['end']\n segment = np.array(wav[start:stop].get_array_of_samples())\n if ignore_shorter_phonemes and segment.size < phoneme_len:\n continue\n mfcc_features = mfcc(segment, samplerate=frequency, nfft=\n mfcc_nfft, winstep=mfcc_winstep)\n for i in range(len(mfcc_features)):\n ith_mfcc = np.array(mfcc_features[i, :])\n ith_mfcc_result_row = {'i': i, 'length': len(mfcc_features),\n 'mfcc': ith_mfcc, **info}\n mfcc_result.append(ith_mfcc_result_row)\n return mfcc_result\n", "step-4": "import json\nimport logging\nimport numpy as np\nfrom python_speech_features import mfcc\nfrom format_converters import get_segment\nfrom schemas import *\nfrom chains.mfcc import Mfcc\nlogger = logging.getLogger()\n\n\nclass MfccLocal(Mfcc):\n \"\"\"\n MfccLocal computes Mfcc features for each phoneme from the sample\n that are not blacklisted based on phoneme label that is\n received from Phoneme chain.\n\n It subclasses Formants to not repeat the sample_layer logic\n which is valid also in this context\n \"\"\"\n abstract_class = False\n\n @staticmethod\n def sample_result_filename(out_sample_path):\n return f'{out_sample_path[:-5]}_mfcc_result.json'\n\n @staticmethod\n def filenames_to_skip_sample(out_sample_path):\n return [f'{out_sample_path[:-5]}_mfcc_result.csv']\n\n @staticmethod\n def serialize_to_json(mfcc_result):\n \"\"\"\n :param mfcc_result: list of mfcc measurements with\n necessary metadata\n :return: serialized object of proper schema\n \"\"\"\n mfcc_schema = MfccLocalSchema()\n mfcc_dict = {'mfcc_info': mfcc_result}\n return mfcc_schema.dumps(mfcc_dict)\n\n def compute_mfcc(self, segments_path, phonemes_result_path):\n \"\"\"\n\n :param segments_path: path to the input wav\n :param phonemes_result_path: path to phonemes results\n that is required by the Local version of the Mfcc\n :return: computed list of mfcc features with all required metadata\n \"\"\"\n wav = get_segment(segments_path, 'wav')\n frequency = wav.frame_rate\n phoneme_len = self.process_settings.get('phoneme_len', 2048)\n ignore_shorter_phonemes = self.process_settings.get(\n 'ignore_shorter_phonemes', True)\n mfcc_nfft = self.process_settings.get('mfcc_nfft', 2048)\n mfcc_winstep = self.process_settings.get('mfcc_winstep', 0.1)\n with open(phonemes_result_path, 'r') as f:\n schema = DecoderOutputSchema()\n json_file = json.load(f)\n phonemes_result = schema.load(json_file)\n phonemes_info = [info for info in phonemes_result[\n 'segment_info'] if info['word'] not in self.\n blacklisted_phonemes]\n mfcc_result = []\n for info in phonemes_info:\n start, stop = 1000 * info['start'], 1000 * info['end']\n segment = np.array(wav[start:stop].get_array_of_samples())\n if ignore_shorter_phonemes and segment.size < phoneme_len:\n continue\n mfcc_features = mfcc(segment, samplerate=frequency, nfft=\n mfcc_nfft, winstep=mfcc_winstep)\n for i in range(len(mfcc_features)):\n ith_mfcc = np.array(mfcc_features[i, :])\n ith_mfcc_result_row = {'i': i, 'length': len(mfcc_features),\n 'mfcc': ith_mfcc, **info}\n mfcc_result.append(ith_mfcc_result_row)\n return mfcc_result\n", "step-5": "import json\nimport logging\n\nimport numpy as np\nfrom python_speech_features import mfcc\n\nfrom format_converters import get_segment\nfrom schemas import *\nfrom chains.mfcc import Mfcc\nlogger = logging.getLogger()\n\n\nclass MfccLocal(Mfcc):\n \"\"\"\n MfccLocal computes Mfcc features for each phoneme from the sample\n that are not blacklisted based on phoneme label that is\n received from Phoneme chain.\n\n It subclasses Formants to not repeat the sample_layer logic\n which is valid also in this context\n \"\"\"\n\n abstract_class = False\n\n @staticmethod\n def sample_result_filename(out_sample_path):\n return f'{out_sample_path[:-5]}_mfcc_result.json'\n\n @staticmethod\n def filenames_to_skip_sample(out_sample_path):\n return [f'{out_sample_path[:-5]}_mfcc_result.csv']\n\n @staticmethod\n def serialize_to_json(mfcc_result):\n \"\"\"\n :param mfcc_result: list of mfcc measurements with\n necessary metadata\n :return: serialized object of proper schema\n \"\"\"\n mfcc_schema = MfccLocalSchema()\n mfcc_dict = {'mfcc_info': mfcc_result}\n return mfcc_schema.dumps(mfcc_dict)\n\n def compute_mfcc(self, segments_path, phonemes_result_path):\n \"\"\"\n\n :param segments_path: path to the input wav\n :param phonemes_result_path: path to phonemes results\n that is required by the Local version of the Mfcc\n :return: computed list of mfcc features with all required metadata\n \"\"\"\n wav = get_segment(segments_path, 'wav')\n frequency = wav.frame_rate\n phoneme_len = self.process_settings.get(\"phoneme_len\", 2048)\n ignore_shorter_phonemes = self.process_settings.get(\"ignore_shorter_phonemes\", True)\n mfcc_nfft = self.process_settings.get(\"mfcc_nfft\", 2048)\n mfcc_winstep = self.process_settings.get(\"mfcc_winstep\", 0.1)\n\n with open(phonemes_result_path, 'r') as f:\n schema = DecoderOutputSchema()\n json_file = json.load(f)\n phonemes_result = schema.load(json_file)\n phonemes_info = [info for info in phonemes_result['segment_info']\n if info['word'] not in self.blacklisted_phonemes]\n\n mfcc_result = []\n for info in phonemes_info:\n start, stop = (1000 * info['start'], 1000 * info['end'])\n segment = np.array(wav[start:stop].get_array_of_samples())\n if ignore_shorter_phonemes and segment.size < phoneme_len:\n continue\n mfcc_features = mfcc(segment, samplerate=frequency,\n nfft=mfcc_nfft, winstep=mfcc_winstep)\n for i in range(len(mfcc_features)):\n ith_mfcc = np.array(mfcc_features[i, :])\n ith_mfcc_result_row = {'i': i, 'length': len(mfcc_features),\n 'mfcc': ith_mfcc, **info}\n mfcc_result.append(ith_mfcc_result_row)\n return mfcc_result", "step-ids": [ 6, 7, 8, 9, 10 ] }
[ 6, 7, 8, 9, 10 ]
import numpy from scipy.spatial.distance import cosine def similarity_metric(embedding1: numpy.ndarray, embedding2: numpy.ndarray ) ->float: return numpy.nan_to_num(1 - cosine(embedding1, embedding2), 0)
normal
{ "blob_id": "ec9f27b4313f72ae6eb7e8280d47de226aeb6bb1", "index": 2270, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef similarity_metric(embedding1: numpy.ndarray, embedding2: numpy.ndarray\n ) ->float:\n return numpy.nan_to_num(1 - cosine(embedding1, embedding2), 0)\n", "step-3": "import numpy\nfrom scipy.spatial.distance import cosine\n\n\ndef similarity_metric(embedding1: numpy.ndarray, embedding2: numpy.ndarray\n ) ->float:\n return numpy.nan_to_num(1 - cosine(embedding1, embedding2), 0)\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> class Model(nn.Module): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Model(nn.Module): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> def forward(self, pov, feats): pov = self.image_embed(pov) full_embed = self.l1(torch.cat((pov, feats), dim=1)) full_embed = self.r1(full_embed) out = self.out(full_embed) return out <|reserved_special_token_1|> <|reserved_special_token_0|> class Model(nn.Module): """Example usage: model = Model() outputs = model(pov_tensor, feat_tensor) """ def __init__(self): super(Model, self).__init__() self.image_embed = nn.Sequential(nn.BatchNorm2d(3), nn.Conv2d(3, 16, 5, stride=2), nn.MaxPool2d(2, 2), nn.LeakyReLU(True), nn. BatchNorm2d(16), nn.Conv2d(16, 24, 3), nn.MaxPool2d(2, 2), nn. LeakyReLU(True), nn.BatchNorm2d(24), nn.Conv2d(24, 24, 3), nn. MaxPool2d(2, 2), nn.LeakyReLU(True), nn.BatchNorm2d(24), nn. Flatten(), nn.Linear(96, 50)) self.l1 = nn.Linear(50 + 2, 50) self.r1 = nn.LeakyReLU() self.out = nn.Linear(50, 11) """Model to approximate Q values. Input ----- pov: (batch_size, 3, 64, 64) tensor of player view input_size: (batch_size, 2) Returns ------- action: (batch_size, 9) tensor with indicies: 0: attack probability 1-5: CAMERA_OPTIONS[0-4] 6: forward probability 7: jump probability 8: place probability """ def forward(self, pov, feats): pov = self.image_embed(pov) full_embed = self.l1(torch.cat((pov, feats), dim=1)) full_embed = self.r1(full_embed) out = self.out(full_embed) return out <|reserved_special_token_1|> import numpy as np import torch import torch.nn as nn from utils import * from collections import OrderedDict from torchsummary import summary class Model(nn.Module): """Example usage: model = Model() outputs = model(pov_tensor, feat_tensor) """ def __init__(self): super(Model, self).__init__() self.image_embed = nn.Sequential(nn.BatchNorm2d(3), nn.Conv2d(3, 16, 5, stride=2), nn.MaxPool2d(2, 2), nn.LeakyReLU(True), nn. BatchNorm2d(16), nn.Conv2d(16, 24, 3), nn.MaxPool2d(2, 2), nn. LeakyReLU(True), nn.BatchNorm2d(24), nn.Conv2d(24, 24, 3), nn. MaxPool2d(2, 2), nn.LeakyReLU(True), nn.BatchNorm2d(24), nn. Flatten(), nn.Linear(96, 50)) self.l1 = nn.Linear(50 + 2, 50) self.r1 = nn.LeakyReLU() self.out = nn.Linear(50, 11) """Model to approximate Q values. Input ----- pov: (batch_size, 3, 64, 64) tensor of player view input_size: (batch_size, 2) Returns ------- action: (batch_size, 9) tensor with indicies: 0: attack probability 1-5: CAMERA_OPTIONS[0-4] 6: forward probability 7: jump probability 8: place probability """ def forward(self, pov, feats): pov = self.image_embed(pov) full_embed = self.l1(torch.cat((pov, feats), dim=1)) full_embed = self.r1(full_embed) out = self.out(full_embed) return out <|reserved_special_token_1|> import numpy as np import torch import torch.nn as nn from utils import * from collections import OrderedDict from torchsummary import summary class Model(nn.Module): """Example usage: model = Model() outputs = model(pov_tensor, feat_tensor) """ def __init__(self): super(Model, self).__init__() # Convolutional network architecture self.image_embed = nn.Sequential( nn.BatchNorm2d(3), nn.Conv2d(3, 16, 5, stride=2), nn.MaxPool2d(2, 2), nn.LeakyReLU(True), nn.BatchNorm2d(16), nn.Conv2d(16, 24, 3), nn.MaxPool2d(2, 2), nn.LeakyReLU(True), nn.BatchNorm2d(24), nn.Conv2d(24, 24, 3), nn.MaxPool2d(2, 2), nn.LeakyReLU(True), nn.BatchNorm2d(24), nn.Flatten(), nn.Linear(96, 50), ) # Regularization layer self.l1 = nn.Linear(50 + 2, 50) self.r1 = nn.LeakyReLU() self.out = nn.Linear(50, 11) """Model to approximate Q values. Input ----- pov: (batch_size, 3, 64, 64) tensor of player view input_size: (batch_size, 2) Returns ------- action: (batch_size, 9) tensor with indicies: 0: attack probability 1-5: CAMERA_OPTIONS[0-4] 6: forward probability 7: jump probability 8: place probability """ def forward(self, pov, feats): pov = self.image_embed(pov) full_embed = self.l1(torch.cat((pov, feats), dim=1)) full_embed = self.r1(full_embed) out = self.out(full_embed) return out
flexible
{ "blob_id": "981cfecdb50b5f3ae326bf3103163f6e814ccc95", "index": 6857, "step-1": "<mask token>\n\n\nclass Model(nn.Module):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass Model(nn.Module):\n <mask token>\n <mask token>\n <mask token>\n\n def forward(self, pov, feats):\n pov = self.image_embed(pov)\n full_embed = self.l1(torch.cat((pov, feats), dim=1))\n full_embed = self.r1(full_embed)\n out = self.out(full_embed)\n return out\n", "step-3": "<mask token>\n\n\nclass Model(nn.Module):\n \"\"\"Example usage:\n\n model = Model()\n outputs = model(pov_tensor, feat_tensor)\n \"\"\"\n\n def __init__(self):\n super(Model, self).__init__()\n self.image_embed = nn.Sequential(nn.BatchNorm2d(3), nn.Conv2d(3, 16,\n 5, stride=2), nn.MaxPool2d(2, 2), nn.LeakyReLU(True), nn.\n BatchNorm2d(16), nn.Conv2d(16, 24, 3), nn.MaxPool2d(2, 2), nn.\n LeakyReLU(True), nn.BatchNorm2d(24), nn.Conv2d(24, 24, 3), nn.\n MaxPool2d(2, 2), nn.LeakyReLU(True), nn.BatchNorm2d(24), nn.\n Flatten(), nn.Linear(96, 50))\n self.l1 = nn.Linear(50 + 2, 50)\n self.r1 = nn.LeakyReLU()\n self.out = nn.Linear(50, 11)\n \"\"\"Model to approximate Q values.\n\n Input\n -----\n pov: (batch_size, 3, 64, 64) tensor of player view\n input_size: (batch_size, 2)\n\n Returns\n -------\n action: (batch_size, 9) tensor with indicies:\n 0: attack probability\n 1-5: CAMERA_OPTIONS[0-4]\n 6: forward probability\n 7: jump probability\n 8: place probability\n\n \"\"\"\n\n def forward(self, pov, feats):\n pov = self.image_embed(pov)\n full_embed = self.l1(torch.cat((pov, feats), dim=1))\n full_embed = self.r1(full_embed)\n out = self.out(full_embed)\n return out\n", "step-4": "import numpy as np\nimport torch\nimport torch.nn as nn\nfrom utils import *\nfrom collections import OrderedDict\nfrom torchsummary import summary\n\n\nclass Model(nn.Module):\n \"\"\"Example usage:\n\n model = Model()\n outputs = model(pov_tensor, feat_tensor)\n \"\"\"\n\n def __init__(self):\n super(Model, self).__init__()\n self.image_embed = nn.Sequential(nn.BatchNorm2d(3), nn.Conv2d(3, 16,\n 5, stride=2), nn.MaxPool2d(2, 2), nn.LeakyReLU(True), nn.\n BatchNorm2d(16), nn.Conv2d(16, 24, 3), nn.MaxPool2d(2, 2), nn.\n LeakyReLU(True), nn.BatchNorm2d(24), nn.Conv2d(24, 24, 3), nn.\n MaxPool2d(2, 2), nn.LeakyReLU(True), nn.BatchNorm2d(24), nn.\n Flatten(), nn.Linear(96, 50))\n self.l1 = nn.Linear(50 + 2, 50)\n self.r1 = nn.LeakyReLU()\n self.out = nn.Linear(50, 11)\n \"\"\"Model to approximate Q values.\n\n Input\n -----\n pov: (batch_size, 3, 64, 64) tensor of player view\n input_size: (batch_size, 2)\n\n Returns\n -------\n action: (batch_size, 9) tensor with indicies:\n 0: attack probability\n 1-5: CAMERA_OPTIONS[0-4]\n 6: forward probability\n 7: jump probability\n 8: place probability\n\n \"\"\"\n\n def forward(self, pov, feats):\n pov = self.image_embed(pov)\n full_embed = self.l1(torch.cat((pov, feats), dim=1))\n full_embed = self.r1(full_embed)\n out = self.out(full_embed)\n return out\n", "step-5": "import numpy as np\nimport torch\nimport torch.nn as nn\nfrom utils import *\nfrom collections import OrderedDict\nfrom torchsummary import summary\n\n\nclass Model(nn.Module):\n \"\"\"Example usage:\n\n model = Model()\n outputs = model(pov_tensor, feat_tensor)\n \"\"\"\n def __init__(self):\n super(Model, self).__init__()\n # Convolutional network architecture\n self.image_embed = nn.Sequential(\n nn.BatchNorm2d(3),\n nn.Conv2d(3, 16, 5, stride=2),\n nn.MaxPool2d(2, 2),\n nn.LeakyReLU(True),\n nn.BatchNorm2d(16),\n nn.Conv2d(16, 24, 3),\n nn.MaxPool2d(2, 2),\n nn.LeakyReLU(True),\n nn.BatchNorm2d(24),\n nn.Conv2d(24, 24, 3),\n nn.MaxPool2d(2, 2),\n nn.LeakyReLU(True),\n nn.BatchNorm2d(24),\n nn.Flatten(),\n nn.Linear(96, 50),\n )\n # Regularization layer\n self.l1 = nn.Linear(50 + 2, 50)\n self.r1 = nn.LeakyReLU()\n self.out = nn.Linear(50, 11)\n\n \"\"\"Model to approximate Q values.\n\n Input\n -----\n pov: (batch_size, 3, 64, 64) tensor of player view\n input_size: (batch_size, 2)\n\n Returns\n -------\n action: (batch_size, 9) tensor with indicies:\n 0: attack probability\n 1-5: CAMERA_OPTIONS[0-4]\n 6: forward probability\n 7: jump probability\n 8: place probability\n\n \"\"\"\n def forward(self, pov, feats):\n pov = self.image_embed(pov)\n full_embed = self.l1(torch.cat((pov, feats), dim=1))\n full_embed = self.r1(full_embed)\n out = self.out(full_embed)\n return out\n", "step-ids": [ 1, 2, 4, 5, 6 ] }
[ 1, 2, 4, 5, 6 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): initial = True dependencies = [] operations = [migrations.CreateModel(name='OpenHumansMember', fields=[( 'oh_id', models.CharField(max_length=16, primary_key=True, serialize=False, unique=True)), ('access_token', models.CharField( max_length=256)), ('refresh_token', models.CharField(max_length=256 )), ('token_expires', models.DateTimeField()), ('seeq_id', models. IntegerField(null=True))])] <|reserved_special_token_1|> from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [] operations = [migrations.CreateModel(name='OpenHumansMember', fields=[( 'oh_id', models.CharField(max_length=16, primary_key=True, serialize=False, unique=True)), ('access_token', models.CharField( max_length=256)), ('refresh_token', models.CharField(max_length=256 )), ('token_expires', models.DateTimeField()), ('seeq_id', models. IntegerField(null=True))])] <|reserved_special_token_1|> # -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2016-12-19 15:25 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='OpenHumansMember', fields=[ ('oh_id', models.CharField(max_length=16, primary_key=True, serialize=False, unique=True)), ('access_token', models.CharField(max_length=256)), ('refresh_token', models.CharField(max_length=256)), ('token_expires', models.DateTimeField()), ('seeq_id', models.IntegerField(null=True)), ], ), ]
flexible
{ "blob_id": "28854823b1edc7df6cf025175811c1858efd2c42", "index": 862, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n initial = True\n dependencies = []\n operations = [migrations.CreateModel(name='OpenHumansMember', fields=[(\n 'oh_id', models.CharField(max_length=16, primary_key=True,\n serialize=False, unique=True)), ('access_token', models.CharField(\n max_length=256)), ('refresh_token', models.CharField(max_length=256\n )), ('token_expires', models.DateTimeField()), ('seeq_id', models.\n IntegerField(null=True))])]\n", "step-4": "from __future__ import unicode_literals\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n initial = True\n dependencies = []\n operations = [migrations.CreateModel(name='OpenHumansMember', fields=[(\n 'oh_id', models.CharField(max_length=16, primary_key=True,\n serialize=False, unique=True)), ('access_token', models.CharField(\n max_length=256)), ('refresh_token', models.CharField(max_length=256\n )), ('token_expires', models.DateTimeField()), ('seeq_id', models.\n IntegerField(null=True))])]\n", "step-5": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.4 on 2016-12-19 15:25\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='OpenHumansMember',\n fields=[\n ('oh_id', models.CharField(max_length=16, primary_key=True, serialize=False, unique=True)),\n ('access_token', models.CharField(max_length=256)),\n ('refresh_token', models.CharField(max_length=256)),\n ('token_expires', models.DateTimeField()),\n ('seeq_id', models.IntegerField(null=True)),\n ],\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Migration(migrations.Migration): dependencies = [('restaurante', '0003_auto_20210324_1932')] operations = [migrations.AlterModelOptions(name='comprobantemodel', options={'verbose_name': 'Comprobante'}), migrations. AlterModelTable(name='comprobantemodel', table='t_comprobante')] <|reserved_special_token_1|> from django.db import migrations class Migration(migrations.Migration): dependencies = [('restaurante', '0003_auto_20210324_1932')] operations = [migrations.AlterModelOptions(name='comprobantemodel', options={'verbose_name': 'Comprobante'}), migrations. AlterModelTable(name='comprobantemodel', table='t_comprobante')] <|reserved_special_token_1|> # Generated by Django 3.1.7 on 2021-03-25 00:33 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('restaurante', '0003_auto_20210324_1932'), ] operations = [ migrations.AlterModelOptions( name='comprobantemodel', options={'verbose_name': 'Comprobante'}, ), migrations.AlterModelTable( name='comprobantemodel', table='t_comprobante', ), ]
flexible
{ "blob_id": "f76a3fac75e7e2b156f4bff5094f11009b65b599", "index": 8822, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('restaurante', '0003_auto_20210324_1932')]\n operations = [migrations.AlterModelOptions(name='comprobantemodel',\n options={'verbose_name': 'Comprobante'}), migrations.\n AlterModelTable(name='comprobantemodel', table='t_comprobante')]\n", "step-4": "from django.db import migrations\n\n\nclass Migration(migrations.Migration):\n dependencies = [('restaurante', '0003_auto_20210324_1932')]\n operations = [migrations.AlterModelOptions(name='comprobantemodel',\n options={'verbose_name': 'Comprobante'}), migrations.\n AlterModelTable(name='comprobantemodel', table='t_comprobante')]\n", "step-5": "# Generated by Django 3.1.7 on 2021-03-25 00:33\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('restaurante', '0003_auto_20210324_1932'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='comprobantemodel',\n options={'verbose_name': 'Comprobante'},\n ),\n migrations.AlterModelTable(\n name='comprobantemodel',\n table='t_comprobante',\n ),\n ]\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python3 import re import subprocess PREFIX = "Enclave/" OBJ_FILES = [ # "Enclave.o", "p_block.o", # "symbols.o", "runtime.o", "primitives.o", "unary_op.o", "unary/isna.o", "unary/mathgen.o", "unary/mathtrig.o", "unary/plusminus.o", "unary/summary.o", "unary/print.o", # data dependent by design "unary/ustats.o", # only the opcode for the dispatch, not the actual. "binary_op.o", "binary/arith.o", "binary/bstats.o", # only the opcode for the dispatch, not the actual. "binary/log_bin.o", "binary/logic.o", "binary/matmul.o", "binary/compare.o", "binary/pminmax.o", "binary/bstats.o", ] CONDITIONALS = [ ] # LIBFTFP = set(['add','mov','pop','setg','and','movabs','push','setl', 'call','movsd','rep','setle','cdqe','movsx','ret','setne','cmp','movsxd','sar','shl', 'imul','movzx','sbb','shr','je','mul','seta','sub', 'jmp','neg','setae','test', 'jne','not','setbe','xor', 'lea','or','sete']) - set(['jne', 'je']) LIBFTFP = set(['add','mov','pop','setg','and','movabs','push','setl', 'call','movsd','rep','setle','cdqe','movsx','ret','setne','cmp','movsxd','sar','shl', 'imul','movzx','sbb','shr','je','mul','seta','sub', 'jmp','neg','setae','test', 'jne','not','setbe','xor', 'lea','or','sete']) SKIP = ['nop',] opcodes = set() cond_results = {} # subprocess.run(["make", "-f", "split.makefile", "clean"], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) # subprocess.run(["make", "-f", "split.makefile", "all"], check=True) for obj_file in OBJ_FILES: cond_results[obj_file] = set() dump = subprocess.run(["objdump", "-M", "intel", "-dr", PREFIX + obj_file], stdout=subprocess.PIPE, check=True).stdout for line in dump.decode("utf-8").split("\n"): cols = line.split('\t') if len(cols) > 2: new_code = re.sub(' .*', '', cols[2]) if new_code == '': continue # if new_code in CONDITIONALS: if new_code not in LIBFTFP and new_code not in SKIP: cond_results[obj_file].add(new_code) opcodes.add(new_code) # print(sorted(opcodes)) print(sorted(opcodes - LIBFTFP)) for k,v in cond_results.items(): print(k,sorted(v)) combo = LIBFTFP.copy() # for s in ['ja', 'jae', 'jb', 'je', 'jne', 'jge', 'jle', 'repz', 'cmovne', 'movq', 'jns']: # combo.add(s) combo.add("cmovne") combo = sorted(combo) for i in range(0, len(combo)): print(r'\texttt{' + combo[i] + '}', end='') if combo[i] not in LIBFTFP: print('*', end='') if i % 5 == 4: print(r' \\') else: print(' & ', end='')
normal
{ "blob_id": "45d69194e14e8c20161e979d4ff34d0b90df4672", "index": 4750, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor obj_file in OBJ_FILES:\n cond_results[obj_file] = set()\n dump = subprocess.run(['objdump', '-M', 'intel', '-dr', PREFIX +\n obj_file], stdout=subprocess.PIPE, check=True).stdout\n for line in dump.decode('utf-8').split('\\n'):\n cols = line.split('\\t')\n if len(cols) > 2:\n new_code = re.sub(' .*', '', cols[2])\n if new_code == '':\n continue\n if new_code not in LIBFTFP and new_code not in SKIP:\n cond_results[obj_file].add(new_code)\n opcodes.add(new_code)\nprint(sorted(opcodes - LIBFTFP))\nfor k, v in cond_results.items():\n print(k, sorted(v))\n<mask token>\ncombo.add('cmovne')\n<mask token>\nfor i in range(0, len(combo)):\n print('\\\\texttt{' + combo[i] + '}', end='')\n if combo[i] not in LIBFTFP:\n print('*', end='')\n if i % 5 == 4:\n print(' \\\\\\\\')\n else:\n print(' & ', end='')\n", "step-3": "<mask token>\nPREFIX = 'Enclave/'\nOBJ_FILES = ['p_block.o', 'runtime.o', 'primitives.o', 'unary_op.o',\n 'unary/isna.o', 'unary/mathgen.o', 'unary/mathtrig.o',\n 'unary/plusminus.o', 'unary/summary.o', 'unary/print.o',\n 'unary/ustats.o', 'binary_op.o', 'binary/arith.o', 'binary/bstats.o',\n 'binary/log_bin.o', 'binary/logic.o', 'binary/matmul.o',\n 'binary/compare.o', 'binary/pminmax.o', 'binary/bstats.o']\nCONDITIONALS = []\nLIBFTFP = set(['add', 'mov', 'pop', 'setg', 'and', 'movabs', 'push', 'setl',\n 'call', 'movsd', 'rep', 'setle', 'cdqe', 'movsx', 'ret', 'setne', 'cmp',\n 'movsxd', 'sar', 'shl', 'imul', 'movzx', 'sbb', 'shr', 'je', 'mul',\n 'seta', 'sub', 'jmp', 'neg', 'setae', 'test', 'jne', 'not', 'setbe',\n 'xor', 'lea', 'or', 'sete'])\nSKIP = ['nop']\nopcodes = set()\ncond_results = {}\nfor obj_file in OBJ_FILES:\n cond_results[obj_file] = set()\n dump = subprocess.run(['objdump', '-M', 'intel', '-dr', PREFIX +\n obj_file], stdout=subprocess.PIPE, check=True).stdout\n for line in dump.decode('utf-8').split('\\n'):\n cols = line.split('\\t')\n if len(cols) > 2:\n new_code = re.sub(' .*', '', cols[2])\n if new_code == '':\n continue\n if new_code not in LIBFTFP and new_code not in SKIP:\n cond_results[obj_file].add(new_code)\n opcodes.add(new_code)\nprint(sorted(opcodes - LIBFTFP))\nfor k, v in cond_results.items():\n print(k, sorted(v))\ncombo = LIBFTFP.copy()\ncombo.add('cmovne')\ncombo = sorted(combo)\nfor i in range(0, len(combo)):\n print('\\\\texttt{' + combo[i] + '}', end='')\n if combo[i] not in LIBFTFP:\n print('*', end='')\n if i % 5 == 4:\n print(' \\\\\\\\')\n else:\n print(' & ', end='')\n", "step-4": "import re\nimport subprocess\nPREFIX = 'Enclave/'\nOBJ_FILES = ['p_block.o', 'runtime.o', 'primitives.o', 'unary_op.o',\n 'unary/isna.o', 'unary/mathgen.o', 'unary/mathtrig.o',\n 'unary/plusminus.o', 'unary/summary.o', 'unary/print.o',\n 'unary/ustats.o', 'binary_op.o', 'binary/arith.o', 'binary/bstats.o',\n 'binary/log_bin.o', 'binary/logic.o', 'binary/matmul.o',\n 'binary/compare.o', 'binary/pminmax.o', 'binary/bstats.o']\nCONDITIONALS = []\nLIBFTFP = set(['add', 'mov', 'pop', 'setg', 'and', 'movabs', 'push', 'setl',\n 'call', 'movsd', 'rep', 'setle', 'cdqe', 'movsx', 'ret', 'setne', 'cmp',\n 'movsxd', 'sar', 'shl', 'imul', 'movzx', 'sbb', 'shr', 'je', 'mul',\n 'seta', 'sub', 'jmp', 'neg', 'setae', 'test', 'jne', 'not', 'setbe',\n 'xor', 'lea', 'or', 'sete'])\nSKIP = ['nop']\nopcodes = set()\ncond_results = {}\nfor obj_file in OBJ_FILES:\n cond_results[obj_file] = set()\n dump = subprocess.run(['objdump', '-M', 'intel', '-dr', PREFIX +\n obj_file], stdout=subprocess.PIPE, check=True).stdout\n for line in dump.decode('utf-8').split('\\n'):\n cols = line.split('\\t')\n if len(cols) > 2:\n new_code = re.sub(' .*', '', cols[2])\n if new_code == '':\n continue\n if new_code not in LIBFTFP and new_code not in SKIP:\n cond_results[obj_file].add(new_code)\n opcodes.add(new_code)\nprint(sorted(opcodes - LIBFTFP))\nfor k, v in cond_results.items():\n print(k, sorted(v))\ncombo = LIBFTFP.copy()\ncombo.add('cmovne')\ncombo = sorted(combo)\nfor i in range(0, len(combo)):\n print('\\\\texttt{' + combo[i] + '}', end='')\n if combo[i] not in LIBFTFP:\n print('*', end='')\n if i % 5 == 4:\n print(' \\\\\\\\')\n else:\n print(' & ', end='')\n", "step-5": "#!/usr/bin/env python3\nimport re\nimport subprocess\n\nPREFIX = \"Enclave/\"\nOBJ_FILES = [\n # \"Enclave.o\",\n \"p_block.o\",\n # \"symbols.o\",\n \"runtime.o\",\n \"primitives.o\",\n \"unary_op.o\",\n \"unary/isna.o\",\n \"unary/mathgen.o\",\n \"unary/mathtrig.o\",\n \"unary/plusminus.o\",\n \"unary/summary.o\",\n \"unary/print.o\", # data dependent by design\n \"unary/ustats.o\", # only the opcode for the dispatch, not the actual.\n \"binary_op.o\",\n \"binary/arith.o\",\n \"binary/bstats.o\", # only the opcode for the dispatch, not the actual.\n \"binary/log_bin.o\",\n \"binary/logic.o\",\n \"binary/matmul.o\",\n \"binary/compare.o\",\n \"binary/pminmax.o\",\n \"binary/bstats.o\",\n]\n\nCONDITIONALS = [\n]\n\n# LIBFTFP = set(['add','mov','pop','setg','and','movabs','push','setl', 'call','movsd','rep','setle','cdqe','movsx','ret','setne','cmp','movsxd','sar','shl', 'imul','movzx','sbb','shr','je','mul','seta','sub', 'jmp','neg','setae','test', 'jne','not','setbe','xor', 'lea','or','sete']) - set(['jne', 'je'])\nLIBFTFP = set(['add','mov','pop','setg','and','movabs','push','setl', 'call','movsd','rep','setle','cdqe','movsx','ret','setne','cmp','movsxd','sar','shl', 'imul','movzx','sbb','shr','je','mul','seta','sub', 'jmp','neg','setae','test', 'jne','not','setbe','xor', 'lea','or','sete'])\n\nSKIP = ['nop',]\n\nopcodes = set()\ncond_results = {}\n# subprocess.run([\"make\", \"-f\", \"split.makefile\", \"clean\"], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)\n# subprocess.run([\"make\", \"-f\", \"split.makefile\", \"all\"], check=True)\nfor obj_file in OBJ_FILES:\n cond_results[obj_file] = set()\n dump = subprocess.run([\"objdump\", \"-M\", \"intel\", \"-dr\", PREFIX + obj_file], stdout=subprocess.PIPE, check=True).stdout\n for line in dump.decode(\"utf-8\").split(\"\\n\"):\n cols = line.split('\\t')\n if len(cols) > 2:\n new_code = re.sub(' .*', '', cols[2])\n if new_code == '':\n continue\n # if new_code in CONDITIONALS:\n if new_code not in LIBFTFP and new_code not in SKIP:\n cond_results[obj_file].add(new_code)\n opcodes.add(new_code)\n\n\n# print(sorted(opcodes))\nprint(sorted(opcodes - LIBFTFP))\nfor k,v in cond_results.items():\n print(k,sorted(v))\n\ncombo = LIBFTFP.copy()\n# for s in ['ja', 'jae', 'jb', 'je', 'jne', 'jge', 'jle', 'repz', 'cmovne', 'movq', 'jns']:\n# combo.add(s)\ncombo.add(\"cmovne\")\ncombo = sorted(combo)\nfor i in range(0, len(combo)):\n print(r'\\texttt{' + combo[i] + '}', end='')\n if combo[i] not in LIBFTFP:\n print('*', end='')\n if i % 5 == 4:\n print(r' \\\\')\n else:\n print(' & ', end='')\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> class TrajectoryRectangle(TrajectoryBase): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> @property def top_left(self) ->Line: """ Line representing the trajectory of the point on the top left corner of the rectangle """ start = Point(self.shape.left_bound, self.shape.top_bound) return Line(start, start + self.velocity) <|reserved_special_token_0|> <|reserved_special_token_0|> class TrajectoryLine(TrajectoryRectangle): """ Create a bounding box around the line and compute the trajectory as if it were a rectangle. """ def __init__(self, shape: Line, velocity: Point): super(TrajectoryLine, self).__init__(shape, velocity) assert isinstance(shape, Line) self._reference = self.shape.start height = abs(self.shape.start.y - self.shape.end.y) width = abs(self.shape.start.x - self.shape.end.x) center = Point((self.shape.start.x + self.shape.end.x) / 2, (self. shape.start.y + self.shape.end.y) / 2) self.shape = Rectangle(height=height, width=width) self.shape.pos = center class TrajectoryPoint(TrajectoryBase): def __init__(self, shape: Point, velocity: Point): super(TrajectoryPoint, self).__init__(shape, velocity) assert isinstance(shape, Point) self._reference = self.shape @property def corners(self) ->Tuple[Line, ...]: return self._trajectory, @property def _trajectory(self) ->Line: return Line(self.shape, self.shape + self.velocity) @property def center(self) ->Line: return self._trajectory @property def top_right(self) ->Line: return self._trajectory @property def top_left(self) ->Line: return self._trajectory @property def bottom_right(self) ->Line: return self._trajectory @property def bottom_left(self) ->Line: return self._trajectory class Trajectory(object): def __new__(cls, shape: Shape, velocity: Point): if isinstance(shape, Point): return TrajectoryPoint(shape, velocity) elif isinstance(shape, Line): return TrajectoryLine(shape, velocity) elif isinstance(shape, Rectangle): return TrajectoryRectangle(shape, velocity) else: raise NotImplementedError( f'No implementation of Trajectory for input shape of type {type(shape)}' ) class Canvas(Rectangle): action_meanings = {(0): 'NOOP', (1): 'UP', (2): 'DOWN'} actions = {k: v for v, k in action_meanings.items()} def __init__(self, paddle_l: Paddle, paddle_r: Paddle, ball: Ball, snell: Snell, ball_speed: int, height: int, width: int, their_update_probability: float, refract: bool, uniform_speed: bool): super().__init__(height=height, width=width, visibility='none', render_value=0) self.pos = self.width / 2, self.height / 2 assert isinstance(their_update_probability, (float, int) ), f'their_update_probability must be numeric, not {type(their_update_probability)}' assert 0 <= their_update_probability <= 1, f'{their_update_probability} outside allowed bounds [0, 1]' self.their_update_probability = their_update_probability self.default_ball_speed = ball_speed self.snell = snell self.ball = ball self.paddle_l = paddle_l self.paddle_r = paddle_r self.sprites = [self, snell, paddle_l, paddle_r, ball] self.uniform_speed = uniform_speed self.refract = refract self.we_scored = False self.they_scored = False self.our_score = 0 self.their_score = 0 def register_sprite(self, sprite: Shape): assert issubclass(type(sprite), Shape ), f'sprite must be subclassed from Shape' self.sprites.insert(-1, sprite) @property def left_bound(self): return 0 @property def right_bound(self): return self.width @property def top_bound(self): return self.height @property def bottom_bound(self): return 0 def to_numpy(self) ->Tuple[np.ndarray, np.ndarray]: """ Performs masked rendering of objects in `self.sprites`. Priority is determined by the ordering of the list, earlier objects will be obscured by later ones. :return: (state, rendering) """ state = self._zero_rgb_image(round(self.height), round(self.width)) rendering = self._zero_rgb_image(round(self.height), round(self.width)) for sprite in self.sprites[1:]: sprite_state, sprite_rendering = sprite.to_numpy(self.height, self.width) state[sprite_state != 0] = sprite_state[sprite_state != 0] rendering[sprite_rendering != 0] = sprite_rendering[ sprite_rendering != 0] return state, rendering def score(self, who): """ Increment the score and reset the ball :param who: 'we' or 'they' :return: reward """ if who == 'they': reward = -1 self.their_score += 1 elif who == 'we': reward = 1 self.our_score += 1 else: raise ValueError(f"who must be 'we' or 'they', not {who}") self._reset_ball() return reward def step(self, action): self._move_our_paddle(action) self._step_their_paddle() reward = self._step_ball() self._step_snell() return reward def get_state_size(self) ->Tuple[int, int]: """ Return the tuple (height, width) of the canvas dimensions """ return self.height, self.width def _step_snell(self) ->None: """ Step the snell layer """ self.snell.step() def _reset_ball(self): self.ball.reset((self.width / 2, self.height / 2)) def _move_our_paddle(self, action) ->None: """ Move our paddle according to the provided action :param action: the action code """ if not isinstance(action, int): action = action.item() assert action in [a for a in self.action_meanings.keys() ], f'{action} is not a valid action' if action == self.actions['UP']: if self.paddle_r.top_bound < self.top_bound: self.paddle_r.up() elif action == self.actions['DOWN']: if self.paddle_r.bottom_bound > self.bottom_bound: self.paddle_r.down() def _step_ball(self, speed: Union[float, int]=None): """ Move the ball to the next position according to the speed of the layer it is in. :param speed: used to continue the trajectory of a ball that interacted with an object """ trajectory = self._get_trajectory(speed) self._get_first_intersection(trajectory) reward = 0 if trajectory.intersection is None: self.ball.pos = trajectory.center.end else: reward = self._interaction_dispatcher(trajectory) return reward def _get_trajectory(self, speed) ->TrajectoryBase: """ Get the ball's trajectory :param speed: The speed of the starting medium :return: trajectory `Line` """ if speed is None: speed = self._get_ball_speed() if self.ball.has_volume: trajectory = Trajectory(self.ball, self.ball.get_velocity(speed)) else: trajectory = Trajectory(self.ball.pos, self.ball.get_velocity( speed)) return trajectory def _interaction_dispatcher(self, trajectory: TrajectoryBase): """ Dispatch data to the appropriate method based on the interaction `obj`. :param trajectory: the trajectory of the ball """ reward = 0 obj = trajectory.intersected_object if obj is self: reward = self._interact_border(trajectory) elif isinstance(obj, Paddle): self._interact_paddle(trajectory) elif isinstance(obj, Snell): self._refract(trajectory) return reward def _interact_paddle(self, trajectory: TrajectoryBase) ->float: paddle = trajectory.intersected_object paddle_fraction = paddle.get_fraction_of_paddle(trajectory. get_center_at_intersection()) angle = paddle_fraction * paddle.max_angle angle = math.pi - angle if self.ball.unit_velocity.x > 0 else angle self.ball.angle = angle reward = self._finish_step_ball(trajectory) return reward def _refract(self, trajectory: TrajectoryBase): edge = trajectory.intersected_edge if self.refract: s0, s1 = self._get_start_and_end_speed(trajectory) angle = edge.angle_to_normal(trajectory.center) if self._exceeds_critical_angle(angle, s0, s1): self._reflect(Point(-1, 1), trajectory) return new_angle = math.asin(s1 / s0 * math.sin(angle)) boundary_angle, new_angle = (self. _adjust_refraction_to_boundary_angle(edge, new_angle)) new_angle = self._adjust_refraction_to_direction_of_incidence( boundary_angle, new_angle, trajectory) self.ball.angle = new_angle return self._finish_step_ball(trajectory) @staticmethod def _exceeds_critical_angle(angle: float, s0: float, s1: float) ->bool: """ Test if the angle exceeds the critical angle :param angle: The angle to the normal of the boundary :param s0: The speed of the original medium :param s1: The speed of the next medium :return: True if the angle exceeds the critical angle """ if s1 > s0: critical_angle = get_critical_angle(s0, s1) if abs(angle) >= critical_angle: return True return False @staticmethod def _adjust_refraction_to_direction_of_incidence(boundary_angle: float, new_angle: float, trajectory: TrajectoryBase) ->float: """ If the direction of incidence was from the right of the boundary, reflect `new_angle`, otherwise, return `new_angle` without modification. :param boundary_angle: must be in the first or fourth quadrant :param new_angle: The angle to be reflected in the return :param trajectory: The angle of the incoming ball in global coordinates :return: The (possibly) reflected `new_angle` """ angle = trajectory.center.angle assert -math.pi / 2 <= boundary_angle <= math.pi / 2, 'boundary_angle should be in first or fourth quadrant' if boundary_angle >= 0 and boundary_angle < angle % (2 * math.pi ) < boundary_angle + math.pi: new_angle = math.pi - new_angle elif boundary_angle < 0 and boundary_angle % (2 * math.pi ) + math.pi < angle % (2 * math.pi) < boundary_angle % (2 * math.pi ): new_angle = math.pi - new_angle return new_angle @staticmethod def _adjust_refraction_to_boundary_angle(boundary: Line, new_angle: float ) ->Tuple[float, float]: """ Compute the rotation of `new_angle` back to global coordinates. Assume incidence from the left side of the boundary. :param boundary: The boundary `primitives.Line` object :param new_angle: The refracted angle normal to the boundary :return: The new angle in global coordinates """ boundary_angle = boundary.angle % (2 * math.pi) if 0 <= boundary_angle < math.pi / 2: boundary_angle = boundary_angle new_angle = boundary_angle - math.pi / 2 + new_angle elif math.pi / 2 <= boundary_angle < math.pi: boundary_angle = math.pi - boundary_angle new_angle = math.pi / 2 - boundary_angle + new_angle elif math.pi <= boundary_angle < 3 * math.pi / 2: boundary_angle = math.pi - boundary_angle new_angle = boundary_angle - math.pi / 2 + new_angle elif 2 * math.pi / 3 <= boundary_angle < 2 * math.pi: boundary_angle = 2 * math.pi - boundary_angle new_angle = math.pi / 2 - boundary_angle - new_angle else: raise ValueError(f'Unexpected angle {boundary_angle}') return boundary_angle, new_angle def _get_start_and_end_speed(self, trajectory: TrajectoryBase) ->Tuple[ float, float]: """ Get the speed at the start of the trajectory and the speed at the end of the trajectory. :param trajectory: The trajectory `primitives.Line` object :return: (initial speed, final speed) """ snell = trajectory.intersected_object if snell.is_in(trajectory.center.start): s0 = snell.speed s1 = self.default_ball_speed else: s0 = self.default_ball_speed s1 = snell.speed return s0, s1 def _interact_border(self, trajectory: TrajectoryBase) ->float: reward = 0.0 edge = trajectory.intersected_edge if edge == self.top_edge or edge == self.bot_edge: self._reflect(Point(1, -1), trajectory) elif edge == self.left_edge: reward = self.score('we') elif edge == self.right_edge: reward = self.score('they') else: raise ValueError(f'invalid edge, {edge}') return reward def _reflect(self, direction: Point, trajectory: TrajectoryBase): """ Multiplies the velocity of the ball by `direction`, continues the path of the ball by calculating the remaining speed using trajectory and point. :param direction: velocity multiplier :param trajectory: The original trajectory of the ball """ self.ball.unit_velocity *= direction return self._finish_step_ball(trajectory) def _finish_step_ball(self, trajectory: TrajectoryBase): """ Finish the remainder of the trajectory after any interactions. :param trajectory: The original trajectory :return: reward """ point = trajectory.get_center_at_intersection() self.ball.pos = point + self.ball.unit_velocity * EPSILON return self._step_ball(trajectory.remaining_speed) def _get_first_intersection(self, trajectory: TrajectoryBase): """ Find the first point at which the trajectory interacted with an object. :param trajectory: the trajectory of the object :return: (shape object interacted with, point of interaction, line object interacted with) """ for trajectory_line in trajectory.corners: for o in self.sprites: if not isinstance(o, Ball): intersection_result = o.get_intersection(trajectory_line) if intersection_result is not None: edge, point = intersection_result if trajectory.intersection is None: trajectory.set_intersection(point, trajectory_line, o, edge) elif point == trajectory.intersection and trajectory_line == trajectory.intersected_trajectory: raise NotImplementedError( 'overlapping parallel edges not implemented') elif point.l2_distance(trajectory_line.start ) < trajectory.intersection.l2_distance(trajectory .intersected_trajectory.start): trajectory.set_intersection(point, trajectory_line, o, edge) def _get_ball_speed(self) ->float: if self.uniform_speed: return self.default_ball_speed elif self.ball.is_overlapping(self.snell): return self.snell.speed else: return self.default_ball_speed def _step_their_paddle(self): """ Move the opponents paddle. Override this in a subclass to change the behavior. """ if random.random() < self.their_update_probability: if self.paddle_l.y < self.ball.y: if self.paddle_l.top_bound < self.top_bound: self.paddle_l.up() elif self.paddle_l.bottom_bound > self.bottom_bound: self.paddle_l.down() <|reserved_special_token_1|> <|reserved_special_token_0|> class TrajectoryRectangle(TrajectoryBase): <|reserved_special_token_0|> def __init__(self, shape: Rectangle, velocity: Point): super(TrajectoryRectangle, self).__init__(shape, velocity) assert isinstance(shape, Rectangle) self._reference = self.shape.pos @property def center(self) ->Line: """ Line representing the trajectory of the center of the rectangle """ return Line(self.shape.pos, self.shape.pos + self.velocity) @property def top_right(self) ->Line: """ Line representing the trajectory of the point on the top right corner of the rectangle """ start = Point(self.shape.right_bound, self.shape.top_bound) return Line(start, start + self.velocity) @property def top_left(self) ->Line: """ Line representing the trajectory of the point on the top left corner of the rectangle """ start = Point(self.shape.left_bound, self.shape.top_bound) return Line(start, start + self.velocity) @property def bottom_right(self) ->Line: """ Line representing the trajectory of the point on the bottom right corner of the rectangle """ start = Point(self.shape.right_bound, self.shape.bottom_bound) return Line(start, start + self.velocity) @property def bottom_left(self) ->Line: """ Line representing the trajectory of the point on the bottom left corner of the rectangle """ start = Point(self.shape.left_bound, self.shape.bottom_bound) return Line(start, start + self.velocity) class TrajectoryLine(TrajectoryRectangle): """ Create a bounding box around the line and compute the trajectory as if it were a rectangle. """ def __init__(self, shape: Line, velocity: Point): super(TrajectoryLine, self).__init__(shape, velocity) assert isinstance(shape, Line) self._reference = self.shape.start height = abs(self.shape.start.y - self.shape.end.y) width = abs(self.shape.start.x - self.shape.end.x) center = Point((self.shape.start.x + self.shape.end.x) / 2, (self. shape.start.y + self.shape.end.y) / 2) self.shape = Rectangle(height=height, width=width) self.shape.pos = center class TrajectoryPoint(TrajectoryBase): def __init__(self, shape: Point, velocity: Point): super(TrajectoryPoint, self).__init__(shape, velocity) assert isinstance(shape, Point) self._reference = self.shape @property def corners(self) ->Tuple[Line, ...]: return self._trajectory, @property def _trajectory(self) ->Line: return Line(self.shape, self.shape + self.velocity) @property def center(self) ->Line: return self._trajectory @property def top_right(self) ->Line: return self._trajectory @property def top_left(self) ->Line: return self._trajectory @property def bottom_right(self) ->Line: return self._trajectory @property def bottom_left(self) ->Line: return self._trajectory class Trajectory(object): def __new__(cls, shape: Shape, velocity: Point): if isinstance(shape, Point): return TrajectoryPoint(shape, velocity) elif isinstance(shape, Line): return TrajectoryLine(shape, velocity) elif isinstance(shape, Rectangle): return TrajectoryRectangle(shape, velocity) else: raise NotImplementedError( f'No implementation of Trajectory for input shape of type {type(shape)}' ) class Canvas(Rectangle): action_meanings = {(0): 'NOOP', (1): 'UP', (2): 'DOWN'} actions = {k: v for v, k in action_meanings.items()} def __init__(self, paddle_l: Paddle, paddle_r: Paddle, ball: Ball, snell: Snell, ball_speed: int, height: int, width: int, their_update_probability: float, refract: bool, uniform_speed: bool): super().__init__(height=height, width=width, visibility='none', render_value=0) self.pos = self.width / 2, self.height / 2 assert isinstance(their_update_probability, (float, int) ), f'their_update_probability must be numeric, not {type(their_update_probability)}' assert 0 <= their_update_probability <= 1, f'{their_update_probability} outside allowed bounds [0, 1]' self.their_update_probability = their_update_probability self.default_ball_speed = ball_speed self.snell = snell self.ball = ball self.paddle_l = paddle_l self.paddle_r = paddle_r self.sprites = [self, snell, paddle_l, paddle_r, ball] self.uniform_speed = uniform_speed self.refract = refract self.we_scored = False self.they_scored = False self.our_score = 0 self.their_score = 0 def register_sprite(self, sprite: Shape): assert issubclass(type(sprite), Shape ), f'sprite must be subclassed from Shape' self.sprites.insert(-1, sprite) @property def left_bound(self): return 0 @property def right_bound(self): return self.width @property def top_bound(self): return self.height @property def bottom_bound(self): return 0 def to_numpy(self) ->Tuple[np.ndarray, np.ndarray]: """ Performs masked rendering of objects in `self.sprites`. Priority is determined by the ordering of the list, earlier objects will be obscured by later ones. :return: (state, rendering) """ state = self._zero_rgb_image(round(self.height), round(self.width)) rendering = self._zero_rgb_image(round(self.height), round(self.width)) for sprite in self.sprites[1:]: sprite_state, sprite_rendering = sprite.to_numpy(self.height, self.width) state[sprite_state != 0] = sprite_state[sprite_state != 0] rendering[sprite_rendering != 0] = sprite_rendering[ sprite_rendering != 0] return state, rendering def score(self, who): """ Increment the score and reset the ball :param who: 'we' or 'they' :return: reward """ if who == 'they': reward = -1 self.their_score += 1 elif who == 'we': reward = 1 self.our_score += 1 else: raise ValueError(f"who must be 'we' or 'they', not {who}") self._reset_ball() return reward def step(self, action): self._move_our_paddle(action) self._step_their_paddle() reward = self._step_ball() self._step_snell() return reward def get_state_size(self) ->Tuple[int, int]: """ Return the tuple (height, width) of the canvas dimensions """ return self.height, self.width def _step_snell(self) ->None: """ Step the snell layer """ self.snell.step() def _reset_ball(self): self.ball.reset((self.width / 2, self.height / 2)) def _move_our_paddle(self, action) ->None: """ Move our paddle according to the provided action :param action: the action code """ if not isinstance(action, int): action = action.item() assert action in [a for a in self.action_meanings.keys() ], f'{action} is not a valid action' if action == self.actions['UP']: if self.paddle_r.top_bound < self.top_bound: self.paddle_r.up() elif action == self.actions['DOWN']: if self.paddle_r.bottom_bound > self.bottom_bound: self.paddle_r.down() def _step_ball(self, speed: Union[float, int]=None): """ Move the ball to the next position according to the speed of the layer it is in. :param speed: used to continue the trajectory of a ball that interacted with an object """ trajectory = self._get_trajectory(speed) self._get_first_intersection(trajectory) reward = 0 if trajectory.intersection is None: self.ball.pos = trajectory.center.end else: reward = self._interaction_dispatcher(trajectory) return reward def _get_trajectory(self, speed) ->TrajectoryBase: """ Get the ball's trajectory :param speed: The speed of the starting medium :return: trajectory `Line` """ if speed is None: speed = self._get_ball_speed() if self.ball.has_volume: trajectory = Trajectory(self.ball, self.ball.get_velocity(speed)) else: trajectory = Trajectory(self.ball.pos, self.ball.get_velocity( speed)) return trajectory def _interaction_dispatcher(self, trajectory: TrajectoryBase): """ Dispatch data to the appropriate method based on the interaction `obj`. :param trajectory: the trajectory of the ball """ reward = 0 obj = trajectory.intersected_object if obj is self: reward = self._interact_border(trajectory) elif isinstance(obj, Paddle): self._interact_paddle(trajectory) elif isinstance(obj, Snell): self._refract(trajectory) return reward def _interact_paddle(self, trajectory: TrajectoryBase) ->float: paddle = trajectory.intersected_object paddle_fraction = paddle.get_fraction_of_paddle(trajectory. get_center_at_intersection()) angle = paddle_fraction * paddle.max_angle angle = math.pi - angle if self.ball.unit_velocity.x > 0 else angle self.ball.angle = angle reward = self._finish_step_ball(trajectory) return reward def _refract(self, trajectory: TrajectoryBase): edge = trajectory.intersected_edge if self.refract: s0, s1 = self._get_start_and_end_speed(trajectory) angle = edge.angle_to_normal(trajectory.center) if self._exceeds_critical_angle(angle, s0, s1): self._reflect(Point(-1, 1), trajectory) return new_angle = math.asin(s1 / s0 * math.sin(angle)) boundary_angle, new_angle = (self. _adjust_refraction_to_boundary_angle(edge, new_angle)) new_angle = self._adjust_refraction_to_direction_of_incidence( boundary_angle, new_angle, trajectory) self.ball.angle = new_angle return self._finish_step_ball(trajectory) @staticmethod def _exceeds_critical_angle(angle: float, s0: float, s1: float) ->bool: """ Test if the angle exceeds the critical angle :param angle: The angle to the normal of the boundary :param s0: The speed of the original medium :param s1: The speed of the next medium :return: True if the angle exceeds the critical angle """ if s1 > s0: critical_angle = get_critical_angle(s0, s1) if abs(angle) >= critical_angle: return True return False @staticmethod def _adjust_refraction_to_direction_of_incidence(boundary_angle: float, new_angle: float, trajectory: TrajectoryBase) ->float: """ If the direction of incidence was from the right of the boundary, reflect `new_angle`, otherwise, return `new_angle` without modification. :param boundary_angle: must be in the first or fourth quadrant :param new_angle: The angle to be reflected in the return :param trajectory: The angle of the incoming ball in global coordinates :return: The (possibly) reflected `new_angle` """ angle = trajectory.center.angle assert -math.pi / 2 <= boundary_angle <= math.pi / 2, 'boundary_angle should be in first or fourth quadrant' if boundary_angle >= 0 and boundary_angle < angle % (2 * math.pi ) < boundary_angle + math.pi: new_angle = math.pi - new_angle elif boundary_angle < 0 and boundary_angle % (2 * math.pi ) + math.pi < angle % (2 * math.pi) < boundary_angle % (2 * math.pi ): new_angle = math.pi - new_angle return new_angle @staticmethod def _adjust_refraction_to_boundary_angle(boundary: Line, new_angle: float ) ->Tuple[float, float]: """ Compute the rotation of `new_angle` back to global coordinates. Assume incidence from the left side of the boundary. :param boundary: The boundary `primitives.Line` object :param new_angle: The refracted angle normal to the boundary :return: The new angle in global coordinates """ boundary_angle = boundary.angle % (2 * math.pi) if 0 <= boundary_angle < math.pi / 2: boundary_angle = boundary_angle new_angle = boundary_angle - math.pi / 2 + new_angle elif math.pi / 2 <= boundary_angle < math.pi: boundary_angle = math.pi - boundary_angle new_angle = math.pi / 2 - boundary_angle + new_angle elif math.pi <= boundary_angle < 3 * math.pi / 2: boundary_angle = math.pi - boundary_angle new_angle = boundary_angle - math.pi / 2 + new_angle elif 2 * math.pi / 3 <= boundary_angle < 2 * math.pi: boundary_angle = 2 * math.pi - boundary_angle new_angle = math.pi / 2 - boundary_angle - new_angle else: raise ValueError(f'Unexpected angle {boundary_angle}') return boundary_angle, new_angle def _get_start_and_end_speed(self, trajectory: TrajectoryBase) ->Tuple[ float, float]: """ Get the speed at the start of the trajectory and the speed at the end of the trajectory. :param trajectory: The trajectory `primitives.Line` object :return: (initial speed, final speed) """ snell = trajectory.intersected_object if snell.is_in(trajectory.center.start): s0 = snell.speed s1 = self.default_ball_speed else: s0 = self.default_ball_speed s1 = snell.speed return s0, s1 def _interact_border(self, trajectory: TrajectoryBase) ->float: reward = 0.0 edge = trajectory.intersected_edge if edge == self.top_edge or edge == self.bot_edge: self._reflect(Point(1, -1), trajectory) elif edge == self.left_edge: reward = self.score('we') elif edge == self.right_edge: reward = self.score('they') else: raise ValueError(f'invalid edge, {edge}') return reward def _reflect(self, direction: Point, trajectory: TrajectoryBase): """ Multiplies the velocity of the ball by `direction`, continues the path of the ball by calculating the remaining speed using trajectory and point. :param direction: velocity multiplier :param trajectory: The original trajectory of the ball """ self.ball.unit_velocity *= direction return self._finish_step_ball(trajectory) def _finish_step_ball(self, trajectory: TrajectoryBase): """ Finish the remainder of the trajectory after any interactions. :param trajectory: The original trajectory :return: reward """ point = trajectory.get_center_at_intersection() self.ball.pos = point + self.ball.unit_velocity * EPSILON return self._step_ball(trajectory.remaining_speed) def _get_first_intersection(self, trajectory: TrajectoryBase): """ Find the first point at which the trajectory interacted with an object. :param trajectory: the trajectory of the object :return: (shape object interacted with, point of interaction, line object interacted with) """ for trajectory_line in trajectory.corners: for o in self.sprites: if not isinstance(o, Ball): intersection_result = o.get_intersection(trajectory_line) if intersection_result is not None: edge, point = intersection_result if trajectory.intersection is None: trajectory.set_intersection(point, trajectory_line, o, edge) elif point == trajectory.intersection and trajectory_line == trajectory.intersected_trajectory: raise NotImplementedError( 'overlapping parallel edges not implemented') elif point.l2_distance(trajectory_line.start ) < trajectory.intersection.l2_distance(trajectory .intersected_trajectory.start): trajectory.set_intersection(point, trajectory_line, o, edge) def _get_ball_speed(self) ->float: if self.uniform_speed: return self.default_ball_speed elif self.ball.is_overlapping(self.snell): return self.snell.speed else: return self.default_ball_speed def _step_their_paddle(self): """ Move the opponents paddle. Override this in a subclass to change the behavior. """ if random.random() < self.their_update_probability: if self.paddle_l.y < self.ball.y: if self.paddle_l.top_bound < self.top_bound: self.paddle_l.up() elif self.paddle_l.bottom_bound > self.bottom_bound: self.paddle_l.down() <|reserved_special_token_1|> <|reserved_special_token_0|> class Paddle(Rectangle): <|reserved_special_token_0|> def up(self): self.y += self.speed <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> class Ball(Rectangle): def __init__(self, size: float, max_initial_angle: float, visibility: str, has_volume: bool=False): """ Ball object :param has_volume: :param size: The size to render the ball :param max_initial_angle: The maximum angle the ball can start with :param visibility: How to render the ball. See `Shape.visibility` :param has_volume: determines whether the ball interacts as a point or as an area """ super().__init__(width=size, height=size, visibility=visibility, render_value=255) self.max_initial_angle = max_initial_angle self.reset(self.pos, direction='left') self.has_volume = has_volume def reset(self, position: Union[Tuple[float, float], Point], direction: str='right'): if direction == 'right': self._angle = (2 * random.random() - 1) * self.max_initial_angle elif direction == 'left': self._angle = math.pi - (2 * random.random() - 1 ) * self.max_initial_angle else: raise ValueError( f"direction must be 'left' or 'right', not {direction}") self.pos = position @property def angle(self): """ Angle with respect to the right horizontal """ return self._angle @angle.setter def angle(self, value): self._angle = value % (2 * math.pi) @property def unit_velocity(self) ->Point: x = math.cos(self.angle) y = math.sin(self.angle) return Point(x, y) @unit_velocity.setter def unit_velocity(self, value: Union[Tuple[float, float], Point]): """ Sets the angle parameter give a set of (x, y) coordinates. :param value: (x, y) """ if isinstance(value, tuple): value = Point(*value) assert isinstance(value, Point ), f'value must be a point, not {type(value)}' self.angle = value.angle def get_velocity(self, speed: Union[float, int]): return self.unit_velocity * speed class Snell(Rectangle): def __init__(self, width, height, speed, change_rate, visibility): """ Rectangular area with a different ball speed. :param width: The width of the layer :param height: The height of the layer :param change_rate: Rate at which the ball speed changes, the standard deviation of the change on each step. :param visibility: Whether and how to render the layer. See `Shape.visibility` """ assert change_rate >= 0, 'Snell `change_rate` must be non-negative' super().__init__(width=width, height=height, visibility=visibility, render_value=(235, 76, 52)) self.speed = speed self._initial_speed = speed self.change_rate = change_rate def step(self): """ Step the Snell speed using a bounded Gaussian random walk. - step with mean 0, standard deviation `self.speed` - Clip the speed at `0.5 * self._initial_speed <= self.speed <= 2.0 * self._initial_speed` """ if self.change_rate != 0: self.speed += stats.norm(loc=0, scale=self.change_rate).rvs() if self.speed < 0.5 * self._initial_speed: self.speed = 0.5 * self._initial_speed if self.speed > 2.0 * self._initial_speed: self.speed = 2.0 * self._initial_speed else: pass class TrajectoryBase(abc.ABC): def __init__(self, shape: Union[Point, Line, Rectangle], velocity: Point): self.shape = shape self.velocity = velocity self._reference = None self.intersection = None self.intersected_trajectory = None self.intersected_object = None self.intersected_edge = None self.remaining_speed = None def set_intersection(self, point: Point, trajectory_line: Line, obj: Shape, edge: Line): assert isinstance(obj, Shape), f'type Shape expected, not {type(obj)}' assert isinstance(point, Point ), f'type Point expected, not {type(point)}' assert isinstance(edge, Line), f'type Line expected, not {type(edge)}' self.intersection = point self.intersected_trajectory = trajectory_line self.remaining_speed = point.l2_distance(trajectory_line.end) self.intersected_object = obj self.intersected_edge = edge def get_center_at_intersection(self) ->Point: """ Get the new center of `self.shape` given that it moved along `intersected_trajectory` to `intersection` :return: new center point """ return self._reference + (self.intersection - self. intersected_trajectory.start) @property def corners(self) ->Tuple[Line, ...]: return (self.top_left, self.top_right, self.bottom_right, self. bottom_left) @property @abc.abstractmethod def center(self) ->Line: ... @property @abc.abstractmethod def top_right(self) ->Line: ... @property @abc.abstractmethod def top_left(self) ->Line: ... @property @abc.abstractmethod def bottom_right(self) ->Line: ... @property @abc.abstractmethod def bottom_left(self) ->Line: ... class TrajectoryRectangle(TrajectoryBase): """ Compute the trajectory of each corner of the rectangle """ def __init__(self, shape: Rectangle, velocity: Point): super(TrajectoryRectangle, self).__init__(shape, velocity) assert isinstance(shape, Rectangle) self._reference = self.shape.pos @property def center(self) ->Line: """ Line representing the trajectory of the center of the rectangle """ return Line(self.shape.pos, self.shape.pos + self.velocity) @property def top_right(self) ->Line: """ Line representing the trajectory of the point on the top right corner of the rectangle """ start = Point(self.shape.right_bound, self.shape.top_bound) return Line(start, start + self.velocity) @property def top_left(self) ->Line: """ Line representing the trajectory of the point on the top left corner of the rectangle """ start = Point(self.shape.left_bound, self.shape.top_bound) return Line(start, start + self.velocity) @property def bottom_right(self) ->Line: """ Line representing the trajectory of the point on the bottom right corner of the rectangle """ start = Point(self.shape.right_bound, self.shape.bottom_bound) return Line(start, start + self.velocity) @property def bottom_left(self) ->Line: """ Line representing the trajectory of the point on the bottom left corner of the rectangle """ start = Point(self.shape.left_bound, self.shape.bottom_bound) return Line(start, start + self.velocity) class TrajectoryLine(TrajectoryRectangle): """ Create a bounding box around the line and compute the trajectory as if it were a rectangle. """ def __init__(self, shape: Line, velocity: Point): super(TrajectoryLine, self).__init__(shape, velocity) assert isinstance(shape, Line) self._reference = self.shape.start height = abs(self.shape.start.y - self.shape.end.y) width = abs(self.shape.start.x - self.shape.end.x) center = Point((self.shape.start.x + self.shape.end.x) / 2, (self. shape.start.y + self.shape.end.y) / 2) self.shape = Rectangle(height=height, width=width) self.shape.pos = center class TrajectoryPoint(TrajectoryBase): def __init__(self, shape: Point, velocity: Point): super(TrajectoryPoint, self).__init__(shape, velocity) assert isinstance(shape, Point) self._reference = self.shape @property def corners(self) ->Tuple[Line, ...]: return self._trajectory, @property def _trajectory(self) ->Line: return Line(self.shape, self.shape + self.velocity) @property def center(self) ->Line: return self._trajectory @property def top_right(self) ->Line: return self._trajectory @property def top_left(self) ->Line: return self._trajectory @property def bottom_right(self) ->Line: return self._trajectory @property def bottom_left(self) ->Line: return self._trajectory class Trajectory(object): def __new__(cls, shape: Shape, velocity: Point): if isinstance(shape, Point): return TrajectoryPoint(shape, velocity) elif isinstance(shape, Line): return TrajectoryLine(shape, velocity) elif isinstance(shape, Rectangle): return TrajectoryRectangle(shape, velocity) else: raise NotImplementedError( f'No implementation of Trajectory for input shape of type {type(shape)}' ) class Canvas(Rectangle): action_meanings = {(0): 'NOOP', (1): 'UP', (2): 'DOWN'} actions = {k: v for v, k in action_meanings.items()} def __init__(self, paddle_l: Paddle, paddle_r: Paddle, ball: Ball, snell: Snell, ball_speed: int, height: int, width: int, their_update_probability: float, refract: bool, uniform_speed: bool): super().__init__(height=height, width=width, visibility='none', render_value=0) self.pos = self.width / 2, self.height / 2 assert isinstance(their_update_probability, (float, int) ), f'their_update_probability must be numeric, not {type(their_update_probability)}' assert 0 <= their_update_probability <= 1, f'{their_update_probability} outside allowed bounds [0, 1]' self.their_update_probability = their_update_probability self.default_ball_speed = ball_speed self.snell = snell self.ball = ball self.paddle_l = paddle_l self.paddle_r = paddle_r self.sprites = [self, snell, paddle_l, paddle_r, ball] self.uniform_speed = uniform_speed self.refract = refract self.we_scored = False self.they_scored = False self.our_score = 0 self.their_score = 0 def register_sprite(self, sprite: Shape): assert issubclass(type(sprite), Shape ), f'sprite must be subclassed from Shape' self.sprites.insert(-1, sprite) @property def left_bound(self): return 0 @property def right_bound(self): return self.width @property def top_bound(self): return self.height @property def bottom_bound(self): return 0 def to_numpy(self) ->Tuple[np.ndarray, np.ndarray]: """ Performs masked rendering of objects in `self.sprites`. Priority is determined by the ordering of the list, earlier objects will be obscured by later ones. :return: (state, rendering) """ state = self._zero_rgb_image(round(self.height), round(self.width)) rendering = self._zero_rgb_image(round(self.height), round(self.width)) for sprite in self.sprites[1:]: sprite_state, sprite_rendering = sprite.to_numpy(self.height, self.width) state[sprite_state != 0] = sprite_state[sprite_state != 0] rendering[sprite_rendering != 0] = sprite_rendering[ sprite_rendering != 0] return state, rendering def score(self, who): """ Increment the score and reset the ball :param who: 'we' or 'they' :return: reward """ if who == 'they': reward = -1 self.their_score += 1 elif who == 'we': reward = 1 self.our_score += 1 else: raise ValueError(f"who must be 'we' or 'they', not {who}") self._reset_ball() return reward def step(self, action): self._move_our_paddle(action) self._step_their_paddle() reward = self._step_ball() self._step_snell() return reward def get_state_size(self) ->Tuple[int, int]: """ Return the tuple (height, width) of the canvas dimensions """ return self.height, self.width def _step_snell(self) ->None: """ Step the snell layer """ self.snell.step() def _reset_ball(self): self.ball.reset((self.width / 2, self.height / 2)) def _move_our_paddle(self, action) ->None: """ Move our paddle according to the provided action :param action: the action code """ if not isinstance(action, int): action = action.item() assert action in [a for a in self.action_meanings.keys() ], f'{action} is not a valid action' if action == self.actions['UP']: if self.paddle_r.top_bound < self.top_bound: self.paddle_r.up() elif action == self.actions['DOWN']: if self.paddle_r.bottom_bound > self.bottom_bound: self.paddle_r.down() def _step_ball(self, speed: Union[float, int]=None): """ Move the ball to the next position according to the speed of the layer it is in. :param speed: used to continue the trajectory of a ball that interacted with an object """ trajectory = self._get_trajectory(speed) self._get_first_intersection(trajectory) reward = 0 if trajectory.intersection is None: self.ball.pos = trajectory.center.end else: reward = self._interaction_dispatcher(trajectory) return reward def _get_trajectory(self, speed) ->TrajectoryBase: """ Get the ball's trajectory :param speed: The speed of the starting medium :return: trajectory `Line` """ if speed is None: speed = self._get_ball_speed() if self.ball.has_volume: trajectory = Trajectory(self.ball, self.ball.get_velocity(speed)) else: trajectory = Trajectory(self.ball.pos, self.ball.get_velocity( speed)) return trajectory def _interaction_dispatcher(self, trajectory: TrajectoryBase): """ Dispatch data to the appropriate method based on the interaction `obj`. :param trajectory: the trajectory of the ball """ reward = 0 obj = trajectory.intersected_object if obj is self: reward = self._interact_border(trajectory) elif isinstance(obj, Paddle): self._interact_paddle(trajectory) elif isinstance(obj, Snell): self._refract(trajectory) return reward def _interact_paddle(self, trajectory: TrajectoryBase) ->float: paddle = trajectory.intersected_object paddle_fraction = paddle.get_fraction_of_paddle(trajectory. get_center_at_intersection()) angle = paddle_fraction * paddle.max_angle angle = math.pi - angle if self.ball.unit_velocity.x > 0 else angle self.ball.angle = angle reward = self._finish_step_ball(trajectory) return reward def _refract(self, trajectory: TrajectoryBase): edge = trajectory.intersected_edge if self.refract: s0, s1 = self._get_start_and_end_speed(trajectory) angle = edge.angle_to_normal(trajectory.center) if self._exceeds_critical_angle(angle, s0, s1): self._reflect(Point(-1, 1), trajectory) return new_angle = math.asin(s1 / s0 * math.sin(angle)) boundary_angle, new_angle = (self. _adjust_refraction_to_boundary_angle(edge, new_angle)) new_angle = self._adjust_refraction_to_direction_of_incidence( boundary_angle, new_angle, trajectory) self.ball.angle = new_angle return self._finish_step_ball(trajectory) @staticmethod def _exceeds_critical_angle(angle: float, s0: float, s1: float) ->bool: """ Test if the angle exceeds the critical angle :param angle: The angle to the normal of the boundary :param s0: The speed of the original medium :param s1: The speed of the next medium :return: True if the angle exceeds the critical angle """ if s1 > s0: critical_angle = get_critical_angle(s0, s1) if abs(angle) >= critical_angle: return True return False @staticmethod def _adjust_refraction_to_direction_of_incidence(boundary_angle: float, new_angle: float, trajectory: TrajectoryBase) ->float: """ If the direction of incidence was from the right of the boundary, reflect `new_angle`, otherwise, return `new_angle` without modification. :param boundary_angle: must be in the first or fourth quadrant :param new_angle: The angle to be reflected in the return :param trajectory: The angle of the incoming ball in global coordinates :return: The (possibly) reflected `new_angle` """ angle = trajectory.center.angle assert -math.pi / 2 <= boundary_angle <= math.pi / 2, 'boundary_angle should be in first or fourth quadrant' if boundary_angle >= 0 and boundary_angle < angle % (2 * math.pi ) < boundary_angle + math.pi: new_angle = math.pi - new_angle elif boundary_angle < 0 and boundary_angle % (2 * math.pi ) + math.pi < angle % (2 * math.pi) < boundary_angle % (2 * math.pi ): new_angle = math.pi - new_angle return new_angle @staticmethod def _adjust_refraction_to_boundary_angle(boundary: Line, new_angle: float ) ->Tuple[float, float]: """ Compute the rotation of `new_angle` back to global coordinates. Assume incidence from the left side of the boundary. :param boundary: The boundary `primitives.Line` object :param new_angle: The refracted angle normal to the boundary :return: The new angle in global coordinates """ boundary_angle = boundary.angle % (2 * math.pi) if 0 <= boundary_angle < math.pi / 2: boundary_angle = boundary_angle new_angle = boundary_angle - math.pi / 2 + new_angle elif math.pi / 2 <= boundary_angle < math.pi: boundary_angle = math.pi - boundary_angle new_angle = math.pi / 2 - boundary_angle + new_angle elif math.pi <= boundary_angle < 3 * math.pi / 2: boundary_angle = math.pi - boundary_angle new_angle = boundary_angle - math.pi / 2 + new_angle elif 2 * math.pi / 3 <= boundary_angle < 2 * math.pi: boundary_angle = 2 * math.pi - boundary_angle new_angle = math.pi / 2 - boundary_angle - new_angle else: raise ValueError(f'Unexpected angle {boundary_angle}') return boundary_angle, new_angle def _get_start_and_end_speed(self, trajectory: TrajectoryBase) ->Tuple[ float, float]: """ Get the speed at the start of the trajectory and the speed at the end of the trajectory. :param trajectory: The trajectory `primitives.Line` object :return: (initial speed, final speed) """ snell = trajectory.intersected_object if snell.is_in(trajectory.center.start): s0 = snell.speed s1 = self.default_ball_speed else: s0 = self.default_ball_speed s1 = snell.speed return s0, s1 def _interact_border(self, trajectory: TrajectoryBase) ->float: reward = 0.0 edge = trajectory.intersected_edge if edge == self.top_edge or edge == self.bot_edge: self._reflect(Point(1, -1), trajectory) elif edge == self.left_edge: reward = self.score('we') elif edge == self.right_edge: reward = self.score('they') else: raise ValueError(f'invalid edge, {edge}') return reward def _reflect(self, direction: Point, trajectory: TrajectoryBase): """ Multiplies the velocity of the ball by `direction`, continues the path of the ball by calculating the remaining speed using trajectory and point. :param direction: velocity multiplier :param trajectory: The original trajectory of the ball """ self.ball.unit_velocity *= direction return self._finish_step_ball(trajectory) def _finish_step_ball(self, trajectory: TrajectoryBase): """ Finish the remainder of the trajectory after any interactions. :param trajectory: The original trajectory :return: reward """ point = trajectory.get_center_at_intersection() self.ball.pos = point + self.ball.unit_velocity * EPSILON return self._step_ball(trajectory.remaining_speed) def _get_first_intersection(self, trajectory: TrajectoryBase): """ Find the first point at which the trajectory interacted with an object. :param trajectory: the trajectory of the object :return: (shape object interacted with, point of interaction, line object interacted with) """ for trajectory_line in trajectory.corners: for o in self.sprites: if not isinstance(o, Ball): intersection_result = o.get_intersection(trajectory_line) if intersection_result is not None: edge, point = intersection_result if trajectory.intersection is None: trajectory.set_intersection(point, trajectory_line, o, edge) elif point == trajectory.intersection and trajectory_line == trajectory.intersected_trajectory: raise NotImplementedError( 'overlapping parallel edges not implemented') elif point.l2_distance(trajectory_line.start ) < trajectory.intersection.l2_distance(trajectory .intersected_trajectory.start): trajectory.set_intersection(point, trajectory_line, o, edge) def _get_ball_speed(self) ->float: if self.uniform_speed: return self.default_ball_speed elif self.ball.is_overlapping(self.snell): return self.snell.speed else: return self.default_ball_speed def _step_their_paddle(self): """ Move the opponents paddle. Override this in a subclass to change the behavior. """ if random.random() < self.their_update_probability: if self.paddle_l.y < self.ball.y: if self.paddle_l.top_bound < self.top_bound: self.paddle_l.up() elif self.paddle_l.bottom_bound > self.bottom_bound: self.paddle_l.down() <|reserved_special_token_1|> <|reserved_special_token_0|> class Paddle(Rectangle): <|reserved_special_token_0|> def up(self): self.y += self.speed <|reserved_special_token_0|> def _get_edges(self) ->Tuple[Line]: """ Only return the field-side edge """ if self.side == 'right': return Line((self.left_bound, self.bottom_bound), (self. left_bound, self.top_bound)), elif self.side == 'left': return Line((self.right_bound, self.bottom_bound), (self. right_bound, self.top_bound)), <|reserved_special_token_0|> class Ball(Rectangle): def __init__(self, size: float, max_initial_angle: float, visibility: str, has_volume: bool=False): """ Ball object :param has_volume: :param size: The size to render the ball :param max_initial_angle: The maximum angle the ball can start with :param visibility: How to render the ball. See `Shape.visibility` :param has_volume: determines whether the ball interacts as a point or as an area """ super().__init__(width=size, height=size, visibility=visibility, render_value=255) self.max_initial_angle = max_initial_angle self.reset(self.pos, direction='left') self.has_volume = has_volume def reset(self, position: Union[Tuple[float, float], Point], direction: str='right'): if direction == 'right': self._angle = (2 * random.random() - 1) * self.max_initial_angle elif direction == 'left': self._angle = math.pi - (2 * random.random() - 1 ) * self.max_initial_angle else: raise ValueError( f"direction must be 'left' or 'right', not {direction}") self.pos = position @property def angle(self): """ Angle with respect to the right horizontal """ return self._angle @angle.setter def angle(self, value): self._angle = value % (2 * math.pi) @property def unit_velocity(self) ->Point: x = math.cos(self.angle) y = math.sin(self.angle) return Point(x, y) @unit_velocity.setter def unit_velocity(self, value: Union[Tuple[float, float], Point]): """ Sets the angle parameter give a set of (x, y) coordinates. :param value: (x, y) """ if isinstance(value, tuple): value = Point(*value) assert isinstance(value, Point ), f'value must be a point, not {type(value)}' self.angle = value.angle def get_velocity(self, speed: Union[float, int]): return self.unit_velocity * speed class Snell(Rectangle): def __init__(self, width, height, speed, change_rate, visibility): """ Rectangular area with a different ball speed. :param width: The width of the layer :param height: The height of the layer :param change_rate: Rate at which the ball speed changes, the standard deviation of the change on each step. :param visibility: Whether and how to render the layer. See `Shape.visibility` """ assert change_rate >= 0, 'Snell `change_rate` must be non-negative' super().__init__(width=width, height=height, visibility=visibility, render_value=(235, 76, 52)) self.speed = speed self._initial_speed = speed self.change_rate = change_rate def step(self): """ Step the Snell speed using a bounded Gaussian random walk. - step with mean 0, standard deviation `self.speed` - Clip the speed at `0.5 * self._initial_speed <= self.speed <= 2.0 * self._initial_speed` """ if self.change_rate != 0: self.speed += stats.norm(loc=0, scale=self.change_rate).rvs() if self.speed < 0.5 * self._initial_speed: self.speed = 0.5 * self._initial_speed if self.speed > 2.0 * self._initial_speed: self.speed = 2.0 * self._initial_speed else: pass class TrajectoryBase(abc.ABC): def __init__(self, shape: Union[Point, Line, Rectangle], velocity: Point): self.shape = shape self.velocity = velocity self._reference = None self.intersection = None self.intersected_trajectory = None self.intersected_object = None self.intersected_edge = None self.remaining_speed = None def set_intersection(self, point: Point, trajectory_line: Line, obj: Shape, edge: Line): assert isinstance(obj, Shape), f'type Shape expected, not {type(obj)}' assert isinstance(point, Point ), f'type Point expected, not {type(point)}' assert isinstance(edge, Line), f'type Line expected, not {type(edge)}' self.intersection = point self.intersected_trajectory = trajectory_line self.remaining_speed = point.l2_distance(trajectory_line.end) self.intersected_object = obj self.intersected_edge = edge def get_center_at_intersection(self) ->Point: """ Get the new center of `self.shape` given that it moved along `intersected_trajectory` to `intersection` :return: new center point """ return self._reference + (self.intersection - self. intersected_trajectory.start) @property def corners(self) ->Tuple[Line, ...]: return (self.top_left, self.top_right, self.bottom_right, self. bottom_left) @property @abc.abstractmethod def center(self) ->Line: ... @property @abc.abstractmethod def top_right(self) ->Line: ... @property @abc.abstractmethod def top_left(self) ->Line: ... @property @abc.abstractmethod def bottom_right(self) ->Line: ... @property @abc.abstractmethod def bottom_left(self) ->Line: ... class TrajectoryRectangle(TrajectoryBase): """ Compute the trajectory of each corner of the rectangle """ def __init__(self, shape: Rectangle, velocity: Point): super(TrajectoryRectangle, self).__init__(shape, velocity) assert isinstance(shape, Rectangle) self._reference = self.shape.pos @property def center(self) ->Line: """ Line representing the trajectory of the center of the rectangle """ return Line(self.shape.pos, self.shape.pos + self.velocity) @property def top_right(self) ->Line: """ Line representing the trajectory of the point on the top right corner of the rectangle """ start = Point(self.shape.right_bound, self.shape.top_bound) return Line(start, start + self.velocity) @property def top_left(self) ->Line: """ Line representing the trajectory of the point on the top left corner of the rectangle """ start = Point(self.shape.left_bound, self.shape.top_bound) return Line(start, start + self.velocity) @property def bottom_right(self) ->Line: """ Line representing the trajectory of the point on the bottom right corner of the rectangle """ start = Point(self.shape.right_bound, self.shape.bottom_bound) return Line(start, start + self.velocity) @property def bottom_left(self) ->Line: """ Line representing the trajectory of the point on the bottom left corner of the rectangle """ start = Point(self.shape.left_bound, self.shape.bottom_bound) return Line(start, start + self.velocity) class TrajectoryLine(TrajectoryRectangle): """ Create a bounding box around the line and compute the trajectory as if it were a rectangle. """ def __init__(self, shape: Line, velocity: Point): super(TrajectoryLine, self).__init__(shape, velocity) assert isinstance(shape, Line) self._reference = self.shape.start height = abs(self.shape.start.y - self.shape.end.y) width = abs(self.shape.start.x - self.shape.end.x) center = Point((self.shape.start.x + self.shape.end.x) / 2, (self. shape.start.y + self.shape.end.y) / 2) self.shape = Rectangle(height=height, width=width) self.shape.pos = center class TrajectoryPoint(TrajectoryBase): def __init__(self, shape: Point, velocity: Point): super(TrajectoryPoint, self).__init__(shape, velocity) assert isinstance(shape, Point) self._reference = self.shape @property def corners(self) ->Tuple[Line, ...]: return self._trajectory, @property def _trajectory(self) ->Line: return Line(self.shape, self.shape + self.velocity) @property def center(self) ->Line: return self._trajectory @property def top_right(self) ->Line: return self._trajectory @property def top_left(self) ->Line: return self._trajectory @property def bottom_right(self) ->Line: return self._trajectory @property def bottom_left(self) ->Line: return self._trajectory class Trajectory(object): def __new__(cls, shape: Shape, velocity: Point): if isinstance(shape, Point): return TrajectoryPoint(shape, velocity) elif isinstance(shape, Line): return TrajectoryLine(shape, velocity) elif isinstance(shape, Rectangle): return TrajectoryRectangle(shape, velocity) else: raise NotImplementedError( f'No implementation of Trajectory for input shape of type {type(shape)}' ) class Canvas(Rectangle): action_meanings = {(0): 'NOOP', (1): 'UP', (2): 'DOWN'} actions = {k: v for v, k in action_meanings.items()} def __init__(self, paddle_l: Paddle, paddle_r: Paddle, ball: Ball, snell: Snell, ball_speed: int, height: int, width: int, their_update_probability: float, refract: bool, uniform_speed: bool): super().__init__(height=height, width=width, visibility='none', render_value=0) self.pos = self.width / 2, self.height / 2 assert isinstance(their_update_probability, (float, int) ), f'their_update_probability must be numeric, not {type(their_update_probability)}' assert 0 <= their_update_probability <= 1, f'{their_update_probability} outside allowed bounds [0, 1]' self.their_update_probability = their_update_probability self.default_ball_speed = ball_speed self.snell = snell self.ball = ball self.paddle_l = paddle_l self.paddle_r = paddle_r self.sprites = [self, snell, paddle_l, paddle_r, ball] self.uniform_speed = uniform_speed self.refract = refract self.we_scored = False self.they_scored = False self.our_score = 0 self.their_score = 0 def register_sprite(self, sprite: Shape): assert issubclass(type(sprite), Shape ), f'sprite must be subclassed from Shape' self.sprites.insert(-1, sprite) @property def left_bound(self): return 0 @property def right_bound(self): return self.width @property def top_bound(self): return self.height @property def bottom_bound(self): return 0 def to_numpy(self) ->Tuple[np.ndarray, np.ndarray]: """ Performs masked rendering of objects in `self.sprites`. Priority is determined by the ordering of the list, earlier objects will be obscured by later ones. :return: (state, rendering) """ state = self._zero_rgb_image(round(self.height), round(self.width)) rendering = self._zero_rgb_image(round(self.height), round(self.width)) for sprite in self.sprites[1:]: sprite_state, sprite_rendering = sprite.to_numpy(self.height, self.width) state[sprite_state != 0] = sprite_state[sprite_state != 0] rendering[sprite_rendering != 0] = sprite_rendering[ sprite_rendering != 0] return state, rendering def score(self, who): """ Increment the score and reset the ball :param who: 'we' or 'they' :return: reward """ if who == 'they': reward = -1 self.their_score += 1 elif who == 'we': reward = 1 self.our_score += 1 else: raise ValueError(f"who must be 'we' or 'they', not {who}") self._reset_ball() return reward def step(self, action): self._move_our_paddle(action) self._step_their_paddle() reward = self._step_ball() self._step_snell() return reward def get_state_size(self) ->Tuple[int, int]: """ Return the tuple (height, width) of the canvas dimensions """ return self.height, self.width def _step_snell(self) ->None: """ Step the snell layer """ self.snell.step() def _reset_ball(self): self.ball.reset((self.width / 2, self.height / 2)) def _move_our_paddle(self, action) ->None: """ Move our paddle according to the provided action :param action: the action code """ if not isinstance(action, int): action = action.item() assert action in [a for a in self.action_meanings.keys() ], f'{action} is not a valid action' if action == self.actions['UP']: if self.paddle_r.top_bound < self.top_bound: self.paddle_r.up() elif action == self.actions['DOWN']: if self.paddle_r.bottom_bound > self.bottom_bound: self.paddle_r.down() def _step_ball(self, speed: Union[float, int]=None): """ Move the ball to the next position according to the speed of the layer it is in. :param speed: used to continue the trajectory of a ball that interacted with an object """ trajectory = self._get_trajectory(speed) self._get_first_intersection(trajectory) reward = 0 if trajectory.intersection is None: self.ball.pos = trajectory.center.end else: reward = self._interaction_dispatcher(trajectory) return reward def _get_trajectory(self, speed) ->TrajectoryBase: """ Get the ball's trajectory :param speed: The speed of the starting medium :return: trajectory `Line` """ if speed is None: speed = self._get_ball_speed() if self.ball.has_volume: trajectory = Trajectory(self.ball, self.ball.get_velocity(speed)) else: trajectory = Trajectory(self.ball.pos, self.ball.get_velocity( speed)) return trajectory def _interaction_dispatcher(self, trajectory: TrajectoryBase): """ Dispatch data to the appropriate method based on the interaction `obj`. :param trajectory: the trajectory of the ball """ reward = 0 obj = trajectory.intersected_object if obj is self: reward = self._interact_border(trajectory) elif isinstance(obj, Paddle): self._interact_paddle(trajectory) elif isinstance(obj, Snell): self._refract(trajectory) return reward def _interact_paddle(self, trajectory: TrajectoryBase) ->float: paddle = trajectory.intersected_object paddle_fraction = paddle.get_fraction_of_paddle(trajectory. get_center_at_intersection()) angle = paddle_fraction * paddle.max_angle angle = math.pi - angle if self.ball.unit_velocity.x > 0 else angle self.ball.angle = angle reward = self._finish_step_ball(trajectory) return reward def _refract(self, trajectory: TrajectoryBase): edge = trajectory.intersected_edge if self.refract: s0, s1 = self._get_start_and_end_speed(trajectory) angle = edge.angle_to_normal(trajectory.center) if self._exceeds_critical_angle(angle, s0, s1): self._reflect(Point(-1, 1), trajectory) return new_angle = math.asin(s1 / s0 * math.sin(angle)) boundary_angle, new_angle = (self. _adjust_refraction_to_boundary_angle(edge, new_angle)) new_angle = self._adjust_refraction_to_direction_of_incidence( boundary_angle, new_angle, trajectory) self.ball.angle = new_angle return self._finish_step_ball(trajectory) @staticmethod def _exceeds_critical_angle(angle: float, s0: float, s1: float) ->bool: """ Test if the angle exceeds the critical angle :param angle: The angle to the normal of the boundary :param s0: The speed of the original medium :param s1: The speed of the next medium :return: True if the angle exceeds the critical angle """ if s1 > s0: critical_angle = get_critical_angle(s0, s1) if abs(angle) >= critical_angle: return True return False @staticmethod def _adjust_refraction_to_direction_of_incidence(boundary_angle: float, new_angle: float, trajectory: TrajectoryBase) ->float: """ If the direction of incidence was from the right of the boundary, reflect `new_angle`, otherwise, return `new_angle` without modification. :param boundary_angle: must be in the first or fourth quadrant :param new_angle: The angle to be reflected in the return :param trajectory: The angle of the incoming ball in global coordinates :return: The (possibly) reflected `new_angle` """ angle = trajectory.center.angle assert -math.pi / 2 <= boundary_angle <= math.pi / 2, 'boundary_angle should be in first or fourth quadrant' if boundary_angle >= 0 and boundary_angle < angle % (2 * math.pi ) < boundary_angle + math.pi: new_angle = math.pi - new_angle elif boundary_angle < 0 and boundary_angle % (2 * math.pi ) + math.pi < angle % (2 * math.pi) < boundary_angle % (2 * math.pi ): new_angle = math.pi - new_angle return new_angle @staticmethod def _adjust_refraction_to_boundary_angle(boundary: Line, new_angle: float ) ->Tuple[float, float]: """ Compute the rotation of `new_angle` back to global coordinates. Assume incidence from the left side of the boundary. :param boundary: The boundary `primitives.Line` object :param new_angle: The refracted angle normal to the boundary :return: The new angle in global coordinates """ boundary_angle = boundary.angle % (2 * math.pi) if 0 <= boundary_angle < math.pi / 2: boundary_angle = boundary_angle new_angle = boundary_angle - math.pi / 2 + new_angle elif math.pi / 2 <= boundary_angle < math.pi: boundary_angle = math.pi - boundary_angle new_angle = math.pi / 2 - boundary_angle + new_angle elif math.pi <= boundary_angle < 3 * math.pi / 2: boundary_angle = math.pi - boundary_angle new_angle = boundary_angle - math.pi / 2 + new_angle elif 2 * math.pi / 3 <= boundary_angle < 2 * math.pi: boundary_angle = 2 * math.pi - boundary_angle new_angle = math.pi / 2 - boundary_angle - new_angle else: raise ValueError(f'Unexpected angle {boundary_angle}') return boundary_angle, new_angle def _get_start_and_end_speed(self, trajectory: TrajectoryBase) ->Tuple[ float, float]: """ Get the speed at the start of the trajectory and the speed at the end of the trajectory. :param trajectory: The trajectory `primitives.Line` object :return: (initial speed, final speed) """ snell = trajectory.intersected_object if snell.is_in(trajectory.center.start): s0 = snell.speed s1 = self.default_ball_speed else: s0 = self.default_ball_speed s1 = snell.speed return s0, s1 def _interact_border(self, trajectory: TrajectoryBase) ->float: reward = 0.0 edge = trajectory.intersected_edge if edge == self.top_edge or edge == self.bot_edge: self._reflect(Point(1, -1), trajectory) elif edge == self.left_edge: reward = self.score('we') elif edge == self.right_edge: reward = self.score('they') else: raise ValueError(f'invalid edge, {edge}') return reward def _reflect(self, direction: Point, trajectory: TrajectoryBase): """ Multiplies the velocity of the ball by `direction`, continues the path of the ball by calculating the remaining speed using trajectory and point. :param direction: velocity multiplier :param trajectory: The original trajectory of the ball """ self.ball.unit_velocity *= direction return self._finish_step_ball(trajectory) def _finish_step_ball(self, trajectory: TrajectoryBase): """ Finish the remainder of the trajectory after any interactions. :param trajectory: The original trajectory :return: reward """ point = trajectory.get_center_at_intersection() self.ball.pos = point + self.ball.unit_velocity * EPSILON return self._step_ball(trajectory.remaining_speed) def _get_first_intersection(self, trajectory: TrajectoryBase): """ Find the first point at which the trajectory interacted with an object. :param trajectory: the trajectory of the object :return: (shape object interacted with, point of interaction, line object interacted with) """ for trajectory_line in trajectory.corners: for o in self.sprites: if not isinstance(o, Ball): intersection_result = o.get_intersection(trajectory_line) if intersection_result is not None: edge, point = intersection_result if trajectory.intersection is None: trajectory.set_intersection(point, trajectory_line, o, edge) elif point == trajectory.intersection and trajectory_line == trajectory.intersected_trajectory: raise NotImplementedError( 'overlapping parallel edges not implemented') elif point.l2_distance(trajectory_line.start ) < trajectory.intersection.l2_distance(trajectory .intersected_trajectory.start): trajectory.set_intersection(point, trajectory_line, o, edge) def _get_ball_speed(self) ->float: if self.uniform_speed: return self.default_ball_speed elif self.ball.is_overlapping(self.snell): return self.snell.speed else: return self.default_ball_speed def _step_their_paddle(self): """ Move the opponents paddle. Override this in a subclass to change the behavior. """ if random.random() < self.their_update_probability: if self.paddle_l.y < self.ball.y: if self.paddle_l.top_bound < self.top_bound: self.paddle_l.up() elif self.paddle_l.bottom_bound > self.bottom_bound: self.paddle_l.down() <|reserved_special_token_1|> import abc import math import random from typing import Union, Tuple import numpy as np from scipy import stats from . import Rectangle, Line, Point, Shape __all__ = ['get_critical_angle', 'Paddle', 'Ball', 'Snell', 'Canvas'] EPSILON = 1e-7 def get_critical_angle(s0: float, s1: float) -> Union[float, None]: """ Returns the critical angle if it exists for a ball moving from a medium with velocity `s0` to a medium with velocity `s1`. If the critical angle does not exist, returns None. :param s0: speed of the initial medium :param s1: speed of the final medium :return: critical angle or None """ if s0 < s1: critical_angle = math.asin(s0 / s1) else: critical_angle = None return critical_angle class Paddle(Rectangle): def __init__(self, height: float, width: float, speed: float, side: str, max_angle: float, visibility: str): """ :param height: The paddle height :param width: The paddle width (only matters for rendering) :param side: The side the paddle will be on ('left' or 'right') :param speed: The units the paddle moves in a single turn :param visibility: Whether and how to render the paddle. See `Shape.visibility` :param max_angle: The maximum angle at which the paddle can hit the ball """ super().__init__(height=height, width=width, visibility=visibility, render_value=255) assert side in ['left', 'right'], f"side must be 'left' or 'right', not {side}" assert 0 <= max_angle <= math.pi / 2, f"max angle must be between 0 and pi/2, not {max_angle}" self.side = side self.speed = speed self.max_angle = max_angle def up(self): self.y += self.speed def down(self): self.y -= self.speed def _get_edges(self) -> Tuple[Line]: """ Only return the field-side edge """ if self.side == 'right': return Line((self.left_bound, self.bottom_bound), (self.left_bound, self.top_bound)), elif self.side == 'left': return Line((self.right_bound, self.bottom_bound), (self.right_bound, self.top_bound)), def get_fraction_of_paddle(self, point: Point): """ Computes the fractional distance from the middle of the paddle, normalized by the paddle's height. Asserts if the ball was not on the paddle. :param point: the point where the ball hit the paddle :return: fraction of the paddle """ fraction = (point.y - self.y) / self.height fraction = max(min(fraction, 0.5), -0.5) # clamp to +/- 0.5 return fraction class Ball(Rectangle): def __init__(self, size: float, max_initial_angle: float, visibility: str, has_volume: bool = False): """ Ball object :param has_volume: :param size: The size to render the ball :param max_initial_angle: The maximum angle the ball can start with :param visibility: How to render the ball. See `Shape.visibility` :param has_volume: determines whether the ball interacts as a point or as an area """ super().__init__(width=size, height=size, visibility=visibility, render_value=255) self.max_initial_angle = max_initial_angle self.reset(self.pos, direction='left') self.has_volume = has_volume def reset(self, position: Union[Tuple[float, float], Point], direction: str = 'right'): if direction == 'right': self._angle = (2 * random.random() - 1) * self.max_initial_angle elif direction == 'left': self._angle = math.pi - (2 * random.random() - 1) * self.max_initial_angle else: raise ValueError(f"direction must be 'left' or 'right', not {direction}") self.pos = position @property def angle(self): """ Angle with respect to the right horizontal """ return self._angle @angle.setter def angle(self, value): self._angle = value % (2 * math.pi) @property def unit_velocity(self) -> Point: x = math.cos(self.angle) y = math.sin(self.angle) return Point(x, y) @unit_velocity.setter def unit_velocity(self, value: Union[Tuple[float, float], Point]): """ Sets the angle parameter give a set of (x, y) coordinates. :param value: (x, y) """ if isinstance(value, tuple): value = Point(*value) assert isinstance(value, Point), f"value must be a point, not {type(value)}" self.angle = value.angle def get_velocity(self, speed: Union[float, int]): return self.unit_velocity * speed class Snell(Rectangle): def __init__(self, width, height, speed, change_rate, visibility): """ Rectangular area with a different ball speed. :param width: The width of the layer :param height: The height of the layer :param change_rate: Rate at which the ball speed changes, the standard deviation of the change on each step. :param visibility: Whether and how to render the layer. See `Shape.visibility` """ assert change_rate >= 0, "Snell `change_rate` must be non-negative" super().__init__(width=width, height=height, visibility=visibility, render_value=(235, 76, 52)) self.speed = speed self._initial_speed = speed self.change_rate = change_rate def step(self): """ Step the Snell speed using a bounded Gaussian random walk. - step with mean 0, standard deviation `self.speed` - Clip the speed at `0.5 * self._initial_speed <= self.speed <= 2.0 * self._initial_speed` """ if self.change_rate != 0: self.speed += stats.norm(loc=0, scale=self.change_rate).rvs() if self.speed < 0.5 * self._initial_speed: self.speed = 0.5 * self._initial_speed if self.speed > 2.0 * self._initial_speed: self.speed = 2.0 * self._initial_speed else: pass class TrajectoryBase(abc.ABC): def __init__(self, shape: Union[Point, Line, Rectangle], velocity: Point): self.shape = shape self.velocity = velocity self._reference = None self.intersection = None self.intersected_trajectory = None self.intersected_object = None self.intersected_edge = None self.remaining_speed = None def set_intersection(self, point: Point, trajectory_line: Line, obj: Shape, edge: Line): assert isinstance(obj, Shape), f"type Shape expected, not {type(obj)}" assert isinstance(point, Point), f"type Point expected, not {type(point)}" assert isinstance(edge, Line), f"type Line expected, not {type(edge)}" self.intersection = point self.intersected_trajectory = trajectory_line self.remaining_speed = point.l2_distance(trajectory_line.end) self.intersected_object = obj self.intersected_edge = edge def get_center_at_intersection(self) -> Point: """ Get the new center of `self.shape` given that it moved along `intersected_trajectory` to `intersection` :return: new center point """ return self._reference + (self.intersection - self.intersected_trajectory.start) @property def corners(self) -> Tuple[Line, ...]: return self.top_left, self.top_right, self.bottom_right, self.bottom_left @property @abc.abstractmethod def center(self) -> Line: ... @property @abc.abstractmethod def top_right(self) -> Line: ... @property @abc.abstractmethod def top_left(self) -> Line: ... @property @abc.abstractmethod def bottom_right(self) -> Line: ... @property @abc.abstractmethod def bottom_left(self) -> Line: ... class TrajectoryRectangle(TrajectoryBase): """ Compute the trajectory of each corner of the rectangle """ def __init__(self, shape: Rectangle, velocity: Point): super(TrajectoryRectangle, self).__init__(shape, velocity) assert isinstance(shape, Rectangle) self._reference = self.shape.pos @property def center(self) -> Line: """ Line representing the trajectory of the center of the rectangle """ return Line(self.shape.pos, self.shape.pos + self.velocity) @property def top_right(self) -> Line: """ Line representing the trajectory of the point on the top right corner of the rectangle """ start = Point(self.shape.right_bound, self.shape.top_bound) return Line(start, start + self.velocity) @property def top_left(self) -> Line: """ Line representing the trajectory of the point on the top left corner of the rectangle """ start = Point(self.shape.left_bound, self.shape.top_bound) return Line(start, start + self.velocity) @property def bottom_right(self) -> Line: """ Line representing the trajectory of the point on the bottom right corner of the rectangle """ start = Point(self.shape.right_bound, self.shape.bottom_bound) return Line(start, start + self.velocity) @property def bottom_left(self) -> Line: """ Line representing the trajectory of the point on the bottom left corner of the rectangle """ start = Point(self.shape.left_bound, self.shape.bottom_bound) return Line(start, start + self.velocity) class TrajectoryLine(TrajectoryRectangle): """ Create a bounding box around the line and compute the trajectory as if it were a rectangle. """ # noinspection PyTypeChecker # noinspection PyUnresolvedReferences def __init__(self, shape: Line, velocity: Point): super(TrajectoryLine, self).__init__(shape, velocity) assert isinstance(shape, Line) self._reference = self.shape.start height = abs(self.shape.start.y - self.shape.end.y) width = abs(self.shape.start.x - self.shape.end.x) center = Point((self.shape.start.x + self.shape.end.x) / 2, (self.shape.start.y + self.shape.end.y) / 2) self.shape = Rectangle(height=height, width=width) self.shape.pos = center class TrajectoryPoint(TrajectoryBase): def __init__(self, shape: Point, velocity: Point): super(TrajectoryPoint, self).__init__(shape, velocity) assert isinstance(shape, Point) self._reference = self.shape @property def corners(self) -> Tuple[Line, ...]: return (self._trajectory,) @property def _trajectory(self) -> Line: return Line(self.shape, self.shape + self.velocity) @property def center(self) -> Line: return self._trajectory @property def top_right(self) -> Line: return self._trajectory @property def top_left(self) -> Line: return self._trajectory @property def bottom_right(self) -> Line: return self._trajectory @property def bottom_left(self) -> Line: return self._trajectory class Trajectory(object): def __new__(cls, shape: Shape, velocity: Point): if isinstance(shape, Point): return TrajectoryPoint(shape, velocity) elif isinstance(shape, Line): return TrajectoryLine(shape, velocity) elif isinstance(shape, Rectangle): return TrajectoryRectangle(shape, velocity) else: raise NotImplementedError(f"No implementation of Trajectory for input shape of type {type(shape)}") class Canvas(Rectangle): action_meanings = {0: 'NOOP', 1: 'UP', 2: 'DOWN', } actions = {k: v for v, k in action_meanings.items()} def __init__(self, paddle_l: Paddle, paddle_r: Paddle, ball: Ball, snell: Snell, ball_speed: int, height: int, width: int, their_update_probability: float, refract: bool, uniform_speed: bool): super().__init__(height=height, width=width, visibility='none', render_value=0) self.pos = self.width / 2, self.height / 2 assert isinstance(their_update_probability, (float, int)), \ f"their_update_probability must be numeric, not {type(their_update_probability)}" assert 0 <= their_update_probability <= 1, f"{their_update_probability} outside allowed bounds [0, 1]" self.their_update_probability = their_update_probability self.default_ball_speed = ball_speed # Initialize objects self.snell = snell self.ball = ball self.paddle_l = paddle_l self.paddle_r = paddle_r self.sprites = [self, snell, paddle_l, paddle_r, ball] self.uniform_speed = uniform_speed self.refract = refract self.we_scored = False self.they_scored = False # score self.our_score = 0 self.their_score = 0 def register_sprite(self, sprite: Shape): assert issubclass(type(sprite), Shape), f"sprite must be subclassed from Shape" # noinspection PyTypeChecker self.sprites.insert(-1, sprite) # insert before ball @property def left_bound(self): return 0 @property def right_bound(self): return self.width @property def top_bound(self): return self.height @property def bottom_bound(self): return 0 # noinspection PyMethodOverriding def to_numpy(self) -> Tuple[np.ndarray, np.ndarray]: """ Performs masked rendering of objects in `self.sprites`. Priority is determined by the ordering of the list, earlier objects will be obscured by later ones. :return: (state, rendering) """ state = self._zero_rgb_image(round(self.height), round(self.width)) rendering = self._zero_rgb_image(round(self.height), round(self.width)) for sprite in self.sprites[1:]: # skip self sprite_state, sprite_rendering = sprite.to_numpy(self.height, self.width) state[sprite_state != 0] = sprite_state[sprite_state != 0] rendering[sprite_rendering != 0] = sprite_rendering[sprite_rendering != 0] return state, rendering def score(self, who): """ Increment the score and reset the ball :param who: 'we' or 'they' :return: reward """ if who == 'they': reward = -1 self.their_score += 1 elif who == 'we': reward = 1 self.our_score += 1 else: raise ValueError(f"who must be 'we' or 'they', not {who}") self._reset_ball() return reward def step(self, action): self._move_our_paddle(action) self._step_their_paddle() reward = self._step_ball() self._step_snell() return reward def get_state_size(self) -> Tuple[int, int]: """ Return the tuple (height, width) of the canvas dimensions """ return self.height, self.width def _step_snell(self) -> None: """ Step the snell layer """ self.snell.step() def _reset_ball(self): self.ball.reset((self.width / 2, self.height / 2)) def _move_our_paddle(self, action) -> None: """ Move our paddle according to the provided action :param action: the action code """ if not isinstance(action, int): action = action.item() # pops the item if the action is a single tensor assert action in [a for a in self.action_meanings.keys()], f"{action} is not a valid action" if action == self.actions['UP']: if self.paddle_r.top_bound < self.top_bound: self.paddle_r.up() elif action == self.actions['DOWN']: if self.paddle_r.bottom_bound > self.bottom_bound: self.paddle_r.down() def _step_ball(self, speed: Union[float, int] = None): """ Move the ball to the next position according to the speed of the layer it is in. :param speed: used to continue the trajectory of a ball that interacted with an object """ trajectory = self._get_trajectory(speed) self._get_first_intersection(trajectory) reward = 0 if trajectory.intersection is None: # No intersection self.ball.pos = trajectory.center.end else: reward = self._interaction_dispatcher(trajectory) return reward def _get_trajectory(self, speed) -> TrajectoryBase: """ Get the ball's trajectory :param speed: The speed of the starting medium :return: trajectory `Line` """ if speed is None: speed = self._get_ball_speed() if self.ball.has_volume: trajectory = Trajectory(self.ball, self.ball.get_velocity(speed)) else: trajectory = Trajectory(self.ball.pos, self.ball.get_velocity(speed)) return trajectory def _interaction_dispatcher(self, trajectory: TrajectoryBase): """ Dispatch data to the appropriate method based on the interaction `obj`. :param trajectory: the trajectory of the ball """ reward = 0 obj = trajectory.intersected_object if obj is self: # border interaction reward = self._interact_border(trajectory) elif isinstance(obj, Paddle): # paddle interaction self._interact_paddle(trajectory) elif isinstance(obj, Snell): self._refract(trajectory) return reward def _interact_paddle(self, trajectory: TrajectoryBase) -> float: paddle = trajectory.intersected_object paddle_fraction = paddle.get_fraction_of_paddle(trajectory.get_center_at_intersection()) angle = paddle_fraction * paddle.max_angle angle = math.pi - angle if self.ball.unit_velocity.x > 0 else angle self.ball.angle = angle reward = self._finish_step_ball(trajectory) return reward def _refract(self, trajectory: TrajectoryBase): edge = trajectory.intersected_edge if self.refract: s0, s1 = self._get_start_and_end_speed(trajectory) angle = edge.angle_to_normal(trajectory.center) if self._exceeds_critical_angle(angle, s0, s1): # TODO: reflect to arbitrary angle (non-vertical interface) self._reflect(Point(-1, 1), trajectory) return new_angle = math.asin(s1 / s0 * math.sin(angle)) boundary_angle, new_angle = self._adjust_refraction_to_boundary_angle(edge, new_angle) new_angle = self._adjust_refraction_to_direction_of_incidence(boundary_angle, new_angle, trajectory) self.ball.angle = new_angle return self._finish_step_ball(trajectory) @staticmethod def _exceeds_critical_angle(angle: float, s0: float, s1: float) -> bool: """ Test if the angle exceeds the critical angle :param angle: The angle to the normal of the boundary :param s0: The speed of the original medium :param s1: The speed of the next medium :return: True if the angle exceeds the critical angle """ if s1 > s0: # if the second speed is faster, there is a critical angle critical_angle = get_critical_angle(s0, s1) if abs(angle) >= critical_angle: return True return False @staticmethod def _adjust_refraction_to_direction_of_incidence(boundary_angle: float, new_angle: float, trajectory: TrajectoryBase) -> float: """ If the direction of incidence was from the right of the boundary, reflect `new_angle`, otherwise, return `new_angle` without modification. :param boundary_angle: must be in the first or fourth quadrant :param new_angle: The angle to be reflected in the return :param trajectory: The angle of the incoming ball in global coordinates :return: The (possibly) reflected `new_angle` """ angle = trajectory.center.angle assert -math.pi / 2 <= boundary_angle <= math.pi / 2, "boundary_angle should be in first or fourth quadrant" # noinspection PyChainedComparisons if boundary_angle >= 0 and boundary_angle < angle % (2 * math.pi) < boundary_angle + math.pi: new_angle = math.pi - new_angle elif (boundary_angle < 0 and boundary_angle % (2 * math.pi) + math.pi < angle % (2 * math.pi) < boundary_angle % ( 2 * math.pi)): new_angle = math.pi - new_angle return new_angle @staticmethod def _adjust_refraction_to_boundary_angle(boundary: Line, new_angle: float) -> Tuple[float, float]: """ Compute the rotation of `new_angle` back to global coordinates. Assume incidence from the left side of the boundary. :param boundary: The boundary `primitives.Line` object :param new_angle: The refracted angle normal to the boundary :return: The new angle in global coordinates """ # TODO: verify this works with a non-vertical interface boundary_angle = boundary.angle % (2 * math.pi) if 0 <= boundary_angle < math.pi / 2: # in the first quadrant boundary_angle = boundary_angle new_angle = boundary_angle - math.pi / 2 + new_angle elif math.pi / 2 <= boundary_angle < math.pi: # in the second quadrant boundary_angle = math.pi - boundary_angle new_angle = math.pi / 2 - boundary_angle + new_angle elif math.pi <= boundary_angle < 3 * math.pi / 2: # in the third quadrant boundary_angle = math.pi - boundary_angle new_angle = boundary_angle - math.pi / 2 + new_angle elif 2 * math.pi / 3 <= boundary_angle < 2 * math.pi: # in the fourth quadrant boundary_angle = 2 * math.pi - boundary_angle new_angle = math.pi / 2 - boundary_angle - new_angle else: raise ValueError(f'Unexpected angle {boundary_angle}') return boundary_angle, new_angle def _get_start_and_end_speed(self, trajectory: TrajectoryBase) -> Tuple[float, float]: """ Get the speed at the start of the trajectory and the speed at the end of the trajectory. :param trajectory: The trajectory `primitives.Line` object :return: (initial speed, final speed) """ snell = trajectory.intersected_object # todo: detect if start is in some other snell layer if snell.is_in(trajectory.center.start): s0 = snell.speed s1 = self.default_ball_speed else: s0 = self.default_ball_speed s1 = snell.speed return s0, s1 def _interact_border(self, trajectory: TrajectoryBase) -> float: reward = 0. edge = trajectory.intersected_edge if edge == self.top_edge or edge == self.bot_edge: self._reflect(Point(1, -1), trajectory) elif edge == self.left_edge: reward = self.score('we') elif edge == self.right_edge: reward = self.score('they') else: raise ValueError(f'invalid edge, {edge}') return reward def _reflect(self, direction: Point, trajectory: TrajectoryBase): """ Multiplies the velocity of the ball by `direction`, continues the path of the ball by calculating the remaining speed using trajectory and point. :param direction: velocity multiplier :param trajectory: The original trajectory of the ball """ self.ball.unit_velocity *= direction return self._finish_step_ball(trajectory) def _finish_step_ball(self, trajectory: TrajectoryBase): """ Finish the remainder of the trajectory after any interactions. :param trajectory: The original trajectory :return: reward """ point = trajectory.get_center_at_intersection() self.ball.pos = point + self.ball.unit_velocity * EPSILON return self._step_ball(trajectory.remaining_speed) def _get_first_intersection(self, trajectory: TrajectoryBase): """ Find the first point at which the trajectory interacted with an object. :param trajectory: the trajectory of the object :return: (shape object interacted with, point of interaction, line object interacted with) """ for trajectory_line in trajectory.corners: for o in self.sprites: if not isinstance(o, Ball): intersection_result = o.get_intersection(trajectory_line) if intersection_result is not None: edge, point = intersection_result if trajectory.intersection is None: trajectory.set_intersection(point, trajectory_line, o, edge) elif point == trajectory.intersection and trajectory_line == trajectory.intersected_trajectory: raise NotImplementedError("overlapping parallel edges not implemented") elif (point.l2_distance(trajectory_line.start) < trajectory.intersection.l2_distance(trajectory.intersected_trajectory.start)): trajectory.set_intersection(point, trajectory_line, o, edge) def _get_ball_speed(self) -> float: if self.uniform_speed: return self.default_ball_speed else: if self.ball.is_overlapping(self.snell): return self.snell.speed else: return self.default_ball_speed def _step_their_paddle(self): """ Move the opponents paddle. Override this in a subclass to change the behavior. """ if random.random() < self.their_update_probability: if self.paddle_l.y < self.ball.y: if self.paddle_l.top_bound < self.top_bound: self.paddle_l.up() else: if self.paddle_l.bottom_bound > self.bottom_bound: self.paddle_l.down()
flexible
{ "blob_id": "42d2be7544d2afb9580841422ae35e1a5621df52", "index": 6459, "step-1": "<mask token>\n\n\nclass TrajectoryRectangle(TrajectoryBase):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n @property\n def top_left(self) ->Line:\n \"\"\"\n Line representing the trajectory of the point on the top left corner of the rectangle\n \"\"\"\n start = Point(self.shape.left_bound, self.shape.top_bound)\n return Line(start, start + self.velocity)\n <mask token>\n <mask token>\n\n\nclass TrajectoryLine(TrajectoryRectangle):\n \"\"\"\n Create a bounding box around the line and compute the trajectory as if it were a rectangle.\n \"\"\"\n\n def __init__(self, shape: Line, velocity: Point):\n super(TrajectoryLine, self).__init__(shape, velocity)\n assert isinstance(shape, Line)\n self._reference = self.shape.start\n height = abs(self.shape.start.y - self.shape.end.y)\n width = abs(self.shape.start.x - self.shape.end.x)\n center = Point((self.shape.start.x + self.shape.end.x) / 2, (self.\n shape.start.y + self.shape.end.y) / 2)\n self.shape = Rectangle(height=height, width=width)\n self.shape.pos = center\n\n\nclass TrajectoryPoint(TrajectoryBase):\n\n def __init__(self, shape: Point, velocity: Point):\n super(TrajectoryPoint, self).__init__(shape, velocity)\n assert isinstance(shape, Point)\n self._reference = self.shape\n\n @property\n def corners(self) ->Tuple[Line, ...]:\n return self._trajectory,\n\n @property\n def _trajectory(self) ->Line:\n return Line(self.shape, self.shape + self.velocity)\n\n @property\n def center(self) ->Line:\n return self._trajectory\n\n @property\n def top_right(self) ->Line:\n return self._trajectory\n\n @property\n def top_left(self) ->Line:\n return self._trajectory\n\n @property\n def bottom_right(self) ->Line:\n return self._trajectory\n\n @property\n def bottom_left(self) ->Line:\n return self._trajectory\n\n\nclass Trajectory(object):\n\n def __new__(cls, shape: Shape, velocity: Point):\n if isinstance(shape, Point):\n return TrajectoryPoint(shape, velocity)\n elif isinstance(shape, Line):\n return TrajectoryLine(shape, velocity)\n elif isinstance(shape, Rectangle):\n return TrajectoryRectangle(shape, velocity)\n else:\n raise NotImplementedError(\n f'No implementation of Trajectory for input shape of type {type(shape)}'\n )\n\n\nclass Canvas(Rectangle):\n action_meanings = {(0): 'NOOP', (1): 'UP', (2): 'DOWN'}\n actions = {k: v for v, k in action_meanings.items()}\n\n def __init__(self, paddle_l: Paddle, paddle_r: Paddle, ball: Ball,\n snell: Snell, ball_speed: int, height: int, width: int,\n their_update_probability: float, refract: bool, uniform_speed: bool):\n super().__init__(height=height, width=width, visibility='none',\n render_value=0)\n self.pos = self.width / 2, self.height / 2\n assert isinstance(their_update_probability, (float, int)\n ), f'their_update_probability must be numeric, not {type(their_update_probability)}'\n assert 0 <= their_update_probability <= 1, f'{their_update_probability} outside allowed bounds [0, 1]'\n self.their_update_probability = their_update_probability\n self.default_ball_speed = ball_speed\n self.snell = snell\n self.ball = ball\n self.paddle_l = paddle_l\n self.paddle_r = paddle_r\n self.sprites = [self, snell, paddle_l, paddle_r, ball]\n self.uniform_speed = uniform_speed\n self.refract = refract\n self.we_scored = False\n self.they_scored = False\n self.our_score = 0\n self.their_score = 0\n\n def register_sprite(self, sprite: Shape):\n assert issubclass(type(sprite), Shape\n ), f'sprite must be subclassed from Shape'\n self.sprites.insert(-1, sprite)\n\n @property\n def left_bound(self):\n return 0\n\n @property\n def right_bound(self):\n return self.width\n\n @property\n def top_bound(self):\n return self.height\n\n @property\n def bottom_bound(self):\n return 0\n\n def to_numpy(self) ->Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Performs masked rendering of objects in `self.sprites`. Priority is determined by the ordering of the list,\n earlier objects will be obscured by later ones.\n\n :return: (state, rendering)\n \"\"\"\n state = self._zero_rgb_image(round(self.height), round(self.width))\n rendering = self._zero_rgb_image(round(self.height), round(self.width))\n for sprite in self.sprites[1:]:\n sprite_state, sprite_rendering = sprite.to_numpy(self.height,\n self.width)\n state[sprite_state != 0] = sprite_state[sprite_state != 0]\n rendering[sprite_rendering != 0] = sprite_rendering[\n sprite_rendering != 0]\n return state, rendering\n\n def score(self, who):\n \"\"\"\n Increment the score and reset the ball\n\n :param who: 'we' or 'they'\n :return: reward\n \"\"\"\n if who == 'they':\n reward = -1\n self.their_score += 1\n elif who == 'we':\n reward = 1\n self.our_score += 1\n else:\n raise ValueError(f\"who must be 'we' or 'they', not {who}\")\n self._reset_ball()\n return reward\n\n def step(self, action):\n self._move_our_paddle(action)\n self._step_their_paddle()\n reward = self._step_ball()\n self._step_snell()\n return reward\n\n def get_state_size(self) ->Tuple[int, int]:\n \"\"\"\n Return the tuple (height, width) of the canvas dimensions\n \"\"\"\n return self.height, self.width\n\n def _step_snell(self) ->None:\n \"\"\"\n Step the snell layer\n \"\"\"\n self.snell.step()\n\n def _reset_ball(self):\n self.ball.reset((self.width / 2, self.height / 2))\n\n def _move_our_paddle(self, action) ->None:\n \"\"\"\n Move our paddle according to the provided action\n\n :param action: the action code\n \"\"\"\n if not isinstance(action, int):\n action = action.item()\n assert action in [a for a in self.action_meanings.keys()\n ], f'{action} is not a valid action'\n if action == self.actions['UP']:\n if self.paddle_r.top_bound < self.top_bound:\n self.paddle_r.up()\n elif action == self.actions['DOWN']:\n if self.paddle_r.bottom_bound > self.bottom_bound:\n self.paddle_r.down()\n\n def _step_ball(self, speed: Union[float, int]=None):\n \"\"\"\n Move the ball to the next position according to the speed of the layer it is in.\n\n :param speed: used to continue the trajectory of a ball that interacted with an object\n \"\"\"\n trajectory = self._get_trajectory(speed)\n self._get_first_intersection(trajectory)\n reward = 0\n if trajectory.intersection is None:\n self.ball.pos = trajectory.center.end\n else:\n reward = self._interaction_dispatcher(trajectory)\n return reward\n\n def _get_trajectory(self, speed) ->TrajectoryBase:\n \"\"\"\n Get the ball's trajectory\n\n :param speed: The speed of the starting medium\n :return: trajectory `Line`\n \"\"\"\n if speed is None:\n speed = self._get_ball_speed()\n if self.ball.has_volume:\n trajectory = Trajectory(self.ball, self.ball.get_velocity(speed))\n else:\n trajectory = Trajectory(self.ball.pos, self.ball.get_velocity(\n speed))\n return trajectory\n\n def _interaction_dispatcher(self, trajectory: TrajectoryBase):\n \"\"\"\n Dispatch data to the appropriate method based on the interaction `obj`.\n\n :param trajectory: the trajectory of the ball\n \"\"\"\n reward = 0\n obj = trajectory.intersected_object\n if obj is self:\n reward = self._interact_border(trajectory)\n elif isinstance(obj, Paddle):\n self._interact_paddle(trajectory)\n elif isinstance(obj, Snell):\n self._refract(trajectory)\n return reward\n\n def _interact_paddle(self, trajectory: TrajectoryBase) ->float:\n paddle = trajectory.intersected_object\n paddle_fraction = paddle.get_fraction_of_paddle(trajectory.\n get_center_at_intersection())\n angle = paddle_fraction * paddle.max_angle\n angle = math.pi - angle if self.ball.unit_velocity.x > 0 else angle\n self.ball.angle = angle\n reward = self._finish_step_ball(trajectory)\n return reward\n\n def _refract(self, trajectory: TrajectoryBase):\n edge = trajectory.intersected_edge\n if self.refract:\n s0, s1 = self._get_start_and_end_speed(trajectory)\n angle = edge.angle_to_normal(trajectory.center)\n if self._exceeds_critical_angle(angle, s0, s1):\n self._reflect(Point(-1, 1), trajectory)\n return\n new_angle = math.asin(s1 / s0 * math.sin(angle))\n boundary_angle, new_angle = (self.\n _adjust_refraction_to_boundary_angle(edge, new_angle))\n new_angle = self._adjust_refraction_to_direction_of_incidence(\n boundary_angle, new_angle, trajectory)\n self.ball.angle = new_angle\n return self._finish_step_ball(trajectory)\n\n @staticmethod\n def _exceeds_critical_angle(angle: float, s0: float, s1: float) ->bool:\n \"\"\"\n Test if the angle exceeds the critical angle\n\n :param angle: The angle to the normal of the boundary\n :param s0: The speed of the original medium\n :param s1: The speed of the next medium\n :return: True if the angle exceeds the critical angle\n \"\"\"\n if s1 > s0:\n critical_angle = get_critical_angle(s0, s1)\n if abs(angle) >= critical_angle:\n return True\n return False\n\n @staticmethod\n def _adjust_refraction_to_direction_of_incidence(boundary_angle: float,\n new_angle: float, trajectory: TrajectoryBase) ->float:\n \"\"\"\n If the direction of incidence was from the right of the boundary, reflect `new_angle`, otherwise, return\n `new_angle` without modification.\n\n :param boundary_angle: must be in the first or fourth quadrant\n :param new_angle: The angle to be reflected in the return\n :param trajectory: The angle of the incoming ball in global coordinates\n :return: The (possibly) reflected `new_angle`\n \"\"\"\n angle = trajectory.center.angle\n assert -math.pi / 2 <= boundary_angle <= math.pi / 2, 'boundary_angle should be in first or fourth quadrant'\n if boundary_angle >= 0 and boundary_angle < angle % (2 * math.pi\n ) < boundary_angle + math.pi:\n new_angle = math.pi - new_angle\n elif boundary_angle < 0 and boundary_angle % (2 * math.pi\n ) + math.pi < angle % (2 * math.pi) < boundary_angle % (2 * math.pi\n ):\n new_angle = math.pi - new_angle\n return new_angle\n\n @staticmethod\n def _adjust_refraction_to_boundary_angle(boundary: Line, new_angle: float\n ) ->Tuple[float, float]:\n \"\"\"\n Compute the rotation of `new_angle` back to global coordinates. Assume incidence from the left side of the\n boundary.\n\n :param boundary: The boundary `primitives.Line` object\n :param new_angle: The refracted angle normal to the boundary\n :return: The new angle in global coordinates\n \"\"\"\n boundary_angle = boundary.angle % (2 * math.pi)\n if 0 <= boundary_angle < math.pi / 2:\n boundary_angle = boundary_angle\n new_angle = boundary_angle - math.pi / 2 + new_angle\n elif math.pi / 2 <= boundary_angle < math.pi:\n boundary_angle = math.pi - boundary_angle\n new_angle = math.pi / 2 - boundary_angle + new_angle\n elif math.pi <= boundary_angle < 3 * math.pi / 2:\n boundary_angle = math.pi - boundary_angle\n new_angle = boundary_angle - math.pi / 2 + new_angle\n elif 2 * math.pi / 3 <= boundary_angle < 2 * math.pi:\n boundary_angle = 2 * math.pi - boundary_angle\n new_angle = math.pi / 2 - boundary_angle - new_angle\n else:\n raise ValueError(f'Unexpected angle {boundary_angle}')\n return boundary_angle, new_angle\n\n def _get_start_and_end_speed(self, trajectory: TrajectoryBase) ->Tuple[\n float, float]:\n \"\"\"\n Get the speed at the start of the trajectory and the speed at the end of the trajectory.\n\n :param trajectory: The trajectory `primitives.Line` object\n :return: (initial speed, final speed)\n \"\"\"\n snell = trajectory.intersected_object\n if snell.is_in(trajectory.center.start):\n s0 = snell.speed\n s1 = self.default_ball_speed\n else:\n s0 = self.default_ball_speed\n s1 = snell.speed\n return s0, s1\n\n def _interact_border(self, trajectory: TrajectoryBase) ->float:\n reward = 0.0\n edge = trajectory.intersected_edge\n if edge == self.top_edge or edge == self.bot_edge:\n self._reflect(Point(1, -1), trajectory)\n elif edge == self.left_edge:\n reward = self.score('we')\n elif edge == self.right_edge:\n reward = self.score('they')\n else:\n raise ValueError(f'invalid edge, {edge}')\n return reward\n\n def _reflect(self, direction: Point, trajectory: TrajectoryBase):\n \"\"\"\n Multiplies the velocity of the ball by `direction`, continues the path of the ball by calculating the remaining\n speed using trajectory and point.\n\n :param direction: velocity multiplier\n :param trajectory: The original trajectory of the ball\n \"\"\"\n self.ball.unit_velocity *= direction\n return self._finish_step_ball(trajectory)\n\n def _finish_step_ball(self, trajectory: TrajectoryBase):\n \"\"\"\n Finish the remainder of the trajectory after any interactions.\n\n :param trajectory: The original trajectory\n :return: reward\n \"\"\"\n point = trajectory.get_center_at_intersection()\n self.ball.pos = point + self.ball.unit_velocity * EPSILON\n return self._step_ball(trajectory.remaining_speed)\n\n def _get_first_intersection(self, trajectory: TrajectoryBase):\n \"\"\"\n Find the first point at which the trajectory interacted with an object.\n\n :param trajectory: the trajectory of the object\n :return: (shape object interacted with, point of interaction, line object interacted with)\n \"\"\"\n for trajectory_line in trajectory.corners:\n for o in self.sprites:\n if not isinstance(o, Ball):\n intersection_result = o.get_intersection(trajectory_line)\n if intersection_result is not None:\n edge, point = intersection_result\n if trajectory.intersection is None:\n trajectory.set_intersection(point,\n trajectory_line, o, edge)\n elif point == trajectory.intersection and trajectory_line == trajectory.intersected_trajectory:\n raise NotImplementedError(\n 'overlapping parallel edges not implemented')\n elif point.l2_distance(trajectory_line.start\n ) < trajectory.intersection.l2_distance(trajectory\n .intersected_trajectory.start):\n trajectory.set_intersection(point,\n trajectory_line, o, edge)\n\n def _get_ball_speed(self) ->float:\n if self.uniform_speed:\n return self.default_ball_speed\n elif self.ball.is_overlapping(self.snell):\n return self.snell.speed\n else:\n return self.default_ball_speed\n\n def _step_their_paddle(self):\n \"\"\"\n Move the opponents paddle. Override this in a subclass to change the behavior.\n \"\"\"\n if random.random() < self.their_update_probability:\n if self.paddle_l.y < self.ball.y:\n if self.paddle_l.top_bound < self.top_bound:\n self.paddle_l.up()\n elif self.paddle_l.bottom_bound > self.bottom_bound:\n self.paddle_l.down()\n", "step-2": "<mask token>\n\n\nclass TrajectoryRectangle(TrajectoryBase):\n <mask token>\n\n def __init__(self, shape: Rectangle, velocity: Point):\n super(TrajectoryRectangle, self).__init__(shape, velocity)\n assert isinstance(shape, Rectangle)\n self._reference = self.shape.pos\n\n @property\n def center(self) ->Line:\n \"\"\"\n Line representing the trajectory of the center of the rectangle\n \"\"\"\n return Line(self.shape.pos, self.shape.pos + self.velocity)\n\n @property\n def top_right(self) ->Line:\n \"\"\"\n Line representing the trajectory of the point on the top right corner of the rectangle\n \"\"\"\n start = Point(self.shape.right_bound, self.shape.top_bound)\n return Line(start, start + self.velocity)\n\n @property\n def top_left(self) ->Line:\n \"\"\"\n Line representing the trajectory of the point on the top left corner of the rectangle\n \"\"\"\n start = Point(self.shape.left_bound, self.shape.top_bound)\n return Line(start, start + self.velocity)\n\n @property\n def bottom_right(self) ->Line:\n \"\"\"\n Line representing the trajectory of the point on the bottom right corner of the rectangle\n \"\"\"\n start = Point(self.shape.right_bound, self.shape.bottom_bound)\n return Line(start, start + self.velocity)\n\n @property\n def bottom_left(self) ->Line:\n \"\"\"\n Line representing the trajectory of the point on the bottom left corner of the rectangle\n \"\"\"\n start = Point(self.shape.left_bound, self.shape.bottom_bound)\n return Line(start, start + self.velocity)\n\n\nclass TrajectoryLine(TrajectoryRectangle):\n \"\"\"\n Create a bounding box around the line and compute the trajectory as if it were a rectangle.\n \"\"\"\n\n def __init__(self, shape: Line, velocity: Point):\n super(TrajectoryLine, self).__init__(shape, velocity)\n assert isinstance(shape, Line)\n self._reference = self.shape.start\n height = abs(self.shape.start.y - self.shape.end.y)\n width = abs(self.shape.start.x - self.shape.end.x)\n center = Point((self.shape.start.x + self.shape.end.x) / 2, (self.\n shape.start.y + self.shape.end.y) / 2)\n self.shape = Rectangle(height=height, width=width)\n self.shape.pos = center\n\n\nclass TrajectoryPoint(TrajectoryBase):\n\n def __init__(self, shape: Point, velocity: Point):\n super(TrajectoryPoint, self).__init__(shape, velocity)\n assert isinstance(shape, Point)\n self._reference = self.shape\n\n @property\n def corners(self) ->Tuple[Line, ...]:\n return self._trajectory,\n\n @property\n def _trajectory(self) ->Line:\n return Line(self.shape, self.shape + self.velocity)\n\n @property\n def center(self) ->Line:\n return self._trajectory\n\n @property\n def top_right(self) ->Line:\n return self._trajectory\n\n @property\n def top_left(self) ->Line:\n return self._trajectory\n\n @property\n def bottom_right(self) ->Line:\n return self._trajectory\n\n @property\n def bottom_left(self) ->Line:\n return self._trajectory\n\n\nclass Trajectory(object):\n\n def __new__(cls, shape: Shape, velocity: Point):\n if isinstance(shape, Point):\n return TrajectoryPoint(shape, velocity)\n elif isinstance(shape, Line):\n return TrajectoryLine(shape, velocity)\n elif isinstance(shape, Rectangle):\n return TrajectoryRectangle(shape, velocity)\n else:\n raise NotImplementedError(\n f'No implementation of Trajectory for input shape of type {type(shape)}'\n )\n\n\nclass Canvas(Rectangle):\n action_meanings = {(0): 'NOOP', (1): 'UP', (2): 'DOWN'}\n actions = {k: v for v, k in action_meanings.items()}\n\n def __init__(self, paddle_l: Paddle, paddle_r: Paddle, ball: Ball,\n snell: Snell, ball_speed: int, height: int, width: int,\n their_update_probability: float, refract: bool, uniform_speed: bool):\n super().__init__(height=height, width=width, visibility='none',\n render_value=0)\n self.pos = self.width / 2, self.height / 2\n assert isinstance(their_update_probability, (float, int)\n ), f'their_update_probability must be numeric, not {type(their_update_probability)}'\n assert 0 <= their_update_probability <= 1, f'{their_update_probability} outside allowed bounds [0, 1]'\n self.their_update_probability = their_update_probability\n self.default_ball_speed = ball_speed\n self.snell = snell\n self.ball = ball\n self.paddle_l = paddle_l\n self.paddle_r = paddle_r\n self.sprites = [self, snell, paddle_l, paddle_r, ball]\n self.uniform_speed = uniform_speed\n self.refract = refract\n self.we_scored = False\n self.they_scored = False\n self.our_score = 0\n self.their_score = 0\n\n def register_sprite(self, sprite: Shape):\n assert issubclass(type(sprite), Shape\n ), f'sprite must be subclassed from Shape'\n self.sprites.insert(-1, sprite)\n\n @property\n def left_bound(self):\n return 0\n\n @property\n def right_bound(self):\n return self.width\n\n @property\n def top_bound(self):\n return self.height\n\n @property\n def bottom_bound(self):\n return 0\n\n def to_numpy(self) ->Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Performs masked rendering of objects in `self.sprites`. Priority is determined by the ordering of the list,\n earlier objects will be obscured by later ones.\n\n :return: (state, rendering)\n \"\"\"\n state = self._zero_rgb_image(round(self.height), round(self.width))\n rendering = self._zero_rgb_image(round(self.height), round(self.width))\n for sprite in self.sprites[1:]:\n sprite_state, sprite_rendering = sprite.to_numpy(self.height,\n self.width)\n state[sprite_state != 0] = sprite_state[sprite_state != 0]\n rendering[sprite_rendering != 0] = sprite_rendering[\n sprite_rendering != 0]\n return state, rendering\n\n def score(self, who):\n \"\"\"\n Increment the score and reset the ball\n\n :param who: 'we' or 'they'\n :return: reward\n \"\"\"\n if who == 'they':\n reward = -1\n self.their_score += 1\n elif who == 'we':\n reward = 1\n self.our_score += 1\n else:\n raise ValueError(f\"who must be 'we' or 'they', not {who}\")\n self._reset_ball()\n return reward\n\n def step(self, action):\n self._move_our_paddle(action)\n self._step_their_paddle()\n reward = self._step_ball()\n self._step_snell()\n return reward\n\n def get_state_size(self) ->Tuple[int, int]:\n \"\"\"\n Return the tuple (height, width) of the canvas dimensions\n \"\"\"\n return self.height, self.width\n\n def _step_snell(self) ->None:\n \"\"\"\n Step the snell layer\n \"\"\"\n self.snell.step()\n\n def _reset_ball(self):\n self.ball.reset((self.width / 2, self.height / 2))\n\n def _move_our_paddle(self, action) ->None:\n \"\"\"\n Move our paddle according to the provided action\n\n :param action: the action code\n \"\"\"\n if not isinstance(action, int):\n action = action.item()\n assert action in [a for a in self.action_meanings.keys()\n ], f'{action} is not a valid action'\n if action == self.actions['UP']:\n if self.paddle_r.top_bound < self.top_bound:\n self.paddle_r.up()\n elif action == self.actions['DOWN']:\n if self.paddle_r.bottom_bound > self.bottom_bound:\n self.paddle_r.down()\n\n def _step_ball(self, speed: Union[float, int]=None):\n \"\"\"\n Move the ball to the next position according to the speed of the layer it is in.\n\n :param speed: used to continue the trajectory of a ball that interacted with an object\n \"\"\"\n trajectory = self._get_trajectory(speed)\n self._get_first_intersection(trajectory)\n reward = 0\n if trajectory.intersection is None:\n self.ball.pos = trajectory.center.end\n else:\n reward = self._interaction_dispatcher(trajectory)\n return reward\n\n def _get_trajectory(self, speed) ->TrajectoryBase:\n \"\"\"\n Get the ball's trajectory\n\n :param speed: The speed of the starting medium\n :return: trajectory `Line`\n \"\"\"\n if speed is None:\n speed = self._get_ball_speed()\n if self.ball.has_volume:\n trajectory = Trajectory(self.ball, self.ball.get_velocity(speed))\n else:\n trajectory = Trajectory(self.ball.pos, self.ball.get_velocity(\n speed))\n return trajectory\n\n def _interaction_dispatcher(self, trajectory: TrajectoryBase):\n \"\"\"\n Dispatch data to the appropriate method based on the interaction `obj`.\n\n :param trajectory: the trajectory of the ball\n \"\"\"\n reward = 0\n obj = trajectory.intersected_object\n if obj is self:\n reward = self._interact_border(trajectory)\n elif isinstance(obj, Paddle):\n self._interact_paddle(trajectory)\n elif isinstance(obj, Snell):\n self._refract(trajectory)\n return reward\n\n def _interact_paddle(self, trajectory: TrajectoryBase) ->float:\n paddle = trajectory.intersected_object\n paddle_fraction = paddle.get_fraction_of_paddle(trajectory.\n get_center_at_intersection())\n angle = paddle_fraction * paddle.max_angle\n angle = math.pi - angle if self.ball.unit_velocity.x > 0 else angle\n self.ball.angle = angle\n reward = self._finish_step_ball(trajectory)\n return reward\n\n def _refract(self, trajectory: TrajectoryBase):\n edge = trajectory.intersected_edge\n if self.refract:\n s0, s1 = self._get_start_and_end_speed(trajectory)\n angle = edge.angle_to_normal(trajectory.center)\n if self._exceeds_critical_angle(angle, s0, s1):\n self._reflect(Point(-1, 1), trajectory)\n return\n new_angle = math.asin(s1 / s0 * math.sin(angle))\n boundary_angle, new_angle = (self.\n _adjust_refraction_to_boundary_angle(edge, new_angle))\n new_angle = self._adjust_refraction_to_direction_of_incidence(\n boundary_angle, new_angle, trajectory)\n self.ball.angle = new_angle\n return self._finish_step_ball(trajectory)\n\n @staticmethod\n def _exceeds_critical_angle(angle: float, s0: float, s1: float) ->bool:\n \"\"\"\n Test if the angle exceeds the critical angle\n\n :param angle: The angle to the normal of the boundary\n :param s0: The speed of the original medium\n :param s1: The speed of the next medium\n :return: True if the angle exceeds the critical angle\n \"\"\"\n if s1 > s0:\n critical_angle = get_critical_angle(s0, s1)\n if abs(angle) >= critical_angle:\n return True\n return False\n\n @staticmethod\n def _adjust_refraction_to_direction_of_incidence(boundary_angle: float,\n new_angle: float, trajectory: TrajectoryBase) ->float:\n \"\"\"\n If the direction of incidence was from the right of the boundary, reflect `new_angle`, otherwise, return\n `new_angle` without modification.\n\n :param boundary_angle: must be in the first or fourth quadrant\n :param new_angle: The angle to be reflected in the return\n :param trajectory: The angle of the incoming ball in global coordinates\n :return: The (possibly) reflected `new_angle`\n \"\"\"\n angle = trajectory.center.angle\n assert -math.pi / 2 <= boundary_angle <= math.pi / 2, 'boundary_angle should be in first or fourth quadrant'\n if boundary_angle >= 0 and boundary_angle < angle % (2 * math.pi\n ) < boundary_angle + math.pi:\n new_angle = math.pi - new_angle\n elif boundary_angle < 0 and boundary_angle % (2 * math.pi\n ) + math.pi < angle % (2 * math.pi) < boundary_angle % (2 * math.pi\n ):\n new_angle = math.pi - new_angle\n return new_angle\n\n @staticmethod\n def _adjust_refraction_to_boundary_angle(boundary: Line, new_angle: float\n ) ->Tuple[float, float]:\n \"\"\"\n Compute the rotation of `new_angle` back to global coordinates. Assume incidence from the left side of the\n boundary.\n\n :param boundary: The boundary `primitives.Line` object\n :param new_angle: The refracted angle normal to the boundary\n :return: The new angle in global coordinates\n \"\"\"\n boundary_angle = boundary.angle % (2 * math.pi)\n if 0 <= boundary_angle < math.pi / 2:\n boundary_angle = boundary_angle\n new_angle = boundary_angle - math.pi / 2 + new_angle\n elif math.pi / 2 <= boundary_angle < math.pi:\n boundary_angle = math.pi - boundary_angle\n new_angle = math.pi / 2 - boundary_angle + new_angle\n elif math.pi <= boundary_angle < 3 * math.pi / 2:\n boundary_angle = math.pi - boundary_angle\n new_angle = boundary_angle - math.pi / 2 + new_angle\n elif 2 * math.pi / 3 <= boundary_angle < 2 * math.pi:\n boundary_angle = 2 * math.pi - boundary_angle\n new_angle = math.pi / 2 - boundary_angle - new_angle\n else:\n raise ValueError(f'Unexpected angle {boundary_angle}')\n return boundary_angle, new_angle\n\n def _get_start_and_end_speed(self, trajectory: TrajectoryBase) ->Tuple[\n float, float]:\n \"\"\"\n Get the speed at the start of the trajectory and the speed at the end of the trajectory.\n\n :param trajectory: The trajectory `primitives.Line` object\n :return: (initial speed, final speed)\n \"\"\"\n snell = trajectory.intersected_object\n if snell.is_in(trajectory.center.start):\n s0 = snell.speed\n s1 = self.default_ball_speed\n else:\n s0 = self.default_ball_speed\n s1 = snell.speed\n return s0, s1\n\n def _interact_border(self, trajectory: TrajectoryBase) ->float:\n reward = 0.0\n edge = trajectory.intersected_edge\n if edge == self.top_edge or edge == self.bot_edge:\n self._reflect(Point(1, -1), trajectory)\n elif edge == self.left_edge:\n reward = self.score('we')\n elif edge == self.right_edge:\n reward = self.score('they')\n else:\n raise ValueError(f'invalid edge, {edge}')\n return reward\n\n def _reflect(self, direction: Point, trajectory: TrajectoryBase):\n \"\"\"\n Multiplies the velocity of the ball by `direction`, continues the path of the ball by calculating the remaining\n speed using trajectory and point.\n\n :param direction: velocity multiplier\n :param trajectory: The original trajectory of the ball\n \"\"\"\n self.ball.unit_velocity *= direction\n return self._finish_step_ball(trajectory)\n\n def _finish_step_ball(self, trajectory: TrajectoryBase):\n \"\"\"\n Finish the remainder of the trajectory after any interactions.\n\n :param trajectory: The original trajectory\n :return: reward\n \"\"\"\n point = trajectory.get_center_at_intersection()\n self.ball.pos = point + self.ball.unit_velocity * EPSILON\n return self._step_ball(trajectory.remaining_speed)\n\n def _get_first_intersection(self, trajectory: TrajectoryBase):\n \"\"\"\n Find the first point at which the trajectory interacted with an object.\n\n :param trajectory: the trajectory of the object\n :return: (shape object interacted with, point of interaction, line object interacted with)\n \"\"\"\n for trajectory_line in trajectory.corners:\n for o in self.sprites:\n if not isinstance(o, Ball):\n intersection_result = o.get_intersection(trajectory_line)\n if intersection_result is not None:\n edge, point = intersection_result\n if trajectory.intersection is None:\n trajectory.set_intersection(point,\n trajectory_line, o, edge)\n elif point == trajectory.intersection and trajectory_line == trajectory.intersected_trajectory:\n raise NotImplementedError(\n 'overlapping parallel edges not implemented')\n elif point.l2_distance(trajectory_line.start\n ) < trajectory.intersection.l2_distance(trajectory\n .intersected_trajectory.start):\n trajectory.set_intersection(point,\n trajectory_line, o, edge)\n\n def _get_ball_speed(self) ->float:\n if self.uniform_speed:\n return self.default_ball_speed\n elif self.ball.is_overlapping(self.snell):\n return self.snell.speed\n else:\n return self.default_ball_speed\n\n def _step_their_paddle(self):\n \"\"\"\n Move the opponents paddle. Override this in a subclass to change the behavior.\n \"\"\"\n if random.random() < self.their_update_probability:\n if self.paddle_l.y < self.ball.y:\n if self.paddle_l.top_bound < self.top_bound:\n self.paddle_l.up()\n elif self.paddle_l.bottom_bound > self.bottom_bound:\n self.paddle_l.down()\n", "step-3": "<mask token>\n\n\nclass Paddle(Rectangle):\n <mask token>\n\n def up(self):\n self.y += self.speed\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Ball(Rectangle):\n\n def __init__(self, size: float, max_initial_angle: float, visibility:\n str, has_volume: bool=False):\n \"\"\"\n Ball object\n\n :param has_volume:\n :param size: The size to render the ball\n :param max_initial_angle: The maximum angle the ball can start with\n :param visibility: How to render the ball. See `Shape.visibility`\n :param has_volume: determines whether the ball interacts as a point or as an area\n \"\"\"\n super().__init__(width=size, height=size, visibility=visibility,\n render_value=255)\n self.max_initial_angle = max_initial_angle\n self.reset(self.pos, direction='left')\n self.has_volume = has_volume\n\n def reset(self, position: Union[Tuple[float, float], Point], direction:\n str='right'):\n if direction == 'right':\n self._angle = (2 * random.random() - 1) * self.max_initial_angle\n elif direction == 'left':\n self._angle = math.pi - (2 * random.random() - 1\n ) * self.max_initial_angle\n else:\n raise ValueError(\n f\"direction must be 'left' or 'right', not {direction}\")\n self.pos = position\n\n @property\n def angle(self):\n \"\"\"\n Angle with respect to the right horizontal\n \"\"\"\n return self._angle\n\n @angle.setter\n def angle(self, value):\n self._angle = value % (2 * math.pi)\n\n @property\n def unit_velocity(self) ->Point:\n x = math.cos(self.angle)\n y = math.sin(self.angle)\n return Point(x, y)\n\n @unit_velocity.setter\n def unit_velocity(self, value: Union[Tuple[float, float], Point]):\n \"\"\"\n Sets the angle parameter give a set of (x, y) coordinates.\n\n :param value: (x, y)\n \"\"\"\n if isinstance(value, tuple):\n value = Point(*value)\n assert isinstance(value, Point\n ), f'value must be a point, not {type(value)}'\n self.angle = value.angle\n\n def get_velocity(self, speed: Union[float, int]):\n return self.unit_velocity * speed\n\n\nclass Snell(Rectangle):\n\n def __init__(self, width, height, speed, change_rate, visibility):\n \"\"\"\n Rectangular area with a different ball speed.\n\n :param width: The width of the layer\n :param height: The height of the layer\n :param change_rate: Rate at which the ball speed changes, the standard deviation of the change on each step.\n :param visibility: Whether and how to render the layer. See `Shape.visibility`\n \"\"\"\n assert change_rate >= 0, 'Snell `change_rate` must be non-negative'\n super().__init__(width=width, height=height, visibility=visibility,\n render_value=(235, 76, 52))\n self.speed = speed\n self._initial_speed = speed\n self.change_rate = change_rate\n\n def step(self):\n \"\"\"\n Step the Snell speed using a bounded Gaussian random walk.\n\n - step with mean 0, standard deviation `self.speed`\n - Clip the speed at `0.5 * self._initial_speed <= self.speed <= 2.0 * self._initial_speed`\n \"\"\"\n if self.change_rate != 0:\n self.speed += stats.norm(loc=0, scale=self.change_rate).rvs()\n if self.speed < 0.5 * self._initial_speed:\n self.speed = 0.5 * self._initial_speed\n if self.speed > 2.0 * self._initial_speed:\n self.speed = 2.0 * self._initial_speed\n else:\n pass\n\n\nclass TrajectoryBase(abc.ABC):\n\n def __init__(self, shape: Union[Point, Line, Rectangle], velocity: Point):\n self.shape = shape\n self.velocity = velocity\n self._reference = None\n self.intersection = None\n self.intersected_trajectory = None\n self.intersected_object = None\n self.intersected_edge = None\n self.remaining_speed = None\n\n def set_intersection(self, point: Point, trajectory_line: Line, obj:\n Shape, edge: Line):\n assert isinstance(obj, Shape), f'type Shape expected, not {type(obj)}'\n assert isinstance(point, Point\n ), f'type Point expected, not {type(point)}'\n assert isinstance(edge, Line), f'type Line expected, not {type(edge)}'\n self.intersection = point\n self.intersected_trajectory = trajectory_line\n self.remaining_speed = point.l2_distance(trajectory_line.end)\n self.intersected_object = obj\n self.intersected_edge = edge\n\n def get_center_at_intersection(self) ->Point:\n \"\"\"\n Get the new center of `self.shape` given that it moved along `intersected_trajectory` to `intersection`\n\n :return: new center point\n \"\"\"\n return self._reference + (self.intersection - self.\n intersected_trajectory.start)\n\n @property\n def corners(self) ->Tuple[Line, ...]:\n return (self.top_left, self.top_right, self.bottom_right, self.\n bottom_left)\n\n @property\n @abc.abstractmethod\n def center(self) ->Line:\n ...\n\n @property\n @abc.abstractmethod\n def top_right(self) ->Line:\n ...\n\n @property\n @abc.abstractmethod\n def top_left(self) ->Line:\n ...\n\n @property\n @abc.abstractmethod\n def bottom_right(self) ->Line:\n ...\n\n @property\n @abc.abstractmethod\n def bottom_left(self) ->Line:\n ...\n\n\nclass TrajectoryRectangle(TrajectoryBase):\n \"\"\"\n Compute the trajectory of each corner of the rectangle\n \"\"\"\n\n def __init__(self, shape: Rectangle, velocity: Point):\n super(TrajectoryRectangle, self).__init__(shape, velocity)\n assert isinstance(shape, Rectangle)\n self._reference = self.shape.pos\n\n @property\n def center(self) ->Line:\n \"\"\"\n Line representing the trajectory of the center of the rectangle\n \"\"\"\n return Line(self.shape.pos, self.shape.pos + self.velocity)\n\n @property\n def top_right(self) ->Line:\n \"\"\"\n Line representing the trajectory of the point on the top right corner of the rectangle\n \"\"\"\n start = Point(self.shape.right_bound, self.shape.top_bound)\n return Line(start, start + self.velocity)\n\n @property\n def top_left(self) ->Line:\n \"\"\"\n Line representing the trajectory of the point on the top left corner of the rectangle\n \"\"\"\n start = Point(self.shape.left_bound, self.shape.top_bound)\n return Line(start, start + self.velocity)\n\n @property\n def bottom_right(self) ->Line:\n \"\"\"\n Line representing the trajectory of the point on the bottom right corner of the rectangle\n \"\"\"\n start = Point(self.shape.right_bound, self.shape.bottom_bound)\n return Line(start, start + self.velocity)\n\n @property\n def bottom_left(self) ->Line:\n \"\"\"\n Line representing the trajectory of the point on the bottom left corner of the rectangle\n \"\"\"\n start = Point(self.shape.left_bound, self.shape.bottom_bound)\n return Line(start, start + self.velocity)\n\n\nclass TrajectoryLine(TrajectoryRectangle):\n \"\"\"\n Create a bounding box around the line and compute the trajectory as if it were a rectangle.\n \"\"\"\n\n def __init__(self, shape: Line, velocity: Point):\n super(TrajectoryLine, self).__init__(shape, velocity)\n assert isinstance(shape, Line)\n self._reference = self.shape.start\n height = abs(self.shape.start.y - self.shape.end.y)\n width = abs(self.shape.start.x - self.shape.end.x)\n center = Point((self.shape.start.x + self.shape.end.x) / 2, (self.\n shape.start.y + self.shape.end.y) / 2)\n self.shape = Rectangle(height=height, width=width)\n self.shape.pos = center\n\n\nclass TrajectoryPoint(TrajectoryBase):\n\n def __init__(self, shape: Point, velocity: Point):\n super(TrajectoryPoint, self).__init__(shape, velocity)\n assert isinstance(shape, Point)\n self._reference = self.shape\n\n @property\n def corners(self) ->Tuple[Line, ...]:\n return self._trajectory,\n\n @property\n def _trajectory(self) ->Line:\n return Line(self.shape, self.shape + self.velocity)\n\n @property\n def center(self) ->Line:\n return self._trajectory\n\n @property\n def top_right(self) ->Line:\n return self._trajectory\n\n @property\n def top_left(self) ->Line:\n return self._trajectory\n\n @property\n def bottom_right(self) ->Line:\n return self._trajectory\n\n @property\n def bottom_left(self) ->Line:\n return self._trajectory\n\n\nclass Trajectory(object):\n\n def __new__(cls, shape: Shape, velocity: Point):\n if isinstance(shape, Point):\n return TrajectoryPoint(shape, velocity)\n elif isinstance(shape, Line):\n return TrajectoryLine(shape, velocity)\n elif isinstance(shape, Rectangle):\n return TrajectoryRectangle(shape, velocity)\n else:\n raise NotImplementedError(\n f'No implementation of Trajectory for input shape of type {type(shape)}'\n )\n\n\nclass Canvas(Rectangle):\n action_meanings = {(0): 'NOOP', (1): 'UP', (2): 'DOWN'}\n actions = {k: v for v, k in action_meanings.items()}\n\n def __init__(self, paddle_l: Paddle, paddle_r: Paddle, ball: Ball,\n snell: Snell, ball_speed: int, height: int, width: int,\n their_update_probability: float, refract: bool, uniform_speed: bool):\n super().__init__(height=height, width=width, visibility='none',\n render_value=0)\n self.pos = self.width / 2, self.height / 2\n assert isinstance(their_update_probability, (float, int)\n ), f'their_update_probability must be numeric, not {type(their_update_probability)}'\n assert 0 <= their_update_probability <= 1, f'{their_update_probability} outside allowed bounds [0, 1]'\n self.their_update_probability = their_update_probability\n self.default_ball_speed = ball_speed\n self.snell = snell\n self.ball = ball\n self.paddle_l = paddle_l\n self.paddle_r = paddle_r\n self.sprites = [self, snell, paddle_l, paddle_r, ball]\n self.uniform_speed = uniform_speed\n self.refract = refract\n self.we_scored = False\n self.they_scored = False\n self.our_score = 0\n self.their_score = 0\n\n def register_sprite(self, sprite: Shape):\n assert issubclass(type(sprite), Shape\n ), f'sprite must be subclassed from Shape'\n self.sprites.insert(-1, sprite)\n\n @property\n def left_bound(self):\n return 0\n\n @property\n def right_bound(self):\n return self.width\n\n @property\n def top_bound(self):\n return self.height\n\n @property\n def bottom_bound(self):\n return 0\n\n def to_numpy(self) ->Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Performs masked rendering of objects in `self.sprites`. Priority is determined by the ordering of the list,\n earlier objects will be obscured by later ones.\n\n :return: (state, rendering)\n \"\"\"\n state = self._zero_rgb_image(round(self.height), round(self.width))\n rendering = self._zero_rgb_image(round(self.height), round(self.width))\n for sprite in self.sprites[1:]:\n sprite_state, sprite_rendering = sprite.to_numpy(self.height,\n self.width)\n state[sprite_state != 0] = sprite_state[sprite_state != 0]\n rendering[sprite_rendering != 0] = sprite_rendering[\n sprite_rendering != 0]\n return state, rendering\n\n def score(self, who):\n \"\"\"\n Increment the score and reset the ball\n\n :param who: 'we' or 'they'\n :return: reward\n \"\"\"\n if who == 'they':\n reward = -1\n self.their_score += 1\n elif who == 'we':\n reward = 1\n self.our_score += 1\n else:\n raise ValueError(f\"who must be 'we' or 'they', not {who}\")\n self._reset_ball()\n return reward\n\n def step(self, action):\n self._move_our_paddle(action)\n self._step_their_paddle()\n reward = self._step_ball()\n self._step_snell()\n return reward\n\n def get_state_size(self) ->Tuple[int, int]:\n \"\"\"\n Return the tuple (height, width) of the canvas dimensions\n \"\"\"\n return self.height, self.width\n\n def _step_snell(self) ->None:\n \"\"\"\n Step the snell layer\n \"\"\"\n self.snell.step()\n\n def _reset_ball(self):\n self.ball.reset((self.width / 2, self.height / 2))\n\n def _move_our_paddle(self, action) ->None:\n \"\"\"\n Move our paddle according to the provided action\n\n :param action: the action code\n \"\"\"\n if not isinstance(action, int):\n action = action.item()\n assert action in [a for a in self.action_meanings.keys()\n ], f'{action} is not a valid action'\n if action == self.actions['UP']:\n if self.paddle_r.top_bound < self.top_bound:\n self.paddle_r.up()\n elif action == self.actions['DOWN']:\n if self.paddle_r.bottom_bound > self.bottom_bound:\n self.paddle_r.down()\n\n def _step_ball(self, speed: Union[float, int]=None):\n \"\"\"\n Move the ball to the next position according to the speed of the layer it is in.\n\n :param speed: used to continue the trajectory of a ball that interacted with an object\n \"\"\"\n trajectory = self._get_trajectory(speed)\n self._get_first_intersection(trajectory)\n reward = 0\n if trajectory.intersection is None:\n self.ball.pos = trajectory.center.end\n else:\n reward = self._interaction_dispatcher(trajectory)\n return reward\n\n def _get_trajectory(self, speed) ->TrajectoryBase:\n \"\"\"\n Get the ball's trajectory\n\n :param speed: The speed of the starting medium\n :return: trajectory `Line`\n \"\"\"\n if speed is None:\n speed = self._get_ball_speed()\n if self.ball.has_volume:\n trajectory = Trajectory(self.ball, self.ball.get_velocity(speed))\n else:\n trajectory = Trajectory(self.ball.pos, self.ball.get_velocity(\n speed))\n return trajectory\n\n def _interaction_dispatcher(self, trajectory: TrajectoryBase):\n \"\"\"\n Dispatch data to the appropriate method based on the interaction `obj`.\n\n :param trajectory: the trajectory of the ball\n \"\"\"\n reward = 0\n obj = trajectory.intersected_object\n if obj is self:\n reward = self._interact_border(trajectory)\n elif isinstance(obj, Paddle):\n self._interact_paddle(trajectory)\n elif isinstance(obj, Snell):\n self._refract(trajectory)\n return reward\n\n def _interact_paddle(self, trajectory: TrajectoryBase) ->float:\n paddle = trajectory.intersected_object\n paddle_fraction = paddle.get_fraction_of_paddle(trajectory.\n get_center_at_intersection())\n angle = paddle_fraction * paddle.max_angle\n angle = math.pi - angle if self.ball.unit_velocity.x > 0 else angle\n self.ball.angle = angle\n reward = self._finish_step_ball(trajectory)\n return reward\n\n def _refract(self, trajectory: TrajectoryBase):\n edge = trajectory.intersected_edge\n if self.refract:\n s0, s1 = self._get_start_and_end_speed(trajectory)\n angle = edge.angle_to_normal(trajectory.center)\n if self._exceeds_critical_angle(angle, s0, s1):\n self._reflect(Point(-1, 1), trajectory)\n return\n new_angle = math.asin(s1 / s0 * math.sin(angle))\n boundary_angle, new_angle = (self.\n _adjust_refraction_to_boundary_angle(edge, new_angle))\n new_angle = self._adjust_refraction_to_direction_of_incidence(\n boundary_angle, new_angle, trajectory)\n self.ball.angle = new_angle\n return self._finish_step_ball(trajectory)\n\n @staticmethod\n def _exceeds_critical_angle(angle: float, s0: float, s1: float) ->bool:\n \"\"\"\n Test if the angle exceeds the critical angle\n\n :param angle: The angle to the normal of the boundary\n :param s0: The speed of the original medium\n :param s1: The speed of the next medium\n :return: True if the angle exceeds the critical angle\n \"\"\"\n if s1 > s0:\n critical_angle = get_critical_angle(s0, s1)\n if abs(angle) >= critical_angle:\n return True\n return False\n\n @staticmethod\n def _adjust_refraction_to_direction_of_incidence(boundary_angle: float,\n new_angle: float, trajectory: TrajectoryBase) ->float:\n \"\"\"\n If the direction of incidence was from the right of the boundary, reflect `new_angle`, otherwise, return\n `new_angle` without modification.\n\n :param boundary_angle: must be in the first or fourth quadrant\n :param new_angle: The angle to be reflected in the return\n :param trajectory: The angle of the incoming ball in global coordinates\n :return: The (possibly) reflected `new_angle`\n \"\"\"\n angle = trajectory.center.angle\n assert -math.pi / 2 <= boundary_angle <= math.pi / 2, 'boundary_angle should be in first or fourth quadrant'\n if boundary_angle >= 0 and boundary_angle < angle % (2 * math.pi\n ) < boundary_angle + math.pi:\n new_angle = math.pi - new_angle\n elif boundary_angle < 0 and boundary_angle % (2 * math.pi\n ) + math.pi < angle % (2 * math.pi) < boundary_angle % (2 * math.pi\n ):\n new_angle = math.pi - new_angle\n return new_angle\n\n @staticmethod\n def _adjust_refraction_to_boundary_angle(boundary: Line, new_angle: float\n ) ->Tuple[float, float]:\n \"\"\"\n Compute the rotation of `new_angle` back to global coordinates. Assume incidence from the left side of the\n boundary.\n\n :param boundary: The boundary `primitives.Line` object\n :param new_angle: The refracted angle normal to the boundary\n :return: The new angle in global coordinates\n \"\"\"\n boundary_angle = boundary.angle % (2 * math.pi)\n if 0 <= boundary_angle < math.pi / 2:\n boundary_angle = boundary_angle\n new_angle = boundary_angle - math.pi / 2 + new_angle\n elif math.pi / 2 <= boundary_angle < math.pi:\n boundary_angle = math.pi - boundary_angle\n new_angle = math.pi / 2 - boundary_angle + new_angle\n elif math.pi <= boundary_angle < 3 * math.pi / 2:\n boundary_angle = math.pi - boundary_angle\n new_angle = boundary_angle - math.pi / 2 + new_angle\n elif 2 * math.pi / 3 <= boundary_angle < 2 * math.pi:\n boundary_angle = 2 * math.pi - boundary_angle\n new_angle = math.pi / 2 - boundary_angle - new_angle\n else:\n raise ValueError(f'Unexpected angle {boundary_angle}')\n return boundary_angle, new_angle\n\n def _get_start_and_end_speed(self, trajectory: TrajectoryBase) ->Tuple[\n float, float]:\n \"\"\"\n Get the speed at the start of the trajectory and the speed at the end of the trajectory.\n\n :param trajectory: The trajectory `primitives.Line` object\n :return: (initial speed, final speed)\n \"\"\"\n snell = trajectory.intersected_object\n if snell.is_in(trajectory.center.start):\n s0 = snell.speed\n s1 = self.default_ball_speed\n else:\n s0 = self.default_ball_speed\n s1 = snell.speed\n return s0, s1\n\n def _interact_border(self, trajectory: TrajectoryBase) ->float:\n reward = 0.0\n edge = trajectory.intersected_edge\n if edge == self.top_edge or edge == self.bot_edge:\n self._reflect(Point(1, -1), trajectory)\n elif edge == self.left_edge:\n reward = self.score('we')\n elif edge == self.right_edge:\n reward = self.score('they')\n else:\n raise ValueError(f'invalid edge, {edge}')\n return reward\n\n def _reflect(self, direction: Point, trajectory: TrajectoryBase):\n \"\"\"\n Multiplies the velocity of the ball by `direction`, continues the path of the ball by calculating the remaining\n speed using trajectory and point.\n\n :param direction: velocity multiplier\n :param trajectory: The original trajectory of the ball\n \"\"\"\n self.ball.unit_velocity *= direction\n return self._finish_step_ball(trajectory)\n\n def _finish_step_ball(self, trajectory: TrajectoryBase):\n \"\"\"\n Finish the remainder of the trajectory after any interactions.\n\n :param trajectory: The original trajectory\n :return: reward\n \"\"\"\n point = trajectory.get_center_at_intersection()\n self.ball.pos = point + self.ball.unit_velocity * EPSILON\n return self._step_ball(trajectory.remaining_speed)\n\n def _get_first_intersection(self, trajectory: TrajectoryBase):\n \"\"\"\n Find the first point at which the trajectory interacted with an object.\n\n :param trajectory: the trajectory of the object\n :return: (shape object interacted with, point of interaction, line object interacted with)\n \"\"\"\n for trajectory_line in trajectory.corners:\n for o in self.sprites:\n if not isinstance(o, Ball):\n intersection_result = o.get_intersection(trajectory_line)\n if intersection_result is not None:\n edge, point = intersection_result\n if trajectory.intersection is None:\n trajectory.set_intersection(point,\n trajectory_line, o, edge)\n elif point == trajectory.intersection and trajectory_line == trajectory.intersected_trajectory:\n raise NotImplementedError(\n 'overlapping parallel edges not implemented')\n elif point.l2_distance(trajectory_line.start\n ) < trajectory.intersection.l2_distance(trajectory\n .intersected_trajectory.start):\n trajectory.set_intersection(point,\n trajectory_line, o, edge)\n\n def _get_ball_speed(self) ->float:\n if self.uniform_speed:\n return self.default_ball_speed\n elif self.ball.is_overlapping(self.snell):\n return self.snell.speed\n else:\n return self.default_ball_speed\n\n def _step_their_paddle(self):\n \"\"\"\n Move the opponents paddle. Override this in a subclass to change the behavior.\n \"\"\"\n if random.random() < self.their_update_probability:\n if self.paddle_l.y < self.ball.y:\n if self.paddle_l.top_bound < self.top_bound:\n self.paddle_l.up()\n elif self.paddle_l.bottom_bound > self.bottom_bound:\n self.paddle_l.down()\n", "step-4": "<mask token>\n\n\nclass Paddle(Rectangle):\n <mask token>\n\n def up(self):\n self.y += self.speed\n <mask token>\n\n def _get_edges(self) ->Tuple[Line]:\n \"\"\"\n Only return the field-side edge\n \"\"\"\n if self.side == 'right':\n return Line((self.left_bound, self.bottom_bound), (self.\n left_bound, self.top_bound)),\n elif self.side == 'left':\n return Line((self.right_bound, self.bottom_bound), (self.\n right_bound, self.top_bound)),\n <mask token>\n\n\nclass Ball(Rectangle):\n\n def __init__(self, size: float, max_initial_angle: float, visibility:\n str, has_volume: bool=False):\n \"\"\"\n Ball object\n\n :param has_volume:\n :param size: The size to render the ball\n :param max_initial_angle: The maximum angle the ball can start with\n :param visibility: How to render the ball. See `Shape.visibility`\n :param has_volume: determines whether the ball interacts as a point or as an area\n \"\"\"\n super().__init__(width=size, height=size, visibility=visibility,\n render_value=255)\n self.max_initial_angle = max_initial_angle\n self.reset(self.pos, direction='left')\n self.has_volume = has_volume\n\n def reset(self, position: Union[Tuple[float, float], Point], direction:\n str='right'):\n if direction == 'right':\n self._angle = (2 * random.random() - 1) * self.max_initial_angle\n elif direction == 'left':\n self._angle = math.pi - (2 * random.random() - 1\n ) * self.max_initial_angle\n else:\n raise ValueError(\n f\"direction must be 'left' or 'right', not {direction}\")\n self.pos = position\n\n @property\n def angle(self):\n \"\"\"\n Angle with respect to the right horizontal\n \"\"\"\n return self._angle\n\n @angle.setter\n def angle(self, value):\n self._angle = value % (2 * math.pi)\n\n @property\n def unit_velocity(self) ->Point:\n x = math.cos(self.angle)\n y = math.sin(self.angle)\n return Point(x, y)\n\n @unit_velocity.setter\n def unit_velocity(self, value: Union[Tuple[float, float], Point]):\n \"\"\"\n Sets the angle parameter give a set of (x, y) coordinates.\n\n :param value: (x, y)\n \"\"\"\n if isinstance(value, tuple):\n value = Point(*value)\n assert isinstance(value, Point\n ), f'value must be a point, not {type(value)}'\n self.angle = value.angle\n\n def get_velocity(self, speed: Union[float, int]):\n return self.unit_velocity * speed\n\n\nclass Snell(Rectangle):\n\n def __init__(self, width, height, speed, change_rate, visibility):\n \"\"\"\n Rectangular area with a different ball speed.\n\n :param width: The width of the layer\n :param height: The height of the layer\n :param change_rate: Rate at which the ball speed changes, the standard deviation of the change on each step.\n :param visibility: Whether and how to render the layer. See `Shape.visibility`\n \"\"\"\n assert change_rate >= 0, 'Snell `change_rate` must be non-negative'\n super().__init__(width=width, height=height, visibility=visibility,\n render_value=(235, 76, 52))\n self.speed = speed\n self._initial_speed = speed\n self.change_rate = change_rate\n\n def step(self):\n \"\"\"\n Step the Snell speed using a bounded Gaussian random walk.\n\n - step with mean 0, standard deviation `self.speed`\n - Clip the speed at `0.5 * self._initial_speed <= self.speed <= 2.0 * self._initial_speed`\n \"\"\"\n if self.change_rate != 0:\n self.speed += stats.norm(loc=0, scale=self.change_rate).rvs()\n if self.speed < 0.5 * self._initial_speed:\n self.speed = 0.5 * self._initial_speed\n if self.speed > 2.0 * self._initial_speed:\n self.speed = 2.0 * self._initial_speed\n else:\n pass\n\n\nclass TrajectoryBase(abc.ABC):\n\n def __init__(self, shape: Union[Point, Line, Rectangle], velocity: Point):\n self.shape = shape\n self.velocity = velocity\n self._reference = None\n self.intersection = None\n self.intersected_trajectory = None\n self.intersected_object = None\n self.intersected_edge = None\n self.remaining_speed = None\n\n def set_intersection(self, point: Point, trajectory_line: Line, obj:\n Shape, edge: Line):\n assert isinstance(obj, Shape), f'type Shape expected, not {type(obj)}'\n assert isinstance(point, Point\n ), f'type Point expected, not {type(point)}'\n assert isinstance(edge, Line), f'type Line expected, not {type(edge)}'\n self.intersection = point\n self.intersected_trajectory = trajectory_line\n self.remaining_speed = point.l2_distance(trajectory_line.end)\n self.intersected_object = obj\n self.intersected_edge = edge\n\n def get_center_at_intersection(self) ->Point:\n \"\"\"\n Get the new center of `self.shape` given that it moved along `intersected_trajectory` to `intersection`\n\n :return: new center point\n \"\"\"\n return self._reference + (self.intersection - self.\n intersected_trajectory.start)\n\n @property\n def corners(self) ->Tuple[Line, ...]:\n return (self.top_left, self.top_right, self.bottom_right, self.\n bottom_left)\n\n @property\n @abc.abstractmethod\n def center(self) ->Line:\n ...\n\n @property\n @abc.abstractmethod\n def top_right(self) ->Line:\n ...\n\n @property\n @abc.abstractmethod\n def top_left(self) ->Line:\n ...\n\n @property\n @abc.abstractmethod\n def bottom_right(self) ->Line:\n ...\n\n @property\n @abc.abstractmethod\n def bottom_left(self) ->Line:\n ...\n\n\nclass TrajectoryRectangle(TrajectoryBase):\n \"\"\"\n Compute the trajectory of each corner of the rectangle\n \"\"\"\n\n def __init__(self, shape: Rectangle, velocity: Point):\n super(TrajectoryRectangle, self).__init__(shape, velocity)\n assert isinstance(shape, Rectangle)\n self._reference = self.shape.pos\n\n @property\n def center(self) ->Line:\n \"\"\"\n Line representing the trajectory of the center of the rectangle\n \"\"\"\n return Line(self.shape.pos, self.shape.pos + self.velocity)\n\n @property\n def top_right(self) ->Line:\n \"\"\"\n Line representing the trajectory of the point on the top right corner of the rectangle\n \"\"\"\n start = Point(self.shape.right_bound, self.shape.top_bound)\n return Line(start, start + self.velocity)\n\n @property\n def top_left(self) ->Line:\n \"\"\"\n Line representing the trajectory of the point on the top left corner of the rectangle\n \"\"\"\n start = Point(self.shape.left_bound, self.shape.top_bound)\n return Line(start, start + self.velocity)\n\n @property\n def bottom_right(self) ->Line:\n \"\"\"\n Line representing the trajectory of the point on the bottom right corner of the rectangle\n \"\"\"\n start = Point(self.shape.right_bound, self.shape.bottom_bound)\n return Line(start, start + self.velocity)\n\n @property\n def bottom_left(self) ->Line:\n \"\"\"\n Line representing the trajectory of the point on the bottom left corner of the rectangle\n \"\"\"\n start = Point(self.shape.left_bound, self.shape.bottom_bound)\n return Line(start, start + self.velocity)\n\n\nclass TrajectoryLine(TrajectoryRectangle):\n \"\"\"\n Create a bounding box around the line and compute the trajectory as if it were a rectangle.\n \"\"\"\n\n def __init__(self, shape: Line, velocity: Point):\n super(TrajectoryLine, self).__init__(shape, velocity)\n assert isinstance(shape, Line)\n self._reference = self.shape.start\n height = abs(self.shape.start.y - self.shape.end.y)\n width = abs(self.shape.start.x - self.shape.end.x)\n center = Point((self.shape.start.x + self.shape.end.x) / 2, (self.\n shape.start.y + self.shape.end.y) / 2)\n self.shape = Rectangle(height=height, width=width)\n self.shape.pos = center\n\n\nclass TrajectoryPoint(TrajectoryBase):\n\n def __init__(self, shape: Point, velocity: Point):\n super(TrajectoryPoint, self).__init__(shape, velocity)\n assert isinstance(shape, Point)\n self._reference = self.shape\n\n @property\n def corners(self) ->Tuple[Line, ...]:\n return self._trajectory,\n\n @property\n def _trajectory(self) ->Line:\n return Line(self.shape, self.shape + self.velocity)\n\n @property\n def center(self) ->Line:\n return self._trajectory\n\n @property\n def top_right(self) ->Line:\n return self._trajectory\n\n @property\n def top_left(self) ->Line:\n return self._trajectory\n\n @property\n def bottom_right(self) ->Line:\n return self._trajectory\n\n @property\n def bottom_left(self) ->Line:\n return self._trajectory\n\n\nclass Trajectory(object):\n\n def __new__(cls, shape: Shape, velocity: Point):\n if isinstance(shape, Point):\n return TrajectoryPoint(shape, velocity)\n elif isinstance(shape, Line):\n return TrajectoryLine(shape, velocity)\n elif isinstance(shape, Rectangle):\n return TrajectoryRectangle(shape, velocity)\n else:\n raise NotImplementedError(\n f'No implementation of Trajectory for input shape of type {type(shape)}'\n )\n\n\nclass Canvas(Rectangle):\n action_meanings = {(0): 'NOOP', (1): 'UP', (2): 'DOWN'}\n actions = {k: v for v, k in action_meanings.items()}\n\n def __init__(self, paddle_l: Paddle, paddle_r: Paddle, ball: Ball,\n snell: Snell, ball_speed: int, height: int, width: int,\n their_update_probability: float, refract: bool, uniform_speed: bool):\n super().__init__(height=height, width=width, visibility='none',\n render_value=0)\n self.pos = self.width / 2, self.height / 2\n assert isinstance(their_update_probability, (float, int)\n ), f'their_update_probability must be numeric, not {type(their_update_probability)}'\n assert 0 <= their_update_probability <= 1, f'{their_update_probability} outside allowed bounds [0, 1]'\n self.their_update_probability = their_update_probability\n self.default_ball_speed = ball_speed\n self.snell = snell\n self.ball = ball\n self.paddle_l = paddle_l\n self.paddle_r = paddle_r\n self.sprites = [self, snell, paddle_l, paddle_r, ball]\n self.uniform_speed = uniform_speed\n self.refract = refract\n self.we_scored = False\n self.they_scored = False\n self.our_score = 0\n self.their_score = 0\n\n def register_sprite(self, sprite: Shape):\n assert issubclass(type(sprite), Shape\n ), f'sprite must be subclassed from Shape'\n self.sprites.insert(-1, sprite)\n\n @property\n def left_bound(self):\n return 0\n\n @property\n def right_bound(self):\n return self.width\n\n @property\n def top_bound(self):\n return self.height\n\n @property\n def bottom_bound(self):\n return 0\n\n def to_numpy(self) ->Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Performs masked rendering of objects in `self.sprites`. Priority is determined by the ordering of the list,\n earlier objects will be obscured by later ones.\n\n :return: (state, rendering)\n \"\"\"\n state = self._zero_rgb_image(round(self.height), round(self.width))\n rendering = self._zero_rgb_image(round(self.height), round(self.width))\n for sprite in self.sprites[1:]:\n sprite_state, sprite_rendering = sprite.to_numpy(self.height,\n self.width)\n state[sprite_state != 0] = sprite_state[sprite_state != 0]\n rendering[sprite_rendering != 0] = sprite_rendering[\n sprite_rendering != 0]\n return state, rendering\n\n def score(self, who):\n \"\"\"\n Increment the score and reset the ball\n\n :param who: 'we' or 'they'\n :return: reward\n \"\"\"\n if who == 'they':\n reward = -1\n self.their_score += 1\n elif who == 'we':\n reward = 1\n self.our_score += 1\n else:\n raise ValueError(f\"who must be 'we' or 'they', not {who}\")\n self._reset_ball()\n return reward\n\n def step(self, action):\n self._move_our_paddle(action)\n self._step_their_paddle()\n reward = self._step_ball()\n self._step_snell()\n return reward\n\n def get_state_size(self) ->Tuple[int, int]:\n \"\"\"\n Return the tuple (height, width) of the canvas dimensions\n \"\"\"\n return self.height, self.width\n\n def _step_snell(self) ->None:\n \"\"\"\n Step the snell layer\n \"\"\"\n self.snell.step()\n\n def _reset_ball(self):\n self.ball.reset((self.width / 2, self.height / 2))\n\n def _move_our_paddle(self, action) ->None:\n \"\"\"\n Move our paddle according to the provided action\n\n :param action: the action code\n \"\"\"\n if not isinstance(action, int):\n action = action.item()\n assert action in [a for a in self.action_meanings.keys()\n ], f'{action} is not a valid action'\n if action == self.actions['UP']:\n if self.paddle_r.top_bound < self.top_bound:\n self.paddle_r.up()\n elif action == self.actions['DOWN']:\n if self.paddle_r.bottom_bound > self.bottom_bound:\n self.paddle_r.down()\n\n def _step_ball(self, speed: Union[float, int]=None):\n \"\"\"\n Move the ball to the next position according to the speed of the layer it is in.\n\n :param speed: used to continue the trajectory of a ball that interacted with an object\n \"\"\"\n trajectory = self._get_trajectory(speed)\n self._get_first_intersection(trajectory)\n reward = 0\n if trajectory.intersection is None:\n self.ball.pos = trajectory.center.end\n else:\n reward = self._interaction_dispatcher(trajectory)\n return reward\n\n def _get_trajectory(self, speed) ->TrajectoryBase:\n \"\"\"\n Get the ball's trajectory\n\n :param speed: The speed of the starting medium\n :return: trajectory `Line`\n \"\"\"\n if speed is None:\n speed = self._get_ball_speed()\n if self.ball.has_volume:\n trajectory = Trajectory(self.ball, self.ball.get_velocity(speed))\n else:\n trajectory = Trajectory(self.ball.pos, self.ball.get_velocity(\n speed))\n return trajectory\n\n def _interaction_dispatcher(self, trajectory: TrajectoryBase):\n \"\"\"\n Dispatch data to the appropriate method based on the interaction `obj`.\n\n :param trajectory: the trajectory of the ball\n \"\"\"\n reward = 0\n obj = trajectory.intersected_object\n if obj is self:\n reward = self._interact_border(trajectory)\n elif isinstance(obj, Paddle):\n self._interact_paddle(trajectory)\n elif isinstance(obj, Snell):\n self._refract(trajectory)\n return reward\n\n def _interact_paddle(self, trajectory: TrajectoryBase) ->float:\n paddle = trajectory.intersected_object\n paddle_fraction = paddle.get_fraction_of_paddle(trajectory.\n get_center_at_intersection())\n angle = paddle_fraction * paddle.max_angle\n angle = math.pi - angle if self.ball.unit_velocity.x > 0 else angle\n self.ball.angle = angle\n reward = self._finish_step_ball(trajectory)\n return reward\n\n def _refract(self, trajectory: TrajectoryBase):\n edge = trajectory.intersected_edge\n if self.refract:\n s0, s1 = self._get_start_and_end_speed(trajectory)\n angle = edge.angle_to_normal(trajectory.center)\n if self._exceeds_critical_angle(angle, s0, s1):\n self._reflect(Point(-1, 1), trajectory)\n return\n new_angle = math.asin(s1 / s0 * math.sin(angle))\n boundary_angle, new_angle = (self.\n _adjust_refraction_to_boundary_angle(edge, new_angle))\n new_angle = self._adjust_refraction_to_direction_of_incidence(\n boundary_angle, new_angle, trajectory)\n self.ball.angle = new_angle\n return self._finish_step_ball(trajectory)\n\n @staticmethod\n def _exceeds_critical_angle(angle: float, s0: float, s1: float) ->bool:\n \"\"\"\n Test if the angle exceeds the critical angle\n\n :param angle: The angle to the normal of the boundary\n :param s0: The speed of the original medium\n :param s1: The speed of the next medium\n :return: True if the angle exceeds the critical angle\n \"\"\"\n if s1 > s0:\n critical_angle = get_critical_angle(s0, s1)\n if abs(angle) >= critical_angle:\n return True\n return False\n\n @staticmethod\n def _adjust_refraction_to_direction_of_incidence(boundary_angle: float,\n new_angle: float, trajectory: TrajectoryBase) ->float:\n \"\"\"\n If the direction of incidence was from the right of the boundary, reflect `new_angle`, otherwise, return\n `new_angle` without modification.\n\n :param boundary_angle: must be in the first or fourth quadrant\n :param new_angle: The angle to be reflected in the return\n :param trajectory: The angle of the incoming ball in global coordinates\n :return: The (possibly) reflected `new_angle`\n \"\"\"\n angle = trajectory.center.angle\n assert -math.pi / 2 <= boundary_angle <= math.pi / 2, 'boundary_angle should be in first or fourth quadrant'\n if boundary_angle >= 0 and boundary_angle < angle % (2 * math.pi\n ) < boundary_angle + math.pi:\n new_angle = math.pi - new_angle\n elif boundary_angle < 0 and boundary_angle % (2 * math.pi\n ) + math.pi < angle % (2 * math.pi) < boundary_angle % (2 * math.pi\n ):\n new_angle = math.pi - new_angle\n return new_angle\n\n @staticmethod\n def _adjust_refraction_to_boundary_angle(boundary: Line, new_angle: float\n ) ->Tuple[float, float]:\n \"\"\"\n Compute the rotation of `new_angle` back to global coordinates. Assume incidence from the left side of the\n boundary.\n\n :param boundary: The boundary `primitives.Line` object\n :param new_angle: The refracted angle normal to the boundary\n :return: The new angle in global coordinates\n \"\"\"\n boundary_angle = boundary.angle % (2 * math.pi)\n if 0 <= boundary_angle < math.pi / 2:\n boundary_angle = boundary_angle\n new_angle = boundary_angle - math.pi / 2 + new_angle\n elif math.pi / 2 <= boundary_angle < math.pi:\n boundary_angle = math.pi - boundary_angle\n new_angle = math.pi / 2 - boundary_angle + new_angle\n elif math.pi <= boundary_angle < 3 * math.pi / 2:\n boundary_angle = math.pi - boundary_angle\n new_angle = boundary_angle - math.pi / 2 + new_angle\n elif 2 * math.pi / 3 <= boundary_angle < 2 * math.pi:\n boundary_angle = 2 * math.pi - boundary_angle\n new_angle = math.pi / 2 - boundary_angle - new_angle\n else:\n raise ValueError(f'Unexpected angle {boundary_angle}')\n return boundary_angle, new_angle\n\n def _get_start_and_end_speed(self, trajectory: TrajectoryBase) ->Tuple[\n float, float]:\n \"\"\"\n Get the speed at the start of the trajectory and the speed at the end of the trajectory.\n\n :param trajectory: The trajectory `primitives.Line` object\n :return: (initial speed, final speed)\n \"\"\"\n snell = trajectory.intersected_object\n if snell.is_in(trajectory.center.start):\n s0 = snell.speed\n s1 = self.default_ball_speed\n else:\n s0 = self.default_ball_speed\n s1 = snell.speed\n return s0, s1\n\n def _interact_border(self, trajectory: TrajectoryBase) ->float:\n reward = 0.0\n edge = trajectory.intersected_edge\n if edge == self.top_edge or edge == self.bot_edge:\n self._reflect(Point(1, -1), trajectory)\n elif edge == self.left_edge:\n reward = self.score('we')\n elif edge == self.right_edge:\n reward = self.score('they')\n else:\n raise ValueError(f'invalid edge, {edge}')\n return reward\n\n def _reflect(self, direction: Point, trajectory: TrajectoryBase):\n \"\"\"\n Multiplies the velocity of the ball by `direction`, continues the path of the ball by calculating the remaining\n speed using trajectory and point.\n\n :param direction: velocity multiplier\n :param trajectory: The original trajectory of the ball\n \"\"\"\n self.ball.unit_velocity *= direction\n return self._finish_step_ball(trajectory)\n\n def _finish_step_ball(self, trajectory: TrajectoryBase):\n \"\"\"\n Finish the remainder of the trajectory after any interactions.\n\n :param trajectory: The original trajectory\n :return: reward\n \"\"\"\n point = trajectory.get_center_at_intersection()\n self.ball.pos = point + self.ball.unit_velocity * EPSILON\n return self._step_ball(trajectory.remaining_speed)\n\n def _get_first_intersection(self, trajectory: TrajectoryBase):\n \"\"\"\n Find the first point at which the trajectory interacted with an object.\n\n :param trajectory: the trajectory of the object\n :return: (shape object interacted with, point of interaction, line object interacted with)\n \"\"\"\n for trajectory_line in trajectory.corners:\n for o in self.sprites:\n if not isinstance(o, Ball):\n intersection_result = o.get_intersection(trajectory_line)\n if intersection_result is not None:\n edge, point = intersection_result\n if trajectory.intersection is None:\n trajectory.set_intersection(point,\n trajectory_line, o, edge)\n elif point == trajectory.intersection and trajectory_line == trajectory.intersected_trajectory:\n raise NotImplementedError(\n 'overlapping parallel edges not implemented')\n elif point.l2_distance(trajectory_line.start\n ) < trajectory.intersection.l2_distance(trajectory\n .intersected_trajectory.start):\n trajectory.set_intersection(point,\n trajectory_line, o, edge)\n\n def _get_ball_speed(self) ->float:\n if self.uniform_speed:\n return self.default_ball_speed\n elif self.ball.is_overlapping(self.snell):\n return self.snell.speed\n else:\n return self.default_ball_speed\n\n def _step_their_paddle(self):\n \"\"\"\n Move the opponents paddle. Override this in a subclass to change the behavior.\n \"\"\"\n if random.random() < self.their_update_probability:\n if self.paddle_l.y < self.ball.y:\n if self.paddle_l.top_bound < self.top_bound:\n self.paddle_l.up()\n elif self.paddle_l.bottom_bound > self.bottom_bound:\n self.paddle_l.down()\n", "step-5": "import abc\nimport math\nimport random\nfrom typing import Union, Tuple\n\nimport numpy as np\nfrom scipy import stats\n\nfrom . import Rectangle, Line, Point, Shape\n\n__all__ = ['get_critical_angle', 'Paddle', 'Ball', 'Snell', 'Canvas']\n\nEPSILON = 1e-7\n\n\ndef get_critical_angle(s0: float, s1: float) -> Union[float, None]:\n \"\"\"\n Returns the critical angle if it exists for a ball moving from a medium with velocity `s0` to a medium with\n velocity `s1`. If the critical angle does not exist, returns None.\n\n :param s0: speed of the initial medium\n :param s1: speed of the final medium\n :return: critical angle or None\n \"\"\"\n if s0 < s1:\n critical_angle = math.asin(s0 / s1)\n else:\n critical_angle = None\n return critical_angle\n\n\nclass Paddle(Rectangle):\n def __init__(self, height: float, width: float, speed: float, side: str, max_angle: float, visibility: str):\n \"\"\"\n\n :param height: The paddle height\n :param width: The paddle width (only matters for rendering)\n :param side: The side the paddle will be on ('left' or 'right')\n :param speed: The units the paddle moves in a single turn\n :param visibility: Whether and how to render the paddle. See `Shape.visibility`\n :param max_angle: The maximum angle at which the paddle can hit the ball\n \"\"\"\n super().__init__(height=height, width=width, visibility=visibility, render_value=255)\n assert side in ['left', 'right'], f\"side must be 'left' or 'right', not {side}\"\n assert 0 <= max_angle <= math.pi / 2, f\"max angle must be between 0 and pi/2, not {max_angle}\"\n self.side = side\n self.speed = speed\n self.max_angle = max_angle\n\n def up(self):\n self.y += self.speed\n\n def down(self):\n self.y -= self.speed\n\n def _get_edges(self) -> Tuple[Line]:\n \"\"\"\n Only return the field-side edge\n \"\"\"\n if self.side == 'right':\n return Line((self.left_bound, self.bottom_bound), (self.left_bound, self.top_bound)),\n elif self.side == 'left':\n return Line((self.right_bound, self.bottom_bound), (self.right_bound, self.top_bound)),\n\n def get_fraction_of_paddle(self, point: Point):\n \"\"\"\n Computes the fractional distance from the middle of the paddle, normalized by the paddle's height.\n Asserts if the ball was not on the paddle.\n\n :param point: the point where the ball hit the paddle\n :return: fraction of the paddle\n \"\"\"\n fraction = (point.y - self.y) / self.height\n fraction = max(min(fraction, 0.5), -0.5) # clamp to +/- 0.5\n return fraction\n\n\nclass Ball(Rectangle):\n def __init__(self, size: float, max_initial_angle: float, visibility: str, has_volume: bool = False):\n \"\"\"\n Ball object\n\n :param has_volume:\n :param size: The size to render the ball\n :param max_initial_angle: The maximum angle the ball can start with\n :param visibility: How to render the ball. See `Shape.visibility`\n :param has_volume: determines whether the ball interacts as a point or as an area\n \"\"\"\n super().__init__(width=size, height=size, visibility=visibility, render_value=255)\n self.max_initial_angle = max_initial_angle\n self.reset(self.pos, direction='left')\n self.has_volume = has_volume\n\n def reset(self, position: Union[Tuple[float, float], Point], direction: str = 'right'):\n if direction == 'right':\n self._angle = (2 * random.random() - 1) * self.max_initial_angle\n elif direction == 'left':\n self._angle = math.pi - (2 * random.random() - 1) * self.max_initial_angle\n else:\n raise ValueError(f\"direction must be 'left' or 'right', not {direction}\")\n self.pos = position\n\n @property\n def angle(self):\n \"\"\"\n Angle with respect to the right horizontal\n \"\"\"\n return self._angle\n\n @angle.setter\n def angle(self, value):\n self._angle = value % (2 * math.pi)\n\n @property\n def unit_velocity(self) -> Point:\n x = math.cos(self.angle)\n y = math.sin(self.angle)\n return Point(x, y)\n\n @unit_velocity.setter\n def unit_velocity(self, value: Union[Tuple[float, float], Point]):\n \"\"\"\n Sets the angle parameter give a set of (x, y) coordinates.\n\n :param value: (x, y)\n \"\"\"\n if isinstance(value, tuple):\n value = Point(*value)\n assert isinstance(value, Point), f\"value must be a point, not {type(value)}\"\n self.angle = value.angle\n\n def get_velocity(self, speed: Union[float, int]):\n return self.unit_velocity * speed\n\n\nclass Snell(Rectangle):\n def __init__(self, width, height, speed, change_rate, visibility):\n \"\"\"\n Rectangular area with a different ball speed.\n\n :param width: The width of the layer\n :param height: The height of the layer\n :param change_rate: Rate at which the ball speed changes, the standard deviation of the change on each step.\n :param visibility: Whether and how to render the layer. See `Shape.visibility`\n \"\"\"\n assert change_rate >= 0, \"Snell `change_rate` must be non-negative\"\n\n super().__init__(width=width, height=height, visibility=visibility, render_value=(235, 76, 52))\n self.speed = speed\n self._initial_speed = speed\n self.change_rate = change_rate\n\n def step(self):\n \"\"\"\n Step the Snell speed using a bounded Gaussian random walk.\n\n - step with mean 0, standard deviation `self.speed`\n - Clip the speed at `0.5 * self._initial_speed <= self.speed <= 2.0 * self._initial_speed`\n \"\"\"\n if self.change_rate != 0:\n self.speed += stats.norm(loc=0, scale=self.change_rate).rvs()\n\n if self.speed < 0.5 * self._initial_speed:\n self.speed = 0.5 * self._initial_speed\n if self.speed > 2.0 * self._initial_speed:\n self.speed = 2.0 * self._initial_speed\n else:\n pass\n\n\nclass TrajectoryBase(abc.ABC):\n def __init__(self, shape: Union[Point, Line, Rectangle], velocity: Point):\n self.shape = shape\n self.velocity = velocity\n\n self._reference = None\n self.intersection = None\n self.intersected_trajectory = None\n self.intersected_object = None\n self.intersected_edge = None\n self.remaining_speed = None\n\n def set_intersection(self, point: Point, trajectory_line: Line, obj: Shape, edge: Line):\n assert isinstance(obj, Shape), f\"type Shape expected, not {type(obj)}\"\n assert isinstance(point, Point), f\"type Point expected, not {type(point)}\"\n assert isinstance(edge, Line), f\"type Line expected, not {type(edge)}\"\n\n self.intersection = point\n self.intersected_trajectory = trajectory_line\n self.remaining_speed = point.l2_distance(trajectory_line.end)\n self.intersected_object = obj\n self.intersected_edge = edge\n\n def get_center_at_intersection(self) -> Point:\n \"\"\"\n Get the new center of `self.shape` given that it moved along `intersected_trajectory` to `intersection`\n\n :return: new center point\n \"\"\"\n return self._reference + (self.intersection - self.intersected_trajectory.start)\n\n @property\n def corners(self) -> Tuple[Line, ...]:\n return self.top_left, self.top_right, self.bottom_right, self.bottom_left\n\n @property\n @abc.abstractmethod\n def center(self) -> Line: ...\n\n @property\n @abc.abstractmethod\n def top_right(self) -> Line: ...\n\n @property\n @abc.abstractmethod\n def top_left(self) -> Line: ...\n\n @property\n @abc.abstractmethod\n def bottom_right(self) -> Line: ...\n\n @property\n @abc.abstractmethod\n def bottom_left(self) -> Line: ...\n\n\nclass TrajectoryRectangle(TrajectoryBase):\n \"\"\"\n Compute the trajectory of each corner of the rectangle\n \"\"\"\n\n def __init__(self, shape: Rectangle, velocity: Point):\n super(TrajectoryRectangle, self).__init__(shape, velocity)\n assert isinstance(shape, Rectangle)\n self._reference = self.shape.pos\n\n @property\n def center(self) -> Line:\n \"\"\"\n Line representing the trajectory of the center of the rectangle\n \"\"\"\n return Line(self.shape.pos, self.shape.pos + self.velocity)\n\n @property\n def top_right(self) -> Line:\n \"\"\"\n Line representing the trajectory of the point on the top right corner of the rectangle\n \"\"\"\n start = Point(self.shape.right_bound, self.shape.top_bound)\n return Line(start, start + self.velocity)\n\n @property\n def top_left(self) -> Line:\n \"\"\"\n Line representing the trajectory of the point on the top left corner of the rectangle\n \"\"\"\n start = Point(self.shape.left_bound, self.shape.top_bound)\n return Line(start, start + self.velocity)\n\n @property\n def bottom_right(self) -> Line:\n \"\"\"\n Line representing the trajectory of the point on the bottom right corner of the rectangle\n \"\"\"\n start = Point(self.shape.right_bound, self.shape.bottom_bound)\n return Line(start, start + self.velocity)\n\n @property\n def bottom_left(self) -> Line:\n \"\"\"\n Line representing the trajectory of the point on the bottom left corner of the rectangle\n \"\"\"\n start = Point(self.shape.left_bound, self.shape.bottom_bound)\n return Line(start, start + self.velocity)\n\n\nclass TrajectoryLine(TrajectoryRectangle):\n \"\"\"\n Create a bounding box around the line and compute the trajectory as if it were a rectangle.\n \"\"\"\n\n # noinspection PyTypeChecker\n # noinspection PyUnresolvedReferences\n def __init__(self, shape: Line, velocity: Point):\n super(TrajectoryLine, self).__init__(shape, velocity)\n assert isinstance(shape, Line)\n self._reference = self.shape.start\n\n height = abs(self.shape.start.y - self.shape.end.y)\n width = abs(self.shape.start.x - self.shape.end.x)\n center = Point((self.shape.start.x + self.shape.end.x) / 2,\n (self.shape.start.y + self.shape.end.y) / 2)\n self.shape = Rectangle(height=height, width=width)\n self.shape.pos = center\n\n\nclass TrajectoryPoint(TrajectoryBase):\n def __init__(self, shape: Point, velocity: Point):\n super(TrajectoryPoint, self).__init__(shape, velocity)\n assert isinstance(shape, Point)\n self._reference = self.shape\n\n @property\n def corners(self) -> Tuple[Line, ...]:\n return (self._trajectory,)\n\n @property\n def _trajectory(self) -> Line:\n return Line(self.shape, self.shape + self.velocity)\n\n @property\n def center(self) -> Line:\n return self._trajectory\n\n @property\n def top_right(self) -> Line:\n return self._trajectory\n\n @property\n def top_left(self) -> Line:\n return self._trajectory\n\n @property\n def bottom_right(self) -> Line:\n return self._trajectory\n\n @property\n def bottom_left(self) -> Line:\n return self._trajectory\n\n\nclass Trajectory(object):\n def __new__(cls, shape: Shape, velocity: Point):\n if isinstance(shape, Point):\n return TrajectoryPoint(shape, velocity)\n elif isinstance(shape, Line):\n return TrajectoryLine(shape, velocity)\n elif isinstance(shape, Rectangle):\n return TrajectoryRectangle(shape, velocity)\n else:\n raise NotImplementedError(f\"No implementation of Trajectory for input shape of type {type(shape)}\")\n\n\nclass Canvas(Rectangle):\n action_meanings = {0: 'NOOP',\n 1: 'UP',\n 2: 'DOWN', }\n actions = {k: v for v, k in action_meanings.items()}\n\n def __init__(self, paddle_l: Paddle, paddle_r: Paddle, ball: Ball, snell: Snell, ball_speed: int, height: int,\n width: int, their_update_probability: float, refract: bool, uniform_speed: bool):\n\n super().__init__(height=height, width=width, visibility='none', render_value=0)\n self.pos = self.width / 2, self.height / 2\n\n assert isinstance(their_update_probability, (float, int)), \\\n f\"their_update_probability must be numeric, not {type(their_update_probability)}\"\n assert 0 <= their_update_probability <= 1, f\"{their_update_probability} outside allowed bounds [0, 1]\"\n\n self.their_update_probability = their_update_probability\n self.default_ball_speed = ball_speed\n\n # Initialize objects\n self.snell = snell\n self.ball = ball\n self.paddle_l = paddle_l\n self.paddle_r = paddle_r\n self.sprites = [self, snell, paddle_l, paddle_r, ball]\n\n self.uniform_speed = uniform_speed\n self.refract = refract\n self.we_scored = False\n self.they_scored = False\n\n # score\n self.our_score = 0\n self.their_score = 0\n\n def register_sprite(self, sprite: Shape):\n assert issubclass(type(sprite), Shape), f\"sprite must be subclassed from Shape\"\n # noinspection PyTypeChecker\n self.sprites.insert(-1, sprite) # insert before ball\n\n @property\n def left_bound(self):\n return 0\n\n @property\n def right_bound(self):\n return self.width\n\n @property\n def top_bound(self):\n return self.height\n\n @property\n def bottom_bound(self):\n return 0\n\n # noinspection PyMethodOverriding\n def to_numpy(self) -> Tuple[np.ndarray, np.ndarray]:\n \"\"\"\n Performs masked rendering of objects in `self.sprites`. Priority is determined by the ordering of the list,\n earlier objects will be obscured by later ones.\n\n :return: (state, rendering)\n \"\"\"\n state = self._zero_rgb_image(round(self.height), round(self.width))\n rendering = self._zero_rgb_image(round(self.height), round(self.width))\n\n for sprite in self.sprites[1:]: # skip self\n sprite_state, sprite_rendering = sprite.to_numpy(self.height, self.width)\n state[sprite_state != 0] = sprite_state[sprite_state != 0]\n rendering[sprite_rendering != 0] = sprite_rendering[sprite_rendering != 0]\n return state, rendering\n\n def score(self, who):\n \"\"\"\n Increment the score and reset the ball\n\n :param who: 'we' or 'they'\n :return: reward\n \"\"\"\n if who == 'they':\n reward = -1\n self.their_score += 1\n elif who == 'we':\n reward = 1\n self.our_score += 1\n else:\n raise ValueError(f\"who must be 'we' or 'they', not {who}\")\n\n self._reset_ball()\n return reward\n\n def step(self, action):\n self._move_our_paddle(action)\n self._step_their_paddle()\n reward = self._step_ball()\n self._step_snell()\n return reward\n\n def get_state_size(self) -> Tuple[int, int]:\n \"\"\"\n Return the tuple (height, width) of the canvas dimensions\n \"\"\"\n return self.height, self.width\n\n def _step_snell(self) -> None:\n \"\"\"\n Step the snell layer\n \"\"\"\n self.snell.step()\n\n def _reset_ball(self):\n self.ball.reset((self.width / 2, self.height / 2))\n\n def _move_our_paddle(self, action) -> None:\n \"\"\"\n Move our paddle according to the provided action\n\n :param action: the action code\n \"\"\"\n if not isinstance(action, int):\n action = action.item() # pops the item if the action is a single tensor\n assert action in [a for a in self.action_meanings.keys()], f\"{action} is not a valid action\"\n if action == self.actions['UP']:\n if self.paddle_r.top_bound < self.top_bound:\n self.paddle_r.up()\n elif action == self.actions['DOWN']:\n if self.paddle_r.bottom_bound > self.bottom_bound:\n self.paddle_r.down()\n\n def _step_ball(self, speed: Union[float, int] = None):\n \"\"\"\n Move the ball to the next position according to the speed of the layer it is in.\n\n :param speed: used to continue the trajectory of a ball that interacted with an object\n \"\"\"\n trajectory = self._get_trajectory(speed)\n\n self._get_first_intersection(trajectory)\n reward = 0\n if trajectory.intersection is None: # No intersection\n self.ball.pos = trajectory.center.end\n else:\n reward = self._interaction_dispatcher(trajectory)\n\n return reward\n\n def _get_trajectory(self, speed) -> TrajectoryBase:\n \"\"\"\n Get the ball's trajectory\n\n :param speed: The speed of the starting medium\n :return: trajectory `Line`\n \"\"\"\n if speed is None:\n speed = self._get_ball_speed()\n if self.ball.has_volume:\n trajectory = Trajectory(self.ball, self.ball.get_velocity(speed))\n else:\n trajectory = Trajectory(self.ball.pos, self.ball.get_velocity(speed))\n return trajectory\n\n def _interaction_dispatcher(self, trajectory: TrajectoryBase):\n \"\"\"\n Dispatch data to the appropriate method based on the interaction `obj`.\n\n :param trajectory: the trajectory of the ball\n \"\"\"\n reward = 0\n\n obj = trajectory.intersected_object\n if obj is self: # border interaction\n reward = self._interact_border(trajectory)\n elif isinstance(obj, Paddle): # paddle interaction\n self._interact_paddle(trajectory)\n elif isinstance(obj, Snell):\n self._refract(trajectory)\n\n return reward\n\n def _interact_paddle(self, trajectory: TrajectoryBase) -> float:\n paddle = trajectory.intersected_object\n paddle_fraction = paddle.get_fraction_of_paddle(trajectory.get_center_at_intersection())\n angle = paddle_fraction * paddle.max_angle\n angle = math.pi - angle if self.ball.unit_velocity.x > 0 else angle\n\n self.ball.angle = angle\n reward = self._finish_step_ball(trajectory)\n return reward\n\n def _refract(self, trajectory: TrajectoryBase):\n edge = trajectory.intersected_edge\n if self.refract:\n s0, s1 = self._get_start_and_end_speed(trajectory)\n\n angle = edge.angle_to_normal(trajectory.center)\n if self._exceeds_critical_angle(angle, s0, s1):\n # TODO: reflect to arbitrary angle (non-vertical interface)\n self._reflect(Point(-1, 1), trajectory)\n return\n\n new_angle = math.asin(s1 / s0 * math.sin(angle))\n\n boundary_angle, new_angle = self._adjust_refraction_to_boundary_angle(edge, new_angle)\n new_angle = self._adjust_refraction_to_direction_of_incidence(boundary_angle, new_angle, trajectory)\n self.ball.angle = new_angle\n\n return self._finish_step_ball(trajectory)\n\n @staticmethod\n def _exceeds_critical_angle(angle: float, s0: float, s1: float) -> bool:\n \"\"\"\n Test if the angle exceeds the critical angle\n\n :param angle: The angle to the normal of the boundary\n :param s0: The speed of the original medium\n :param s1: The speed of the next medium\n :return: True if the angle exceeds the critical angle\n \"\"\"\n if s1 > s0: # if the second speed is faster, there is a critical angle\n critical_angle = get_critical_angle(s0, s1)\n if abs(angle) >= critical_angle:\n return True\n return False\n\n @staticmethod\n def _adjust_refraction_to_direction_of_incidence(boundary_angle: float, new_angle: float,\n trajectory: TrajectoryBase) -> float:\n \"\"\"\n If the direction of incidence was from the right of the boundary, reflect `new_angle`, otherwise, return\n `new_angle` without modification.\n\n :param boundary_angle: must be in the first or fourth quadrant\n :param new_angle: The angle to be reflected in the return\n :param trajectory: The angle of the incoming ball in global coordinates\n :return: The (possibly) reflected `new_angle`\n \"\"\"\n angle = trajectory.center.angle\n assert -math.pi / 2 <= boundary_angle <= math.pi / 2, \"boundary_angle should be in first or fourth quadrant\"\n # noinspection PyChainedComparisons\n if boundary_angle >= 0 and boundary_angle < angle % (2 * math.pi) < boundary_angle + math.pi:\n new_angle = math.pi - new_angle\n elif (boundary_angle < 0 and\n boundary_angle % (2 * math.pi) + math.pi < angle % (2 * math.pi) < boundary_angle % (\n 2 * math.pi)):\n new_angle = math.pi - new_angle\n return new_angle\n\n @staticmethod\n def _adjust_refraction_to_boundary_angle(boundary: Line, new_angle: float) -> Tuple[float, float]:\n \"\"\"\n Compute the rotation of `new_angle` back to global coordinates. Assume incidence from the left side of the\n boundary.\n\n :param boundary: The boundary `primitives.Line` object\n :param new_angle: The refracted angle normal to the boundary\n :return: The new angle in global coordinates\n \"\"\"\n # TODO: verify this works with a non-vertical interface\n\n boundary_angle = boundary.angle % (2 * math.pi)\n if 0 <= boundary_angle < math.pi / 2: # in the first quadrant\n boundary_angle = boundary_angle\n new_angle = boundary_angle - math.pi / 2 + new_angle\n elif math.pi / 2 <= boundary_angle < math.pi: # in the second quadrant\n boundary_angle = math.pi - boundary_angle\n new_angle = math.pi / 2 - boundary_angle + new_angle\n elif math.pi <= boundary_angle < 3 * math.pi / 2: # in the third quadrant\n boundary_angle = math.pi - boundary_angle\n new_angle = boundary_angle - math.pi / 2 + new_angle\n elif 2 * math.pi / 3 <= boundary_angle < 2 * math.pi: # in the fourth quadrant\n boundary_angle = 2 * math.pi - boundary_angle\n new_angle = math.pi / 2 - boundary_angle - new_angle\n else:\n raise ValueError(f'Unexpected angle {boundary_angle}')\n return boundary_angle, new_angle\n\n def _get_start_and_end_speed(self, trajectory: TrajectoryBase) -> Tuple[float, float]:\n \"\"\"\n Get the speed at the start of the trajectory and the speed at the end of the trajectory.\n\n :param trajectory: The trajectory `primitives.Line` object\n :return: (initial speed, final speed)\n \"\"\"\n snell = trajectory.intersected_object\n # todo: detect if start is in some other snell layer\n if snell.is_in(trajectory.center.start):\n s0 = snell.speed\n s1 = self.default_ball_speed\n else:\n s0 = self.default_ball_speed\n s1 = snell.speed\n return s0, s1\n\n def _interact_border(self, trajectory: TrajectoryBase) -> float:\n reward = 0.\n edge = trajectory.intersected_edge\n\n if edge == self.top_edge or edge == self.bot_edge:\n self._reflect(Point(1, -1), trajectory)\n elif edge == self.left_edge:\n reward = self.score('we')\n elif edge == self.right_edge:\n reward = self.score('they')\n else:\n raise ValueError(f'invalid edge, {edge}')\n\n return reward\n\n def _reflect(self, direction: Point, trajectory: TrajectoryBase):\n \"\"\"\n Multiplies the velocity of the ball by `direction`, continues the path of the ball by calculating the remaining\n speed using trajectory and point.\n\n :param direction: velocity multiplier\n :param trajectory: The original trajectory of the ball\n \"\"\"\n self.ball.unit_velocity *= direction\n return self._finish_step_ball(trajectory)\n\n def _finish_step_ball(self, trajectory: TrajectoryBase):\n \"\"\"\n Finish the remainder of the trajectory after any interactions.\n\n :param trajectory: The original trajectory\n :return: reward\n \"\"\"\n point = trajectory.get_center_at_intersection()\n self.ball.pos = point + self.ball.unit_velocity * EPSILON\n return self._step_ball(trajectory.remaining_speed)\n\n def _get_first_intersection(self, trajectory: TrajectoryBase):\n \"\"\"\n Find the first point at which the trajectory interacted with an object.\n\n :param trajectory: the trajectory of the object\n :return: (shape object interacted with, point of interaction, line object interacted with)\n \"\"\"\n for trajectory_line in trajectory.corners:\n for o in self.sprites:\n if not isinstance(o, Ball):\n intersection_result = o.get_intersection(trajectory_line)\n if intersection_result is not None:\n edge, point = intersection_result\n if trajectory.intersection is None:\n trajectory.set_intersection(point, trajectory_line, o, edge)\n elif point == trajectory.intersection and trajectory_line == trajectory.intersected_trajectory:\n raise NotImplementedError(\"overlapping parallel edges not implemented\")\n elif (point.l2_distance(trajectory_line.start) <\n trajectory.intersection.l2_distance(trajectory.intersected_trajectory.start)):\n trajectory.set_intersection(point, trajectory_line, o, edge)\n\n def _get_ball_speed(self) -> float:\n if self.uniform_speed:\n return self.default_ball_speed\n else:\n if self.ball.is_overlapping(self.snell):\n return self.snell.speed\n else:\n return self.default_ball_speed\n\n def _step_their_paddle(self):\n \"\"\"\n Move the opponents paddle. Override this in a subclass to change the behavior.\n \"\"\"\n if random.random() < self.their_update_probability:\n if self.paddle_l.y < self.ball.y:\n if self.paddle_l.top_bound < self.top_bound:\n self.paddle_l.up()\n else:\n if self.paddle_l.bottom_bound > self.bottom_bound:\n self.paddle_l.down()\n", "step-ids": [ 46, 51, 75, 76, 83 ] }
[ 46, 51, 75, 76, 83 ]
from django.db import models # Create your models here. from user.models import User class Post(models.Model): class Meta: db_table = 'bl_post' id = models.AutoField(primary_key=True) title = models.CharField(max_length=200, null=False) pubdate = models.DateTimeField(null=False) # 作者 # author_id = models.IntegerField(null=False) author = models.ForeignKey(User) # 内容 def __repr__(self): return "<Post {} {} {} {} [{}] >".format(self.id, self.title,self.author,self.content,self.author.id) __str__ = __repr__ class Content(models.Model): class Meta: db_table = 'bl_content' # id 可以不写,主键django帮你创建一个pk post = models.OneToOneField(Post, to_field='id') # post_id content = models.TextField(null=False) def __repr__(self): return "<Content {} {} {} >".format(self.id,self.post.id, self.content[:40]) __str__ = __repr__
normal
{ "blob_id": "34a523b31e5567d2a8aec95c5820792d1ae80892", "index": 5335, "step-1": "<mask token>\n\n\nclass Post(models.Model):\n\n\n class Meta:\n db_table = 'bl_post'\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Content(models.Model):\n\n\n class Meta:\n db_table = 'bl_content'\n post = models.OneToOneField(Post, to_field='id')\n content = models.TextField(null=False)\n\n def __repr__(self):\n return '<Content {} {} {} >'.format(self.id, self.post.id, self.\n content[:40])\n __str__ = __repr__\n", "step-2": "<mask token>\n\n\nclass Post(models.Model):\n\n\n class Meta:\n db_table = 'bl_post'\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __repr__(self):\n return '<Post {} {} {} {} [{}] >'.format(self.id, self.title, self.\n author, self.content, self.author.id)\n <mask token>\n\n\nclass Content(models.Model):\n\n\n class Meta:\n db_table = 'bl_content'\n post = models.OneToOneField(Post, to_field='id')\n content = models.TextField(null=False)\n\n def __repr__(self):\n return '<Content {} {} {} >'.format(self.id, self.post.id, self.\n content[:40])\n __str__ = __repr__\n", "step-3": "<mask token>\n\n\nclass Post(models.Model):\n\n\n class Meta:\n db_table = 'bl_post'\n id = models.AutoField(primary_key=True)\n title = models.CharField(max_length=200, null=False)\n pubdate = models.DateTimeField(null=False)\n author = models.ForeignKey(User)\n\n def __repr__(self):\n return '<Post {} {} {} {} [{}] >'.format(self.id, self.title, self.\n author, self.content, self.author.id)\n __str__ = __repr__\n\n\nclass Content(models.Model):\n\n\n class Meta:\n db_table = 'bl_content'\n post = models.OneToOneField(Post, to_field='id')\n content = models.TextField(null=False)\n\n def __repr__(self):\n return '<Content {} {} {} >'.format(self.id, self.post.id, self.\n content[:40])\n __str__ = __repr__\n", "step-4": "from django.db import models\nfrom user.models import User\n\n\nclass Post(models.Model):\n\n\n class Meta:\n db_table = 'bl_post'\n id = models.AutoField(primary_key=True)\n title = models.CharField(max_length=200, null=False)\n pubdate = models.DateTimeField(null=False)\n author = models.ForeignKey(User)\n\n def __repr__(self):\n return '<Post {} {} {} {} [{}] >'.format(self.id, self.title, self.\n author, self.content, self.author.id)\n __str__ = __repr__\n\n\nclass Content(models.Model):\n\n\n class Meta:\n db_table = 'bl_content'\n post = models.OneToOneField(Post, to_field='id')\n content = models.TextField(null=False)\n\n def __repr__(self):\n return '<Content {} {} {} >'.format(self.id, self.post.id, self.\n content[:40])\n __str__ = __repr__\n", "step-5": "from django.db import models\n\n# Create your models here.\nfrom user.models import User\n\n\nclass Post(models.Model):\n class Meta:\n db_table = 'bl_post'\n\n id = models.AutoField(primary_key=True)\n title = models.CharField(max_length=200, null=False)\n pubdate = models.DateTimeField(null=False)\n # 作者\n # author_id = models.IntegerField(null=False)\n author = models.ForeignKey(User)\n\n # 内容\n\n def __repr__(self):\n return \"<Post {} {} {} {} [{}] >\".format(self.id, self.title,self.author,self.content,self.author.id)\n\n __str__ = __repr__\n\n\nclass Content(models.Model):\n class Meta:\n db_table = 'bl_content'\n\n # id 可以不写,主键django帮你创建一个pk\n post = models.OneToOneField(Post, to_field='id') # post_id\n content = models.TextField(null=False)\n\n def __repr__(self):\n return \"<Content {} {} {} >\".format(self.id,self.post.id, self.content[:40])\n\n __str__ = __repr__\n", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def election(votes, message=True, force_forward=False): votes = deepcopy(votes) N = len(votes) for i in range(N): obtained = Counter([v[-1] for v in votes if len(v)]).most_common() M = len(obtained) top = obtained[0] if M == 1: return top[0] accum = [0] for ob in obtained[::-1]: accum.append(accum[-1] + ob[1]) accum = accum[:0:-1] candidates = {top[0]} for m in range(1, M): if accum[m] < obtained[m - 1][1]: break else: candidates.add(obtained[m][0]) else: m += 1 if message: print('The {}-th vote: {}'.format(i + 1, obtained)) if m == 1: return top[0] elif m >= M: l = M - 2 while l >= 0 and obtained[l][1] == obtained[-1][1]: l -= 1 candidates = {obtained[i][0] for i in range(l + 1)} fighting = {obtained[i][0] for i in range(l + 1, M)} losers = set() for f in fighting: tmp_votes = deepcopy(votes) tmp_candidates = candidates | {f} for n in range(N): while len(tmp_votes[n]) > 0 and not tmp_votes[n][-1 ] in tmp_candidates: tmp_votes[n].pop() tmp_result = election(tmp_votes, message=False) if tmp_result != f and not (isinstance(tmp_result, list) and f in dict(tmp_result)): losers.add(f) candidates |= fighting candidates -= losers if losers: if message: print(' Candidates {} survived.'.format([obtained[j][0 ] for j in range(m) if obtained[j][0] in candidates])) else: if message: print(' All the candidates survived.') if force_forward: drop = obtained[randrange(l + 1, M)][0] candidates.discard(drop) if message: print(" Drop the candidate '{}'.".format(drop)) elif message: print(' Final winner was not determined.') return obtained elif message: print(' Candidates {} survived.'.format([obtained[j][0] for j in range(m)])) for n in range(N): while len(votes[n]) > 0 and not votes[n][-1] in candidates: votes[n].pop() <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def election(votes, message=True, force_forward=False): votes = deepcopy(votes) N = len(votes) for i in range(N): obtained = Counter([v[-1] for v in votes if len(v)]).most_common() M = len(obtained) top = obtained[0] if M == 1: return top[0] accum = [0] for ob in obtained[::-1]: accum.append(accum[-1] + ob[1]) accum = accum[:0:-1] candidates = {top[0]} for m in range(1, M): if accum[m] < obtained[m - 1][1]: break else: candidates.add(obtained[m][0]) else: m += 1 if message: print('The {}-th vote: {}'.format(i + 1, obtained)) if m == 1: return top[0] elif m >= M: l = M - 2 while l >= 0 and obtained[l][1] == obtained[-1][1]: l -= 1 candidates = {obtained[i][0] for i in range(l + 1)} fighting = {obtained[i][0] for i in range(l + 1, M)} losers = set() for f in fighting: tmp_votes = deepcopy(votes) tmp_candidates = candidates | {f} for n in range(N): while len(tmp_votes[n]) > 0 and not tmp_votes[n][-1 ] in tmp_candidates: tmp_votes[n].pop() tmp_result = election(tmp_votes, message=False) if tmp_result != f and not (isinstance(tmp_result, list) and f in dict(tmp_result)): losers.add(f) candidates |= fighting candidates -= losers if losers: if message: print(' Candidates {} survived.'.format([obtained[j][0 ] for j in range(m) if obtained[j][0] in candidates])) else: if message: print(' All the candidates survived.') if force_forward: drop = obtained[randrange(l + 1, M)][0] candidates.discard(drop) if message: print(" Drop the candidate '{}'.".format(drop)) elif message: print(' Final winner was not determined.') return obtained elif message: print(' Candidates {} survived.'.format([obtained[j][0] for j in range(m)])) for n in range(N): while len(votes[n]) > 0 and not votes[n][-1] in candidates: votes[n].pop() if __name__ == '__main__': args = sys.argv if len(args) <= 1: K = 0 else: K = int(args[1]) votes = [] while True: try: votes.append(list(input().strip().upper()[::-1])) except EOFError: break if K == 0: winner = election(votes) print('---') if isinstance(winner, list): print("The candidates '{}' are still surviving.".format(winner)) else: print("The candidate '{}' is the Final Winner !!!".format(winner)) else: win_times = defaultdict(int) for _ in range(K): win_times[election(votes, message=False, force_forward=True)] += 1 result = list(win_times.items()) if len(result) == 1: winner = result[0][0] print("The candidate '{}' is the Final Winner !!".format(winner)) else: print('Final winner was not determined.') print('The winner distribution is: {}'.format(dict(win_times))) <|reserved_special_token_1|> from collections import Counter, defaultdict from random import randrange from copy import deepcopy import sys def election(votes, message=True, force_forward=False): votes = deepcopy(votes) N = len(votes) for i in range(N): obtained = Counter([v[-1] for v in votes if len(v)]).most_common() M = len(obtained) top = obtained[0] if M == 1: return top[0] accum = [0] for ob in obtained[::-1]: accum.append(accum[-1] + ob[1]) accum = accum[:0:-1] candidates = {top[0]} for m in range(1, M): if accum[m] < obtained[m - 1][1]: break else: candidates.add(obtained[m][0]) else: m += 1 if message: print('The {}-th vote: {}'.format(i + 1, obtained)) if m == 1: return top[0] elif m >= M: l = M - 2 while l >= 0 and obtained[l][1] == obtained[-1][1]: l -= 1 candidates = {obtained[i][0] for i in range(l + 1)} fighting = {obtained[i][0] for i in range(l + 1, M)} losers = set() for f in fighting: tmp_votes = deepcopy(votes) tmp_candidates = candidates | {f} for n in range(N): while len(tmp_votes[n]) > 0 and not tmp_votes[n][-1 ] in tmp_candidates: tmp_votes[n].pop() tmp_result = election(tmp_votes, message=False) if tmp_result != f and not (isinstance(tmp_result, list) and f in dict(tmp_result)): losers.add(f) candidates |= fighting candidates -= losers if losers: if message: print(' Candidates {} survived.'.format([obtained[j][0 ] for j in range(m) if obtained[j][0] in candidates])) else: if message: print(' All the candidates survived.') if force_forward: drop = obtained[randrange(l + 1, M)][0] candidates.discard(drop) if message: print(" Drop the candidate '{}'.".format(drop)) elif message: print(' Final winner was not determined.') return obtained elif message: print(' Candidates {} survived.'.format([obtained[j][0] for j in range(m)])) for n in range(N): while len(votes[n]) > 0 and not votes[n][-1] in candidates: votes[n].pop() if __name__ == '__main__': args = sys.argv if len(args) <= 1: K = 0 else: K = int(args[1]) votes = [] while True: try: votes.append(list(input().strip().upper()[::-1])) except EOFError: break if K == 0: winner = election(votes) print('---') if isinstance(winner, list): print("The candidates '{}' are still surviving.".format(winner)) else: print("The candidate '{}' is the Final Winner !!!".format(winner)) else: win_times = defaultdict(int) for _ in range(K): win_times[election(votes, message=False, force_forward=True)] += 1 result = list(win_times.items()) if len(result) == 1: winner = result[0][0] print("The candidate '{}' is the Final Winner !!".format(winner)) else: print('Final winner was not determined.') print('The winner distribution is: {}'.format(dict(win_times))) <|reserved_special_token_1|> from collections import Counter, defaultdict from random import randrange from copy import deepcopy import sys def election(votes, message=True, force_forward=False): votes = deepcopy(votes) N = len(votes) for i in range(N): obtained = Counter([v[-1] for v in votes if len(v)]).most_common() M = len(obtained) top = obtained[0] if M == 1: return top[0] accum = [0] for ob in obtained[::-1]: accum.append(accum[-1] + ob[1]) accum = accum[:0:-1] candidates = {top[0]} for m in range(1,M): if accum[m] < obtained[m-1][1]: break else: candidates.add(obtained[m][0]) else: m += 1 if message: print('The {}-th vote: {}'.format(i+1, obtained)) if m == 1: return top[0] elif m >= M: l = M-2 while l >= 0 and obtained[l][1] == obtained[-1][1]: l -= 1 candidates = {obtained[i][0] for i in range(l+1)} fighting = {obtained[i][0] for i in range(l+1,M)} losers = set() for f in fighting: tmp_votes = deepcopy(votes) tmp_candidates = candidates | {f} for n in range(N): while len(tmp_votes[n]) > 0 and not tmp_votes[n][-1] in tmp_candidates: tmp_votes[n].pop() tmp_result = election(tmp_votes, message=False) if tmp_result != f and not (isinstance(tmp_result,list) and f in dict(tmp_result)): losers.add(f) candidates |= fighting candidates -= losers if losers: if message: print(' Candidates {} survived.'.format([ obtained[j][0] for j in range(m) if obtained[j][0] in candidates])) else: if message: print(' All the candidates survived.') if force_forward: drop = obtained[randrange(l+1,M)][0] candidates.discard(drop) if message: print(' Drop the candidate \'{}\'.'.format(drop)) elif message: print(' Final winner was not determined.') return obtained elif message: print(' Candidates {} survived.'.format([ obtained[j][0] for j in range(m)])) for n in range(N): while len(votes[n]) > 0 and not votes[n][-1] in candidates: votes[n].pop() if __name__ == '__main__': args = sys.argv if len(args) <= 1: K = 0 else: K = int(args[1]) votes = [] while True: try: votes.append(list(input().strip().upper()[::-1])) except EOFError: break if K == 0: winner = election(votes) print('---') if isinstance(winner, list): print('The candidates \'{}\' are still surviving.'.format(winner)) else: print('The candidate \'{}\' is the Final Winner !!!'.format(winner)) else: win_times = defaultdict(int) for _ in range(K): win_times[election(votes, message=False, force_forward=True)] += 1 result = list(win_times.items()) if len(result) == 1: winner = result[0][0] print('The candidate \'{}\' is the Final Winner !!'.format(winner)) else: print('Final winner was not determined.') print('The winner distribution is: {}'.format(dict(win_times)))
flexible
{ "blob_id": "05764d1cfd9573616fcd6b125280fddf2e5ce7ad", "index": 3712, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef election(votes, message=True, force_forward=False):\n votes = deepcopy(votes)\n N = len(votes)\n for i in range(N):\n obtained = Counter([v[-1] for v in votes if len(v)]).most_common()\n M = len(obtained)\n top = obtained[0]\n if M == 1:\n return top[0]\n accum = [0]\n for ob in obtained[::-1]:\n accum.append(accum[-1] + ob[1])\n accum = accum[:0:-1]\n candidates = {top[0]}\n for m in range(1, M):\n if accum[m] < obtained[m - 1][1]:\n break\n else:\n candidates.add(obtained[m][0])\n else:\n m += 1\n if message:\n print('The {}-th vote: {}'.format(i + 1, obtained))\n if m == 1:\n return top[0]\n elif m >= M:\n l = M - 2\n while l >= 0 and obtained[l][1] == obtained[-1][1]:\n l -= 1\n candidates = {obtained[i][0] for i in range(l + 1)}\n fighting = {obtained[i][0] for i in range(l + 1, M)}\n losers = set()\n for f in fighting:\n tmp_votes = deepcopy(votes)\n tmp_candidates = candidates | {f}\n for n in range(N):\n while len(tmp_votes[n]) > 0 and not tmp_votes[n][-1\n ] in tmp_candidates:\n tmp_votes[n].pop()\n tmp_result = election(tmp_votes, message=False)\n if tmp_result != f and not (isinstance(tmp_result, list) and\n f in dict(tmp_result)):\n losers.add(f)\n candidates |= fighting\n candidates -= losers\n if losers:\n if message:\n print(' Candidates {} survived.'.format([obtained[j][0\n ] for j in range(m) if obtained[j][0] in candidates]))\n else:\n if message:\n print(' All the candidates survived.')\n if force_forward:\n drop = obtained[randrange(l + 1, M)][0]\n candidates.discard(drop)\n if message:\n print(\" Drop the candidate '{}'.\".format(drop))\n elif message:\n print(' Final winner was not determined.')\n return obtained\n elif message:\n print(' Candidates {} survived.'.format([obtained[j][0] for j in\n range(m)]))\n for n in range(N):\n while len(votes[n]) > 0 and not votes[n][-1] in candidates:\n votes[n].pop()\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef election(votes, message=True, force_forward=False):\n votes = deepcopy(votes)\n N = len(votes)\n for i in range(N):\n obtained = Counter([v[-1] for v in votes if len(v)]).most_common()\n M = len(obtained)\n top = obtained[0]\n if M == 1:\n return top[0]\n accum = [0]\n for ob in obtained[::-1]:\n accum.append(accum[-1] + ob[1])\n accum = accum[:0:-1]\n candidates = {top[0]}\n for m in range(1, M):\n if accum[m] < obtained[m - 1][1]:\n break\n else:\n candidates.add(obtained[m][0])\n else:\n m += 1\n if message:\n print('The {}-th vote: {}'.format(i + 1, obtained))\n if m == 1:\n return top[0]\n elif m >= M:\n l = M - 2\n while l >= 0 and obtained[l][1] == obtained[-1][1]:\n l -= 1\n candidates = {obtained[i][0] for i in range(l + 1)}\n fighting = {obtained[i][0] for i in range(l + 1, M)}\n losers = set()\n for f in fighting:\n tmp_votes = deepcopy(votes)\n tmp_candidates = candidates | {f}\n for n in range(N):\n while len(tmp_votes[n]) > 0 and not tmp_votes[n][-1\n ] in tmp_candidates:\n tmp_votes[n].pop()\n tmp_result = election(tmp_votes, message=False)\n if tmp_result != f and not (isinstance(tmp_result, list) and\n f in dict(tmp_result)):\n losers.add(f)\n candidates |= fighting\n candidates -= losers\n if losers:\n if message:\n print(' Candidates {} survived.'.format([obtained[j][0\n ] for j in range(m) if obtained[j][0] in candidates]))\n else:\n if message:\n print(' All the candidates survived.')\n if force_forward:\n drop = obtained[randrange(l + 1, M)][0]\n candidates.discard(drop)\n if message:\n print(\" Drop the candidate '{}'.\".format(drop))\n elif message:\n print(' Final winner was not determined.')\n return obtained\n elif message:\n print(' Candidates {} survived.'.format([obtained[j][0] for j in\n range(m)]))\n for n in range(N):\n while len(votes[n]) > 0 and not votes[n][-1] in candidates:\n votes[n].pop()\n\n\nif __name__ == '__main__':\n args = sys.argv\n if len(args) <= 1:\n K = 0\n else:\n K = int(args[1])\n votes = []\n while True:\n try:\n votes.append(list(input().strip().upper()[::-1]))\n except EOFError:\n break\n if K == 0:\n winner = election(votes)\n print('---')\n if isinstance(winner, list):\n print(\"The candidates '{}' are still surviving.\".format(winner))\n else:\n print(\"The candidate '{}' is the Final Winner !!!\".format(winner))\n else:\n win_times = defaultdict(int)\n for _ in range(K):\n win_times[election(votes, message=False, force_forward=True)] += 1\n result = list(win_times.items())\n if len(result) == 1:\n winner = result[0][0]\n print(\"The candidate '{}' is the Final Winner !!\".format(winner))\n else:\n print('Final winner was not determined.')\n print('The winner distribution is: {}'.format(dict(win_times)))\n", "step-4": "from collections import Counter, defaultdict\nfrom random import randrange\nfrom copy import deepcopy\nimport sys\n\n\ndef election(votes, message=True, force_forward=False):\n votes = deepcopy(votes)\n N = len(votes)\n for i in range(N):\n obtained = Counter([v[-1] for v in votes if len(v)]).most_common()\n M = len(obtained)\n top = obtained[0]\n if M == 1:\n return top[0]\n accum = [0]\n for ob in obtained[::-1]:\n accum.append(accum[-1] + ob[1])\n accum = accum[:0:-1]\n candidates = {top[0]}\n for m in range(1, M):\n if accum[m] < obtained[m - 1][1]:\n break\n else:\n candidates.add(obtained[m][0])\n else:\n m += 1\n if message:\n print('The {}-th vote: {}'.format(i + 1, obtained))\n if m == 1:\n return top[0]\n elif m >= M:\n l = M - 2\n while l >= 0 and obtained[l][1] == obtained[-1][1]:\n l -= 1\n candidates = {obtained[i][0] for i in range(l + 1)}\n fighting = {obtained[i][0] for i in range(l + 1, M)}\n losers = set()\n for f in fighting:\n tmp_votes = deepcopy(votes)\n tmp_candidates = candidates | {f}\n for n in range(N):\n while len(tmp_votes[n]) > 0 and not tmp_votes[n][-1\n ] in tmp_candidates:\n tmp_votes[n].pop()\n tmp_result = election(tmp_votes, message=False)\n if tmp_result != f and not (isinstance(tmp_result, list) and\n f in dict(tmp_result)):\n losers.add(f)\n candidates |= fighting\n candidates -= losers\n if losers:\n if message:\n print(' Candidates {} survived.'.format([obtained[j][0\n ] for j in range(m) if obtained[j][0] in candidates]))\n else:\n if message:\n print(' All the candidates survived.')\n if force_forward:\n drop = obtained[randrange(l + 1, M)][0]\n candidates.discard(drop)\n if message:\n print(\" Drop the candidate '{}'.\".format(drop))\n elif message:\n print(' Final winner was not determined.')\n return obtained\n elif message:\n print(' Candidates {} survived.'.format([obtained[j][0] for j in\n range(m)]))\n for n in range(N):\n while len(votes[n]) > 0 and not votes[n][-1] in candidates:\n votes[n].pop()\n\n\nif __name__ == '__main__':\n args = sys.argv\n if len(args) <= 1:\n K = 0\n else:\n K = int(args[1])\n votes = []\n while True:\n try:\n votes.append(list(input().strip().upper()[::-1]))\n except EOFError:\n break\n if K == 0:\n winner = election(votes)\n print('---')\n if isinstance(winner, list):\n print(\"The candidates '{}' are still surviving.\".format(winner))\n else:\n print(\"The candidate '{}' is the Final Winner !!!\".format(winner))\n else:\n win_times = defaultdict(int)\n for _ in range(K):\n win_times[election(votes, message=False, force_forward=True)] += 1\n result = list(win_times.items())\n if len(result) == 1:\n winner = result[0][0]\n print(\"The candidate '{}' is the Final Winner !!\".format(winner))\n else:\n print('Final winner was not determined.')\n print('The winner distribution is: {}'.format(dict(win_times)))\n", "step-5": "from collections import Counter, defaultdict\nfrom random import randrange\nfrom copy import deepcopy\nimport sys\n\ndef election(votes, message=True, force_forward=False):\n votes = deepcopy(votes)\n N = len(votes)\n for i in range(N):\n obtained = Counter([v[-1] for v in votes if len(v)]).most_common()\n M = len(obtained)\n top = obtained[0]\n if M == 1:\n return top[0]\n\n accum = [0]\n for ob in obtained[::-1]:\n accum.append(accum[-1] + ob[1])\n accum = accum[:0:-1]\n candidates = {top[0]}\n for m in range(1,M):\n if accum[m] < obtained[m-1][1]:\n break\n else:\n candidates.add(obtained[m][0])\n else:\n m += 1\n\n if message:\n print('The {}-th vote: {}'.format(i+1, obtained))\n if m == 1:\n return top[0]\n elif m >= M:\n l = M-2\n while l >= 0 and obtained[l][1] == obtained[-1][1]:\n l -= 1\n candidates = {obtained[i][0] for i in range(l+1)}\n fighting = {obtained[i][0] for i in range(l+1,M)}\n losers = set()\n for f in fighting:\n tmp_votes = deepcopy(votes)\n tmp_candidates = candidates | {f}\n for n in range(N):\n while len(tmp_votes[n]) > 0 and not tmp_votes[n][-1] in tmp_candidates:\n tmp_votes[n].pop()\n tmp_result = election(tmp_votes, message=False)\n if tmp_result != f and not (isinstance(tmp_result,list) and f in dict(tmp_result)):\n losers.add(f)\n candidates |= fighting\n candidates -= losers\n if losers:\n if message:\n print(' Candidates {} survived.'.format([ obtained[j][0] for j in range(m) if obtained[j][0] in candidates])) \n else:\n if message:\n print(' All the candidates survived.')\n if force_forward:\n drop = obtained[randrange(l+1,M)][0]\n candidates.discard(drop)\n if message:\n print(' Drop the candidate \\'{}\\'.'.format(drop))\n elif message:\n print(' Final winner was not determined.')\n return obtained\n elif message:\n print(' Candidates {} survived.'.format([ obtained[j][0] for j in range(m)]))\n \n for n in range(N):\n while len(votes[n]) > 0 and not votes[n][-1] in candidates:\n votes[n].pop()\n\nif __name__ == '__main__':\n args = sys.argv\n if len(args) <= 1:\n K = 0\n else:\n K = int(args[1])\n\n votes = []\n while True:\n try:\n votes.append(list(input().strip().upper()[::-1]))\n except EOFError:\n break\n\n if K == 0:\n winner = election(votes)\n print('---')\n if isinstance(winner, list):\n print('The candidates \\'{}\\' are still surviving.'.format(winner))\n else:\n print('The candidate \\'{}\\' is the Final Winner !!!'.format(winner))\n else:\n win_times = defaultdict(int)\n for _ in range(K):\n win_times[election(votes, message=False, force_forward=True)] += 1\n result = list(win_times.items())\n if len(result) == 1:\n winner = result[0][0]\n print('The candidate \\'{}\\' is the Final Winner !!'.format(winner)) \n else:\n print('Final winner was not determined.')\n print('The winner distribution is: {}'.format(dict(win_times)))\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import pandas as pd def load_covid(): covid = pd.read_csv("https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv") target = 'new_cases' date = 'date' dataset = covid[(covid['location'] == 'World')].copy()[[target, date]] dataset[date] = pd.to_datetime(dataset[date]) dataset.index = dataset[date] dataset['month'] = dataset['date'].dt.month dataset = dataset.drop(columns=['date']) return { 'target': target, 'dataset': dataset, }
normal
{ "blob_id": "e19529dce407da0f1e21f6a3696efcefac9ed040", "index": 8500, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef load_covid():\n covid = pd.read_csv(\n 'https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv'\n )\n target = 'new_cases'\n date = 'date'\n dataset = covid[covid['location'] == 'World'].copy()[[target, date]]\n dataset[date] = pd.to_datetime(dataset[date])\n dataset.index = dataset[date]\n dataset['month'] = dataset['date'].dt.month\n dataset = dataset.drop(columns=['date'])\n return {'target': target, 'dataset': dataset}\n", "step-3": "import pandas as pd\n\n\ndef load_covid():\n covid = pd.read_csv(\n 'https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv'\n )\n target = 'new_cases'\n date = 'date'\n dataset = covid[covid['location'] == 'World'].copy()[[target, date]]\n dataset[date] = pd.to_datetime(dataset[date])\n dataset.index = dataset[date]\n dataset['month'] = dataset['date'].dt.month\n dataset = dataset.drop(columns=['date'])\n return {'target': target, 'dataset': dataset}\n", "step-4": "import pandas as pd\n\n\ndef load_covid():\n covid = pd.read_csv(\"https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv\")\n\n target = 'new_cases'\n date = 'date'\n\n dataset = covid[(covid['location'] == 'World')].copy()[[target, date]]\n dataset[date] = pd.to_datetime(dataset[date])\n dataset.index = dataset[date]\n\n dataset['month'] = dataset['date'].dt.month\n dataset = dataset.drop(columns=['date'])\n\n return {\n 'target': target,\n 'dataset': dataset,\n }\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> {'name': 'Clarico CMS Blocks', 'category': 'Website', 'version': '1.0', 'summary': '13 CMS Building Blocks', 'description': '', 'depends': [ 'snippet_style_1', 'snippet_style_2', 'snippet_style_3', 'snippet_style_4', 'snippet_style_5', 'snippet_style_6', 'snippet_style_7', 'snippet_style_8', 'snippet_style_9', 'snippet_style_10', 'snippet_style_11', 'snippet_style_12', 'snippet_style_13'], 'author': 'Emipro Technologies Pvt. Ltd.', 'website': 'http://www.emiprotechnologies.com', 'installable': True} <|reserved_special_token_1|> { # Theme information 'name' : 'Clarico CMS Blocks', 'category' : 'Website', 'version' : '1.0', 'summary': '13 CMS Building Blocks', 'description': """""", # Dependencies 'depends': [ 'snippet_style_1', 'snippet_style_2', 'snippet_style_3', 'snippet_style_4', 'snippet_style_5', 'snippet_style_6', 'snippet_style_7', 'snippet_style_8', 'snippet_style_9', 'snippet_style_10', 'snippet_style_11', 'snippet_style_12', 'snippet_style_13', ], # Author 'author': 'Emipro Technologies Pvt. Ltd.', 'website': 'http://www.emiprotechnologies.com', # Technical 'installable': True, }
flexible
{ "blob_id": "34f98d4a6a15c9a7b42f237cab204b736dc97136", "index": 1372, "step-1": "<mask token>\n", "step-2": "{'name': 'Clarico CMS Blocks', 'category': 'Website', 'version': '1.0',\n 'summary': '13 CMS Building Blocks', 'description': '', 'depends': [\n 'snippet_style_1', 'snippet_style_2', 'snippet_style_3',\n 'snippet_style_4', 'snippet_style_5', 'snippet_style_6',\n 'snippet_style_7', 'snippet_style_8', 'snippet_style_9',\n 'snippet_style_10', 'snippet_style_11', 'snippet_style_12',\n 'snippet_style_13'], 'author': 'Emipro Technologies Pvt. Ltd.',\n 'website': 'http://www.emiprotechnologies.com', 'installable': True}\n", "step-3": "{\n # Theme information\n 'name' : 'Clarico CMS Blocks',\n 'category' : 'Website',\n 'version' : '1.0',\n 'summary': '13 CMS Building Blocks',\n 'description': \"\"\"\"\"\",\n\n # Dependencies\n 'depends': [\n\t 'snippet_style_1',\n 'snippet_style_2',\n 'snippet_style_3',\n 'snippet_style_4',\n 'snippet_style_5',\n 'snippet_style_6',\n 'snippet_style_7',\n 'snippet_style_8',\n 'snippet_style_9',\n 'snippet_style_10',\n 'snippet_style_11',\n 'snippet_style_12',\n 'snippet_style_13',\n\t\n ],\n\n\n # Author\n 'author': 'Emipro Technologies Pvt. Ltd.',\n 'website': 'http://www.emiprotechnologies.com',\n\n # Technical\n 'installable': True,\n}\n\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> app_name = 'movies' urlpatterns = [path('', views.index, name='index'), path('<int:movie_id>', views.detail, name='detail')] <|reserved_special_token_1|> from django.urls import path from . import views app_name = 'movies' urlpatterns = [path('', views.index, name='index'), path('<int:movie_id>', views.detail, name='detail')] <|reserved_special_token_1|> from django.urls import path from . import views # url configuration for view.index function app_name = 'movies' urlpatterns = [ path('', views.index, name='index'), # represents a root of this app path('<int:movie_id>', views.detail, name='detail') ]
flexible
{ "blob_id": "5aaac757b766b0143ca3ea54d8fc4b8936160ec7", "index": 5090, "step-1": "<mask token>\n", "step-2": "<mask token>\napp_name = 'movies'\nurlpatterns = [path('', views.index, name='index'), path('<int:movie_id>',\n views.detail, name='detail')]\n", "step-3": "from django.urls import path\nfrom . import views\napp_name = 'movies'\nurlpatterns = [path('', views.index, name='index'), path('<int:movie_id>',\n views.detail, name='detail')]\n", "step-4": "from django.urls import path\nfrom . import views\n\n# url configuration for view.index function\napp_name = 'movies'\nurlpatterns = [\n path('', views.index, name='index'), # represents a root of this app\n path('<int:movie_id>', views.detail, name='detail')\n]\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
#from skimage import measure #from svmutil import * import cv2 import numpy as np def inside(r, q): rx, ry, rw, rh = r qx, qy, qw, qh = q return rx > qx and ry > qy and rx + rw < qx + qw and ry + rh < qy + qh def draw_detections(img, rects, thickness = 1): for x, y, w, h in rects: # the HOG detector returns slightly larger rectangles than the real objects. # so we slightly shrink the rectangles to get a nicer output. pad_w, pad_h = int(0.15*w), int(0.05*h) cv2.rectangle(img, (x+pad_w, y+pad_h), (x+w-pad_w, y+h-pad_h), (0, 255, 0), thickness) if __name__ == '__main__': hog = cv2.HOGDescriptor() hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector()) hogParams = {'winStride': (8, 8), 'padding': (32, 32), 'scale': 1.05} cap = cv2.VideoCapture(0) while(True): ret, frame = cap.read() if not ret: break found, w = hog.detectMultiScale(frame, **hogParams) found_filtered = [] for ri, r in enumerate(found): for qi, q in enumerate(found): if ri != qi and inside(r, q): break else: found_filtered.append(r) #draw_detections(frame, found) draw_detections(frame, found_filtered, 3) print('%d (%d) found' % (len(found_filtered), len(found))) key = cv2.waitKey(10) if key == 27: cv2.destroyAllWindows() break cv2.imshow('img', frame) # if cv2.waitKey(1) & 0xFF == ord('q'): # break cap.release() cv2.destroyAllWindows()
normal
{ "blob_id": "f012f862ad064fc168bd5328b97c433164a3a36f", "index": 3742, "step-1": "<mask token>\n\n\ndef draw_detections(img, rects, thickness=1):\n for x, y, w, h in rects:\n pad_w, pad_h = int(0.15 * w), int(0.05 * h)\n cv2.rectangle(img, (x + pad_w, y + pad_h), (x + w - pad_w, y + h -\n pad_h), (0, 255, 0), thickness)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef inside(r, q):\n rx, ry, rw, rh = r\n qx, qy, qw, qh = q\n return rx > qx and ry > qy and rx + rw < qx + qw and ry + rh < qy + qh\n\n\ndef draw_detections(img, rects, thickness=1):\n for x, y, w, h in rects:\n pad_w, pad_h = int(0.15 * w), int(0.05 * h)\n cv2.rectangle(img, (x + pad_w, y + pad_h), (x + w - pad_w, y + h -\n pad_h), (0, 255, 0), thickness)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef inside(r, q):\n rx, ry, rw, rh = r\n qx, qy, qw, qh = q\n return rx > qx and ry > qy and rx + rw < qx + qw and ry + rh < qy + qh\n\n\ndef draw_detections(img, rects, thickness=1):\n for x, y, w, h in rects:\n pad_w, pad_h = int(0.15 * w), int(0.05 * h)\n cv2.rectangle(img, (x + pad_w, y + pad_h), (x + w - pad_w, y + h -\n pad_h), (0, 255, 0), thickness)\n\n\nif __name__ == '__main__':\n hog = cv2.HOGDescriptor()\n hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())\n hogParams = {'winStride': (8, 8), 'padding': (32, 32), 'scale': 1.05}\n cap = cv2.VideoCapture(0)\n while True:\n ret, frame = cap.read()\n if not ret:\n break\n found, w = hog.detectMultiScale(frame, **hogParams)\n found_filtered = []\n for ri, r in enumerate(found):\n for qi, q in enumerate(found):\n if ri != qi and inside(r, q):\n break\n else:\n found_filtered.append(r)\n draw_detections(frame, found_filtered, 3)\n print('%d (%d) found' % (len(found_filtered), len(found)))\n key = cv2.waitKey(10)\n if key == 27:\n cv2.destroyAllWindows()\n break\n cv2.imshow('img', frame)\n cap.release()\n cv2.destroyAllWindows()\n", "step-4": "import cv2\nimport numpy as np\n\n\ndef inside(r, q):\n rx, ry, rw, rh = r\n qx, qy, qw, qh = q\n return rx > qx and ry > qy and rx + rw < qx + qw and ry + rh < qy + qh\n\n\ndef draw_detections(img, rects, thickness=1):\n for x, y, w, h in rects:\n pad_w, pad_h = int(0.15 * w), int(0.05 * h)\n cv2.rectangle(img, (x + pad_w, y + pad_h), (x + w - pad_w, y + h -\n pad_h), (0, 255, 0), thickness)\n\n\nif __name__ == '__main__':\n hog = cv2.HOGDescriptor()\n hog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())\n hogParams = {'winStride': (8, 8), 'padding': (32, 32), 'scale': 1.05}\n cap = cv2.VideoCapture(0)\n while True:\n ret, frame = cap.read()\n if not ret:\n break\n found, w = hog.detectMultiScale(frame, **hogParams)\n found_filtered = []\n for ri, r in enumerate(found):\n for qi, q in enumerate(found):\n if ri != qi and inside(r, q):\n break\n else:\n found_filtered.append(r)\n draw_detections(frame, found_filtered, 3)\n print('%d (%d) found' % (len(found_filtered), len(found)))\n key = cv2.waitKey(10)\n if key == 27:\n cv2.destroyAllWindows()\n break\n cv2.imshow('img', frame)\n cap.release()\n cv2.destroyAllWindows()\n", "step-5": "#from skimage import measure\n#from svmutil import *\nimport cv2\nimport numpy as np \n\ndef inside(r, q):\n\trx, ry, rw, rh = r\n\tqx, qy, qw, qh = q\n\treturn rx > qx and ry > qy and rx + rw < qx + qw and ry + rh < qy + qh\n\ndef draw_detections(img, rects, thickness = 1):\n\tfor x, y, w, h in rects:\n # the HOG detector returns slightly larger rectangles than the real objects.\n # so we slightly shrink the rectangles to get a nicer output.\n\t\tpad_w, pad_h = int(0.15*w), int(0.05*h)\n\t\tcv2.rectangle(img, (x+pad_w, y+pad_h), (x+w-pad_w, y+h-pad_h), (0, 255, 0), thickness)\n\nif __name__ == '__main__': \n\thog = cv2.HOGDescriptor()\n\thog.setSVMDetector(cv2.HOGDescriptor_getDefaultPeopleDetector())\n\thogParams = {'winStride': (8, 8), 'padding': (32, 32), 'scale': 1.05}\n\n\tcap = cv2.VideoCapture(0)\n\n\twhile(True):\n\n\t\tret, frame = cap.read()\n\t\tif not ret:\n\t\t\tbreak\n\n\t\tfound, w = hog.detectMultiScale(frame, **hogParams)\n\t\tfound_filtered = []\n\t\tfor ri, r in enumerate(found):\n\t\t\tfor qi, q in enumerate(found):\n\t\t\t\tif ri != qi and inside(r, q):\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tfound_filtered.append(r)\n\n\t\t#draw_detections(frame, found)\n\t\tdraw_detections(frame, found_filtered, 3)\n\t\tprint('%d (%d) found' % (len(found_filtered), len(found)))\n\t\tkey = cv2.waitKey(10)\n\t\tif key == 27:\n\t\t\tcv2.destroyAllWindows()\n\t\t\tbreak\n\n\t\tcv2.imshow('img', frame)\n#\t\tif cv2.waitKey(1) & 0xFF == ord('q'):\n#\t\t\tbreak\n\t\n\tcap.release()\n\tcv2.destroyAllWindows()\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
<|reserved_special_token_0|> def sumInput(text): f = open(text, 'r') sum = 0 count = 1 for line in f: count += 1 line = line.strip() if line[0] == '+': sum += int(line[1:]) else: sum -= int(line[1:]) f.close() return sum <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def sumInput(text): f = open(text, 'r') sum = 0 count = 1 for line in f: count += 1 line = line.strip() if line[0] == '+': sum += int(line[1:]) else: sum -= int(line[1:]) f.close() return sum def main(): print(sumInput('input.txt')) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def sumInput(text): f = open(text, 'r') sum = 0 count = 1 for line in f: count += 1 line = line.strip() if line[0] == '+': sum += int(line[1:]) else: sum -= int(line[1:]) f.close() return sum def main(): print(sumInput('input.txt')) if __name__ == '__main__': main() <|reserved_special_token_1|> import sys def sumInput(text): f = open(text, 'r') sum = 0 count = 1 for line in f: count += 1 line = line.strip() if line[0] == '+': sum += int(line[1:]) else: sum -= int(line[1:]) f.close() return sum def main(): print(sumInput('input.txt')) if __name__ == '__main__': main() <|reserved_special_token_1|> #!/Library/Frameworks/Python.framework/Versions/3.7/bin/python3 import sys def sumInput(text): f = open(text, 'r') sum = 0 count = 1 for line in f: count += 1 line = line.strip() if (line[0] == '+'): sum += int(line[1:]) else: sum -= int(line[1:]) f.close() return sum def main(): print(sumInput('input.txt')) if __name__ == "__main__": main()
flexible
{ "blob_id": "c0d71d970b2632dbf182a5ee8bad27d3e41578f6", "index": 208, "step-1": "<mask token>\n\n\ndef sumInput(text):\n f = open(text, 'r')\n sum = 0\n count = 1\n for line in f:\n count += 1\n line = line.strip()\n if line[0] == '+':\n sum += int(line[1:])\n else:\n sum -= int(line[1:])\n f.close()\n return sum\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef sumInput(text):\n f = open(text, 'r')\n sum = 0\n count = 1\n for line in f:\n count += 1\n line = line.strip()\n if line[0] == '+':\n sum += int(line[1:])\n else:\n sum -= int(line[1:])\n f.close()\n return sum\n\n\ndef main():\n print(sumInput('input.txt'))\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef sumInput(text):\n f = open(text, 'r')\n sum = 0\n count = 1\n for line in f:\n count += 1\n line = line.strip()\n if line[0] == '+':\n sum += int(line[1:])\n else:\n sum -= int(line[1:])\n f.close()\n return sum\n\n\ndef main():\n print(sumInput('input.txt'))\n\n\nif __name__ == '__main__':\n main()\n", "step-4": "import sys\n\n\ndef sumInput(text):\n f = open(text, 'r')\n sum = 0\n count = 1\n for line in f:\n count += 1\n line = line.strip()\n if line[0] == '+':\n sum += int(line[1:])\n else:\n sum -= int(line[1:])\n f.close()\n return sum\n\n\ndef main():\n print(sumInput('input.txt'))\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "#!/Library/Frameworks/Python.framework/Versions/3.7/bin/python3\n\nimport sys\n\ndef sumInput(text):\n f = open(text, 'r')\n sum = 0\n count = 1\n for line in f:\n count += 1\n line = line.strip()\n if (line[0] == '+'):\n sum += int(line[1:])\n else:\n sum -= int(line[1:])\n f.close()\n return sum\n\ndef main():\n print(sumInput('input.txt'))\n\nif __name__ == \"__main__\":\n main()\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
def sum_numbers(numbers=None): sum = 0 if numbers == None: for number in range(1, 101): sum += number return sum for number in numbers: sum += number return sum
normal
{ "blob_id": "a85d06d72b053b0ef6cb6ec2ba465bfb8975b28e", "index": 3879, "step-1": "<mask token>\n", "step-2": "def sum_numbers(numbers=None):\n sum = 0\n if numbers == None:\n for number in range(1, 101):\n sum += number\n return sum\n for number in numbers:\n sum += number\n return sum\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
<|reserved_special_token_0|> def main(): try: tempfile = tempfile_name() get_datafile(tempfile) except: print('Could not retrieve datafile ' + tempfile) exit(-1) et = get_yesterdays_et(tempfile) if et == -1.0: print('No et found for ' + datestr) exit(-1) new_water_level = int(et / base_et * 100) print('New Water Level will be %d' % new_water_level) status = set_os_et(new_water_level) notify(status) exit(0) def yesterday(): dt = datetime.datetime.now(datetime.timezone.utc) local_timezone = tzlocal.get_localzone() dt = dt.astimezone(local_timezone) delta = datetime.timedelta(1) dt = dt - delta return datetime.datetime.strftime(dt, '%-m/%-d/%Y') def get_yesterdays_et(tempfile): datestr = yesterday() et = -1.0 with open(tempfile, 'r') as tmp: rdr = csv.reader(tmp) for r in rdr: if r[1] == datestr: et = float(r[3]) print('Found et for ' + datestr + ': ' + str(et)) os.remove(tempfile) return et def tempfile_name(): return '/tmp/get_et_rate_' + str(datetime.datetime.now().timestamp() ) + '.csv' def get_datafile(tempfile): global uri urllib.request.urlretrieve(uri, tempfile) def get_password(): try: pw = os.environ['OPENSPRINKLER_PASSWORD'] except: print( 'OpenSprinkler password not set in env variable OPENSPRINKLER_PASSWORD' ) exit(-1) pw = pw.encode('ascii') m = hashlib.md5() m.update(pw) return m.hexdigest() def set_os_et(new_water_level): hash = get_password() status = '' r = requests.get('http://192.168.1.13/jo?pw=' + hash) res = json.loads(r.text) status = status + 'Old water level: %s\n' % {res['wl']} r = requests.get('http://192.168.1.13/co?pw=%s&o23=%d' % (hash, new_water_level)) r = requests.get('http://192.168.1.13/jo?pw=' + hash) res = json.loads(r.text) status = status + 'Successfully set to new value %s\n' % {res['wl']} return status def notify(status): session = boto3.Session(profile_name='trbryan') sns = session.client('sns') response = sns.publish(TopicArn= 'arn:aws:sns:us-west-2:509611857908:opensprinkler_et_update', Message=status, Subject='Daily OpenSprinkler ET Adjustment', MessageStructure='string') <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def main(): try: tempfile = tempfile_name() get_datafile(tempfile) except: print('Could not retrieve datafile ' + tempfile) exit(-1) et = get_yesterdays_et(tempfile) if et == -1.0: print('No et found for ' + datestr) exit(-1) new_water_level = int(et / base_et * 100) print('New Water Level will be %d' % new_water_level) status = set_os_et(new_water_level) notify(status) exit(0) def yesterday(): dt = datetime.datetime.now(datetime.timezone.utc) local_timezone = tzlocal.get_localzone() dt = dt.astimezone(local_timezone) delta = datetime.timedelta(1) dt = dt - delta return datetime.datetime.strftime(dt, '%-m/%-d/%Y') def get_yesterdays_et(tempfile): datestr = yesterday() et = -1.0 with open(tempfile, 'r') as tmp: rdr = csv.reader(tmp) for r in rdr: if r[1] == datestr: et = float(r[3]) print('Found et for ' + datestr + ': ' + str(et)) os.remove(tempfile) return et def tempfile_name(): return '/tmp/get_et_rate_' + str(datetime.datetime.now().timestamp() ) + '.csv' def get_datafile(tempfile): global uri urllib.request.urlretrieve(uri, tempfile) def get_password(): try: pw = os.environ['OPENSPRINKLER_PASSWORD'] except: print( 'OpenSprinkler password not set in env variable OPENSPRINKLER_PASSWORD' ) exit(-1) pw = pw.encode('ascii') m = hashlib.md5() m.update(pw) return m.hexdigest() def set_os_et(new_water_level): hash = get_password() status = '' r = requests.get('http://192.168.1.13/jo?pw=' + hash) res = json.loads(r.text) status = status + 'Old water level: %s\n' % {res['wl']} r = requests.get('http://192.168.1.13/co?pw=%s&o23=%d' % (hash, new_water_level)) r = requests.get('http://192.168.1.13/jo?pw=' + hash) res = json.loads(r.text) status = status + 'Successfully set to new value %s\n' % {res['wl']} return status def notify(status): session = boto3.Session(profile_name='trbryan') sns = session.client('sns') response = sns.publish(TopicArn= 'arn:aws:sns:us-west-2:509611857908:opensprinkler_et_update', Message=status, Subject='Daily OpenSprinkler ET Adjustment', MessageStructure='string') if __name__ == '__main__': main() <|reserved_special_token_1|> <|reserved_special_token_0|> uri = 'ftp://ftpcimis.water.ca.gov/pub2/daily/daily107.csv' base_et = 0.15 def main(): try: tempfile = tempfile_name() get_datafile(tempfile) except: print('Could not retrieve datafile ' + tempfile) exit(-1) et = get_yesterdays_et(tempfile) if et == -1.0: print('No et found for ' + datestr) exit(-1) new_water_level = int(et / base_et * 100) print('New Water Level will be %d' % new_water_level) status = set_os_et(new_water_level) notify(status) exit(0) def yesterday(): dt = datetime.datetime.now(datetime.timezone.utc) local_timezone = tzlocal.get_localzone() dt = dt.astimezone(local_timezone) delta = datetime.timedelta(1) dt = dt - delta return datetime.datetime.strftime(dt, '%-m/%-d/%Y') def get_yesterdays_et(tempfile): datestr = yesterday() et = -1.0 with open(tempfile, 'r') as tmp: rdr = csv.reader(tmp) for r in rdr: if r[1] == datestr: et = float(r[3]) print('Found et for ' + datestr + ': ' + str(et)) os.remove(tempfile) return et def tempfile_name(): return '/tmp/get_et_rate_' + str(datetime.datetime.now().timestamp() ) + '.csv' def get_datafile(tempfile): global uri urllib.request.urlretrieve(uri, tempfile) def get_password(): try: pw = os.environ['OPENSPRINKLER_PASSWORD'] except: print( 'OpenSprinkler password not set in env variable OPENSPRINKLER_PASSWORD' ) exit(-1) pw = pw.encode('ascii') m = hashlib.md5() m.update(pw) return m.hexdigest() def set_os_et(new_water_level): hash = get_password() status = '' r = requests.get('http://192.168.1.13/jo?pw=' + hash) res = json.loads(r.text) status = status + 'Old water level: %s\n' % {res['wl']} r = requests.get('http://192.168.1.13/co?pw=%s&o23=%d' % (hash, new_water_level)) r = requests.get('http://192.168.1.13/jo?pw=' + hash) res = json.loads(r.text) status = status + 'Successfully set to new value %s\n' % {res['wl']} return status def notify(status): session = boto3.Session(profile_name='trbryan') sns = session.client('sns') response = sns.publish(TopicArn= 'arn:aws:sns:us-west-2:509611857908:opensprinkler_et_update', Message=status, Subject='Daily OpenSprinkler ET Adjustment', MessageStructure='string') if __name__ == '__main__': main() <|reserved_special_token_1|> import os, sys, datetime, pytz, tzlocal, urllib.request, requests, csv, hashlib, json, boto3 uri = 'ftp://ftpcimis.water.ca.gov/pub2/daily/daily107.csv' base_et = 0.15 def main(): try: tempfile = tempfile_name() get_datafile(tempfile) except: print('Could not retrieve datafile ' + tempfile) exit(-1) et = get_yesterdays_et(tempfile) if et == -1.0: print('No et found for ' + datestr) exit(-1) new_water_level = int(et / base_et * 100) print('New Water Level will be %d' % new_water_level) status = set_os_et(new_water_level) notify(status) exit(0) def yesterday(): dt = datetime.datetime.now(datetime.timezone.utc) local_timezone = tzlocal.get_localzone() dt = dt.astimezone(local_timezone) delta = datetime.timedelta(1) dt = dt - delta return datetime.datetime.strftime(dt, '%-m/%-d/%Y') def get_yesterdays_et(tempfile): datestr = yesterday() et = -1.0 with open(tempfile, 'r') as tmp: rdr = csv.reader(tmp) for r in rdr: if r[1] == datestr: et = float(r[3]) print('Found et for ' + datestr + ': ' + str(et)) os.remove(tempfile) return et def tempfile_name(): return '/tmp/get_et_rate_' + str(datetime.datetime.now().timestamp() ) + '.csv' def get_datafile(tempfile): global uri urllib.request.urlretrieve(uri, tempfile) def get_password(): try: pw = os.environ['OPENSPRINKLER_PASSWORD'] except: print( 'OpenSprinkler password not set in env variable OPENSPRINKLER_PASSWORD' ) exit(-1) pw = pw.encode('ascii') m = hashlib.md5() m.update(pw) return m.hexdigest() def set_os_et(new_water_level): hash = get_password() status = '' r = requests.get('http://192.168.1.13/jo?pw=' + hash) res = json.loads(r.text) status = status + 'Old water level: %s\n' % {res['wl']} r = requests.get('http://192.168.1.13/co?pw=%s&o23=%d' % (hash, new_water_level)) r = requests.get('http://192.168.1.13/jo?pw=' + hash) res = json.loads(r.text) status = status + 'Successfully set to new value %s\n' % {res['wl']} return status def notify(status): session = boto3.Session(profile_name='trbryan') sns = session.client('sns') response = sns.publish(TopicArn= 'arn:aws:sns:us-west-2:509611857908:opensprinkler_et_update', Message=status, Subject='Daily OpenSprinkler ET Adjustment', MessageStructure='string') if __name__ == '__main__': main() <|reserved_special_token_1|> import os, sys, datetime, pytz, tzlocal, urllib.request, requests, csv, hashlib, json, boto3 uri = 'ftp://ftpcimis.water.ca.gov/pub2/daily/daily107.csv' #Station 107 is Santa Barbara base_et = 0.15 def main(): try: tempfile = tempfile_name() get_datafile(tempfile) except: print("Could not retrieve datafile " + tempfile) exit(-1) et = get_yesterdays_et(tempfile) if et == -1.0: print("No et found for " + datestr) exit(-1) new_water_level = int(et/base_et * 100) print("New Water Level will be %d" % new_water_level) status = set_os_et(new_water_level) notify(status) exit(0) def yesterday(): dt = datetime.datetime.now(datetime.timezone.utc) local_timezone = tzlocal.get_localzone() dt = dt.astimezone(local_timezone) delta = datetime.timedelta(1) dt = dt - delta return datetime.datetime.strftime(dt, "%-m/%-d/%Y") def get_yesterdays_et(tempfile): datestr = yesterday() et = -1.0 with open(tempfile, 'r') as tmp: rdr = csv.reader(tmp) for r in rdr: if r[1] == datestr: et = float(r[3]) print("Found et for " + datestr + ": " + str(et)) os.remove(tempfile) return et def tempfile_name(): return '/tmp/get_et_rate_' + str(datetime.datetime.now().timestamp()) + '.csv' def get_datafile(tempfile): global uri urllib.request.urlretrieve(uri, tempfile) def get_password(): try: pw = os.environ['OPENSPRINKLER_PASSWORD'] except: print("OpenSprinkler password not set in env variable OPENSPRINKLER_PASSWORD") exit(-1) pw = pw.encode('ascii') m = hashlib.md5() m.update(pw) return m.hexdigest() def set_os_et(new_water_level): hash = get_password() status = "" r = requests.get('http://192.168.1.13/jo?pw=' + hash) res = json.loads(r.text) status = status + "Old water level: %s\n" % {res['wl']} r = requests.get('http://192.168.1.13/co?pw=%s&o23=%d' % (hash, new_water_level)) r = requests.get('http://192.168.1.13/jo?pw=' + hash) res = json.loads(r.text) status = status + "Successfully set to new value %s\n" % {res['wl']} return status def notify(status): session = boto3.Session(profile_name='trbryan') sns = session.client('sns') response = sns.publish( TopicArn='arn:aws:sns:us-west-2:509611857908:opensprinkler_et_update', Message=status, Subject='Daily OpenSprinkler ET Adjustment', MessageStructure='string', ) if __name__ == "__main__": main()
flexible
{ "blob_id": "4d82e68faa3102fc2949fd805588504b7d874589", "index": 5457, "step-1": "<mask token>\n\n\ndef main():\n try:\n tempfile = tempfile_name()\n get_datafile(tempfile)\n except:\n print('Could not retrieve datafile ' + tempfile)\n exit(-1)\n et = get_yesterdays_et(tempfile)\n if et == -1.0:\n print('No et found for ' + datestr)\n exit(-1)\n new_water_level = int(et / base_et * 100)\n print('New Water Level will be %d' % new_water_level)\n status = set_os_et(new_water_level)\n notify(status)\n exit(0)\n\n\ndef yesterday():\n dt = datetime.datetime.now(datetime.timezone.utc)\n local_timezone = tzlocal.get_localzone()\n dt = dt.astimezone(local_timezone)\n delta = datetime.timedelta(1)\n dt = dt - delta\n return datetime.datetime.strftime(dt, '%-m/%-d/%Y')\n\n\ndef get_yesterdays_et(tempfile):\n datestr = yesterday()\n et = -1.0\n with open(tempfile, 'r') as tmp:\n rdr = csv.reader(tmp)\n for r in rdr:\n if r[1] == datestr:\n et = float(r[3])\n print('Found et for ' + datestr + ': ' + str(et))\n os.remove(tempfile)\n return et\n\n\ndef tempfile_name():\n return '/tmp/get_et_rate_' + str(datetime.datetime.now().timestamp()\n ) + '.csv'\n\n\ndef get_datafile(tempfile):\n global uri\n urllib.request.urlretrieve(uri, tempfile)\n\n\ndef get_password():\n try:\n pw = os.environ['OPENSPRINKLER_PASSWORD']\n except:\n print(\n 'OpenSprinkler password not set in env variable OPENSPRINKLER_PASSWORD'\n )\n exit(-1)\n pw = pw.encode('ascii')\n m = hashlib.md5()\n m.update(pw)\n return m.hexdigest()\n\n\ndef set_os_et(new_water_level):\n hash = get_password()\n status = ''\n r = requests.get('http://192.168.1.13/jo?pw=' + hash)\n res = json.loads(r.text)\n status = status + 'Old water level: %s\\n' % {res['wl']}\n r = requests.get('http://192.168.1.13/co?pw=%s&o23=%d' % (hash,\n new_water_level))\n r = requests.get('http://192.168.1.13/jo?pw=' + hash)\n res = json.loads(r.text)\n status = status + 'Successfully set to new value %s\\n' % {res['wl']}\n return status\n\n\ndef notify(status):\n session = boto3.Session(profile_name='trbryan')\n sns = session.client('sns')\n response = sns.publish(TopicArn=\n 'arn:aws:sns:us-west-2:509611857908:opensprinkler_et_update',\n Message=status, Subject='Daily OpenSprinkler ET Adjustment',\n MessageStructure='string')\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef main():\n try:\n tempfile = tempfile_name()\n get_datafile(tempfile)\n except:\n print('Could not retrieve datafile ' + tempfile)\n exit(-1)\n et = get_yesterdays_et(tempfile)\n if et == -1.0:\n print('No et found for ' + datestr)\n exit(-1)\n new_water_level = int(et / base_et * 100)\n print('New Water Level will be %d' % new_water_level)\n status = set_os_et(new_water_level)\n notify(status)\n exit(0)\n\n\ndef yesterday():\n dt = datetime.datetime.now(datetime.timezone.utc)\n local_timezone = tzlocal.get_localzone()\n dt = dt.astimezone(local_timezone)\n delta = datetime.timedelta(1)\n dt = dt - delta\n return datetime.datetime.strftime(dt, '%-m/%-d/%Y')\n\n\ndef get_yesterdays_et(tempfile):\n datestr = yesterday()\n et = -1.0\n with open(tempfile, 'r') as tmp:\n rdr = csv.reader(tmp)\n for r in rdr:\n if r[1] == datestr:\n et = float(r[3])\n print('Found et for ' + datestr + ': ' + str(et))\n os.remove(tempfile)\n return et\n\n\ndef tempfile_name():\n return '/tmp/get_et_rate_' + str(datetime.datetime.now().timestamp()\n ) + '.csv'\n\n\ndef get_datafile(tempfile):\n global uri\n urllib.request.urlretrieve(uri, tempfile)\n\n\ndef get_password():\n try:\n pw = os.environ['OPENSPRINKLER_PASSWORD']\n except:\n print(\n 'OpenSprinkler password not set in env variable OPENSPRINKLER_PASSWORD'\n )\n exit(-1)\n pw = pw.encode('ascii')\n m = hashlib.md5()\n m.update(pw)\n return m.hexdigest()\n\n\ndef set_os_et(new_water_level):\n hash = get_password()\n status = ''\n r = requests.get('http://192.168.1.13/jo?pw=' + hash)\n res = json.loads(r.text)\n status = status + 'Old water level: %s\\n' % {res['wl']}\n r = requests.get('http://192.168.1.13/co?pw=%s&o23=%d' % (hash,\n new_water_level))\n r = requests.get('http://192.168.1.13/jo?pw=' + hash)\n res = json.loads(r.text)\n status = status + 'Successfully set to new value %s\\n' % {res['wl']}\n return status\n\n\ndef notify(status):\n session = boto3.Session(profile_name='trbryan')\n sns = session.client('sns')\n response = sns.publish(TopicArn=\n 'arn:aws:sns:us-west-2:509611857908:opensprinkler_et_update',\n Message=status, Subject='Daily OpenSprinkler ET Adjustment',\n MessageStructure='string')\n\n\nif __name__ == '__main__':\n main()\n", "step-3": "<mask token>\nuri = 'ftp://ftpcimis.water.ca.gov/pub2/daily/daily107.csv'\nbase_et = 0.15\n\n\ndef main():\n try:\n tempfile = tempfile_name()\n get_datafile(tempfile)\n except:\n print('Could not retrieve datafile ' + tempfile)\n exit(-1)\n et = get_yesterdays_et(tempfile)\n if et == -1.0:\n print('No et found for ' + datestr)\n exit(-1)\n new_water_level = int(et / base_et * 100)\n print('New Water Level will be %d' % new_water_level)\n status = set_os_et(new_water_level)\n notify(status)\n exit(0)\n\n\ndef yesterday():\n dt = datetime.datetime.now(datetime.timezone.utc)\n local_timezone = tzlocal.get_localzone()\n dt = dt.astimezone(local_timezone)\n delta = datetime.timedelta(1)\n dt = dt - delta\n return datetime.datetime.strftime(dt, '%-m/%-d/%Y')\n\n\ndef get_yesterdays_et(tempfile):\n datestr = yesterday()\n et = -1.0\n with open(tempfile, 'r') as tmp:\n rdr = csv.reader(tmp)\n for r in rdr:\n if r[1] == datestr:\n et = float(r[3])\n print('Found et for ' + datestr + ': ' + str(et))\n os.remove(tempfile)\n return et\n\n\ndef tempfile_name():\n return '/tmp/get_et_rate_' + str(datetime.datetime.now().timestamp()\n ) + '.csv'\n\n\ndef get_datafile(tempfile):\n global uri\n urllib.request.urlretrieve(uri, tempfile)\n\n\ndef get_password():\n try:\n pw = os.environ['OPENSPRINKLER_PASSWORD']\n except:\n print(\n 'OpenSprinkler password not set in env variable OPENSPRINKLER_PASSWORD'\n )\n exit(-1)\n pw = pw.encode('ascii')\n m = hashlib.md5()\n m.update(pw)\n return m.hexdigest()\n\n\ndef set_os_et(new_water_level):\n hash = get_password()\n status = ''\n r = requests.get('http://192.168.1.13/jo?pw=' + hash)\n res = json.loads(r.text)\n status = status + 'Old water level: %s\\n' % {res['wl']}\n r = requests.get('http://192.168.1.13/co?pw=%s&o23=%d' % (hash,\n new_water_level))\n r = requests.get('http://192.168.1.13/jo?pw=' + hash)\n res = json.loads(r.text)\n status = status + 'Successfully set to new value %s\\n' % {res['wl']}\n return status\n\n\ndef notify(status):\n session = boto3.Session(profile_name='trbryan')\n sns = session.client('sns')\n response = sns.publish(TopicArn=\n 'arn:aws:sns:us-west-2:509611857908:opensprinkler_et_update',\n Message=status, Subject='Daily OpenSprinkler ET Adjustment',\n MessageStructure='string')\n\n\nif __name__ == '__main__':\n main()\n", "step-4": "import os, sys, datetime, pytz, tzlocal, urllib.request, requests, csv, hashlib, json, boto3\nuri = 'ftp://ftpcimis.water.ca.gov/pub2/daily/daily107.csv'\nbase_et = 0.15\n\n\ndef main():\n try:\n tempfile = tempfile_name()\n get_datafile(tempfile)\n except:\n print('Could not retrieve datafile ' + tempfile)\n exit(-1)\n et = get_yesterdays_et(tempfile)\n if et == -1.0:\n print('No et found for ' + datestr)\n exit(-1)\n new_water_level = int(et / base_et * 100)\n print('New Water Level will be %d' % new_water_level)\n status = set_os_et(new_water_level)\n notify(status)\n exit(0)\n\n\ndef yesterday():\n dt = datetime.datetime.now(datetime.timezone.utc)\n local_timezone = tzlocal.get_localzone()\n dt = dt.astimezone(local_timezone)\n delta = datetime.timedelta(1)\n dt = dt - delta\n return datetime.datetime.strftime(dt, '%-m/%-d/%Y')\n\n\ndef get_yesterdays_et(tempfile):\n datestr = yesterday()\n et = -1.0\n with open(tempfile, 'r') as tmp:\n rdr = csv.reader(tmp)\n for r in rdr:\n if r[1] == datestr:\n et = float(r[3])\n print('Found et for ' + datestr + ': ' + str(et))\n os.remove(tempfile)\n return et\n\n\ndef tempfile_name():\n return '/tmp/get_et_rate_' + str(datetime.datetime.now().timestamp()\n ) + '.csv'\n\n\ndef get_datafile(tempfile):\n global uri\n urllib.request.urlretrieve(uri, tempfile)\n\n\ndef get_password():\n try:\n pw = os.environ['OPENSPRINKLER_PASSWORD']\n except:\n print(\n 'OpenSprinkler password not set in env variable OPENSPRINKLER_PASSWORD'\n )\n exit(-1)\n pw = pw.encode('ascii')\n m = hashlib.md5()\n m.update(pw)\n return m.hexdigest()\n\n\ndef set_os_et(new_water_level):\n hash = get_password()\n status = ''\n r = requests.get('http://192.168.1.13/jo?pw=' + hash)\n res = json.loads(r.text)\n status = status + 'Old water level: %s\\n' % {res['wl']}\n r = requests.get('http://192.168.1.13/co?pw=%s&o23=%d' % (hash,\n new_water_level))\n r = requests.get('http://192.168.1.13/jo?pw=' + hash)\n res = json.loads(r.text)\n status = status + 'Successfully set to new value %s\\n' % {res['wl']}\n return status\n\n\ndef notify(status):\n session = boto3.Session(profile_name='trbryan')\n sns = session.client('sns')\n response = sns.publish(TopicArn=\n 'arn:aws:sns:us-west-2:509611857908:opensprinkler_et_update',\n Message=status, Subject='Daily OpenSprinkler ET Adjustment',\n MessageStructure='string')\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "import os, sys, datetime, pytz, tzlocal, urllib.request, requests, csv, hashlib, json, boto3\n\nuri = 'ftp://ftpcimis.water.ca.gov/pub2/daily/daily107.csv' #Station 107 is Santa Barbara\nbase_et = 0.15\n\n\ndef main():\n try:\n tempfile = tempfile_name()\n get_datafile(tempfile)\n except:\n print(\"Could not retrieve datafile \" + tempfile)\n exit(-1)\n\n et = get_yesterdays_et(tempfile)\n if et == -1.0:\n print(\"No et found for \" + datestr)\n exit(-1)\n\n new_water_level = int(et/base_et * 100)\n print(\"New Water Level will be %d\" % new_water_level)\n status = set_os_et(new_water_level)\n notify(status)\n exit(0)\n\ndef yesterday():\n dt = datetime.datetime.now(datetime.timezone.utc)\n local_timezone = tzlocal.get_localzone()\n dt = dt.astimezone(local_timezone)\n delta = datetime.timedelta(1)\n dt = dt - delta\n return datetime.datetime.strftime(dt, \"%-m/%-d/%Y\")\n\ndef get_yesterdays_et(tempfile):\n datestr = yesterday()\n et = -1.0\n with open(tempfile, 'r') as tmp:\n rdr = csv.reader(tmp)\n for r in rdr:\n if r[1] == datestr:\n et = float(r[3])\n print(\"Found et for \" + datestr + \": \" + str(et))\n os.remove(tempfile)\n return et\n\ndef tempfile_name():\n return '/tmp/get_et_rate_' + str(datetime.datetime.now().timestamp()) + '.csv'\n\ndef get_datafile(tempfile):\n global uri\n urllib.request.urlretrieve(uri, tempfile)\n\ndef get_password():\n try:\n pw = os.environ['OPENSPRINKLER_PASSWORD']\n except:\n print(\"OpenSprinkler password not set in env variable OPENSPRINKLER_PASSWORD\")\n exit(-1)\n pw = pw.encode('ascii')\n m = hashlib.md5()\n m.update(pw)\n return m.hexdigest()\n\ndef set_os_et(new_water_level):\n hash = get_password()\n status = \"\"\n r = requests.get('http://192.168.1.13/jo?pw=' + hash)\n res = json.loads(r.text)\n status = status + \"Old water level: %s\\n\" % {res['wl']}\n r = requests.get('http://192.168.1.13/co?pw=%s&o23=%d' % (hash, new_water_level))\n r = requests.get('http://192.168.1.13/jo?pw=' + hash)\n res = json.loads(r.text)\n status = status + \"Successfully set to new value %s\\n\" % {res['wl']}\n return status\n\ndef notify(status):\n session = boto3.Session(profile_name='trbryan')\n sns = session.client('sns')\n response = sns.publish(\n TopicArn='arn:aws:sns:us-west-2:509611857908:opensprinkler_et_update',\n Message=status,\n Subject='Daily OpenSprinkler ET Adjustment',\n MessageStructure='string',\n )\n\n\nif __name__ == \"__main__\": main()", "step-ids": [ 8, 9, 10, 11, 12 ] }
[ 8, 9, 10, 11, 12 ]
# _*_ coding: utf-8 _*_ from service import service_logger from service.TaskService import TaskService class ApiException(Exception): def __init__(self, message, code=400, data=None): Exception.__init__(self, message) self.code = code self.msg = message self.data = data def __str__(self): return self.msg def to_dict(self): res = dict(self.data or ()) res['msg'] = self.msg res['code'] = self.code return res def error_handle(msg='', data=None): service_logger.error(data={"msg": msg, "data": data}) raise ApiException(msg)
normal
{ "blob_id": "0ac14b023c51bfd1cf99bd2d991baa30a671e066", "index": 9994, "step-1": "<mask token>\n\n\nclass ApiException(Exception):\n\n def __init__(self, message, code=400, data=None):\n Exception.__init__(self, message)\n self.code = code\n self.msg = message\n self.data = data\n\n def __str__(self):\n return self.msg\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass ApiException(Exception):\n\n def __init__(self, message, code=400, data=None):\n Exception.__init__(self, message)\n self.code = code\n self.msg = message\n self.data = data\n\n def __str__(self):\n return self.msg\n\n def to_dict(self):\n res = dict(self.data or ())\n res['msg'] = self.msg\n res['code'] = self.code\n return res\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass ApiException(Exception):\n\n def __init__(self, message, code=400, data=None):\n Exception.__init__(self, message)\n self.code = code\n self.msg = message\n self.data = data\n\n def __str__(self):\n return self.msg\n\n def to_dict(self):\n res = dict(self.data or ())\n res['msg'] = self.msg\n res['code'] = self.code\n return res\n\n\ndef error_handle(msg='', data=None):\n service_logger.error(data={'msg': msg, 'data': data})\n raise ApiException(msg)\n", "step-4": "from service import service_logger\nfrom service.TaskService import TaskService\n\n\nclass ApiException(Exception):\n\n def __init__(self, message, code=400, data=None):\n Exception.__init__(self, message)\n self.code = code\n self.msg = message\n self.data = data\n\n def __str__(self):\n return self.msg\n\n def to_dict(self):\n res = dict(self.data or ())\n res['msg'] = self.msg\n res['code'] = self.code\n return res\n\n\ndef error_handle(msg='', data=None):\n service_logger.error(data={'msg': msg, 'data': data})\n raise ApiException(msg)\n", "step-5": "# _*_ coding: utf-8 _*_\r\nfrom service import service_logger\r\nfrom service.TaskService import TaskService\r\n\r\nclass ApiException(Exception):\r\n\r\n def __init__(self, message, code=400, data=None):\r\n Exception.__init__(self, message)\r\n\r\n self.code = code\r\n self.msg = message\r\n self.data = data\r\n\r\n def __str__(self):\r\n return self.msg\r\n\r\n def to_dict(self):\r\n res = dict(self.data or ())\r\n res['msg'] = self.msg\r\n res['code'] = self.code\r\n\r\n return res\r\n\r\n\r\ndef error_handle(msg='', data=None):\r\n service_logger.error(data={\"msg\": msg, \"data\": data})\r\n raise ApiException(msg)", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
<|reserved_special_token_0|> class cRandomString: @staticmethod def RandomTitle(name): platform = ['PS4', 'XBOX', 'PC', 'NS', 'IOS'] random.shuffle(platform) platform = '/'.join(platform) firstWord = ['Cool', 'Hot', 'New', '2018', 'Gift', '*Cool*', '*Hot*', '*New*', '$Cool$', '$Hot$', '$New$'] firstWord = random.choice(firstWord) title = firstWord + ' 🤑 FREE Fortnite XXXX SKIN ' + platform title = title.replace('XXXX', name) return title <|reserved_special_token_0|> @staticmethod def RandomTag(name): tag_temp = ( 'XXXX, XXXX fortnite, XXXX free, XXXX skin,fortnite XXXX skin free, how to get the XXXX skin, iPhone XXXX free skins, iPad XXXX free skins' ) tag_final = tag_temp.replace('XXXX', name) return tag_final <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class cRandomString: @staticmethod def RandomTitle(name): platform = ['PS4', 'XBOX', 'PC', 'NS', 'IOS'] random.shuffle(platform) platform = '/'.join(platform) firstWord = ['Cool', 'Hot', 'New', '2018', 'Gift', '*Cool*', '*Hot*', '*New*', '$Cool$', '$Hot$', '$New$'] firstWord = random.choice(firstWord) title = firstWord + ' 🤑 FREE Fortnite XXXX SKIN ' + platform title = title.replace('XXXX', name) return title @staticmethod def RandomDescription(name): platform = ['PS4', 'Xbox One', 'PC', 'Nintendo Switch', 'IOS'] random.shuffle(platform) platform = ', '.join(platform) description_temp = ( """Hey Guys! In today's video I will show you how to get the XXXX skin for free in fortnite! This is working on xbox, ps4, ios, pc and nintendo switch! This method is 100% free and working as of 2018. This is the best way to get a fortnite XXXX skin for free key code! This is a working and legal method! How To Get FREE SKINS In Fortnite: Battle Royale! [{0}]""" .format(platform)) description_final = description_temp.replace('XXXX', name) return description_final @staticmethod def RandomTag(name): tag_temp = ( 'XXXX, XXXX fortnite, XXXX free, XXXX skin,fortnite XXXX skin free, how to get the XXXX skin, iPhone XXXX free skins, iPad XXXX free skins' ) tag_final = tag_temp.replace('XXXX', name) return tag_final <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> reload(sys) sys.setdefaultencoding('utf-8') class cRandomString: @staticmethod def RandomTitle(name): platform = ['PS4', 'XBOX', 'PC', 'NS', 'IOS'] random.shuffle(platform) platform = '/'.join(platform) firstWord = ['Cool', 'Hot', 'New', '2018', 'Gift', '*Cool*', '*Hot*', '*New*', '$Cool$', '$Hot$', '$New$'] firstWord = random.choice(firstWord) title = firstWord + ' 🤑 FREE Fortnite XXXX SKIN ' + platform title = title.replace('XXXX', name) return title @staticmethod def RandomDescription(name): platform = ['PS4', 'Xbox One', 'PC', 'Nintendo Switch', 'IOS'] random.shuffle(platform) platform = ', '.join(platform) description_temp = ( """Hey Guys! In today's video I will show you how to get the XXXX skin for free in fortnite! This is working on xbox, ps4, ios, pc and nintendo switch! This method is 100% free and working as of 2018. This is the best way to get a fortnite XXXX skin for free key code! This is a working and legal method! How To Get FREE SKINS In Fortnite: Battle Royale! [{0}]""" .format(platform)) description_final = description_temp.replace('XXXX', name) return description_final @staticmethod def RandomTag(name): tag_temp = ( 'XXXX, XXXX fortnite, XXXX free, XXXX skin,fortnite XXXX skin free, how to get the XXXX skin, iPhone XXXX free skins, iPad XXXX free skins' ) tag_final = tag_temp.replace('XXXX', name) return tag_final if __name__ == '__main__': cRandomString.RandomDescription('123') <|reserved_special_token_1|> import random import sys reload(sys) sys.setdefaultencoding('utf-8') class cRandomString: @staticmethod def RandomTitle(name): platform = ['PS4', 'XBOX', 'PC', 'NS', 'IOS'] random.shuffle(platform) platform = '/'.join(platform) firstWord = ['Cool', 'Hot', 'New', '2018', 'Gift', '*Cool*', '*Hot*', '*New*', '$Cool$', '$Hot$', '$New$'] firstWord = random.choice(firstWord) title = firstWord + ' 🤑 FREE Fortnite XXXX SKIN ' + platform title = title.replace('XXXX', name) return title @staticmethod def RandomDescription(name): platform = ['PS4', 'Xbox One', 'PC', 'Nintendo Switch', 'IOS'] random.shuffle(platform) platform = ', '.join(platform) description_temp = ( """Hey Guys! In today's video I will show you how to get the XXXX skin for free in fortnite! This is working on xbox, ps4, ios, pc and nintendo switch! This method is 100% free and working as of 2018. This is the best way to get a fortnite XXXX skin for free key code! This is a working and legal method! How To Get FREE SKINS In Fortnite: Battle Royale! [{0}]""" .format(platform)) description_final = description_temp.replace('XXXX', name) return description_final @staticmethod def RandomTag(name): tag_temp = ( 'XXXX, XXXX fortnite, XXXX free, XXXX skin,fortnite XXXX skin free, how to get the XXXX skin, iPhone XXXX free skins, iPad XXXX free skins' ) tag_final = tag_temp.replace('XXXX', name) return tag_final if __name__ == '__main__': cRandomString.RandomDescription('123') <|reserved_special_token_1|> # -*- coding:utf-8 -*- # author:Kyseng # file: cRandomString.py # time: 2018/11/8 11:41 PM # functhion: import random import sys reload(sys) sys.setdefaultencoding('utf-8') class cRandomString(): @staticmethod def RandomTitle(name): # name = name.decode('utf8') # print name platform = ["PS4", "XBOX", "PC", "NS", "IOS"] random.shuffle(platform) platform = "/".join(platform) firstWord = ['Cool', 'Hot', 'New', '2018', 'Gift', '*Cool*', '*Hot*', '*New*', '$Cool$', '$Hot$', '$New$'] firstWord = random.choice(firstWord) title = firstWord + ' 🤑 FREE Fortnite XXXX SKIN ' + platform title = title.replace('XXXX', name) return title @staticmethod def RandomDescription(name): platform = ["PS4", "Xbox One", "PC", "Nintendo Switch", "IOS"] random.shuffle(platform) platform = ", ".join(platform) description_temp = "Hey Guys!\n\nIn today's video I will show you how to get the XXXX skin for free in fortnite!\n\nThis is working on xbox, ps4, ios, pc and nintendo switch!\n\nThis method is 100% free and working as of 2018.\n\nThis is the best way to get a fortnite XXXX skin for free key code! \n\nThis is a working and legal method!\n\nHow To Get FREE SKINS In Fortnite: Battle Royale! [{0}]".format(platform) description_final = description_temp.replace('XXXX', name) return description_final @staticmethod def RandomTag(name): tag_temp = "XXXX, XXXX fortnite, XXXX free, XXXX skin,fortnite XXXX skin free, how to get the XXXX skin, iPhone XXXX free skins, iPad XXXX free skins" tag_final = tag_temp.replace('XXXX', name) return tag_final if __name__ == "__main__": cRandomString.RandomDescription("123")
flexible
{ "blob_id": "ed02cbf3ebef307d6209004e1e388312bfda0b50", "index": 2027, "step-1": "<mask token>\n\n\nclass cRandomString:\n\n @staticmethod\n def RandomTitle(name):\n platform = ['PS4', 'XBOX', 'PC', 'NS', 'IOS']\n random.shuffle(platform)\n platform = '/'.join(platform)\n firstWord = ['Cool', 'Hot', 'New', '2018', 'Gift', '*Cool*',\n '*Hot*', '*New*', '$Cool$', '$Hot$', '$New$']\n firstWord = random.choice(firstWord)\n title = firstWord + ' 🤑 FREE Fortnite XXXX SKIN ' + platform\n title = title.replace('XXXX', name)\n return title\n <mask token>\n\n @staticmethod\n def RandomTag(name):\n tag_temp = (\n 'XXXX, XXXX fortnite, XXXX free, XXXX skin,fortnite XXXX skin free, how to get the XXXX skin, iPhone XXXX free skins, iPad XXXX free skins'\n )\n tag_final = tag_temp.replace('XXXX', name)\n return tag_final\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass cRandomString:\n\n @staticmethod\n def RandomTitle(name):\n platform = ['PS4', 'XBOX', 'PC', 'NS', 'IOS']\n random.shuffle(platform)\n platform = '/'.join(platform)\n firstWord = ['Cool', 'Hot', 'New', '2018', 'Gift', '*Cool*',\n '*Hot*', '*New*', '$Cool$', '$Hot$', '$New$']\n firstWord = random.choice(firstWord)\n title = firstWord + ' 🤑 FREE Fortnite XXXX SKIN ' + platform\n title = title.replace('XXXX', name)\n return title\n\n @staticmethod\n def RandomDescription(name):\n platform = ['PS4', 'Xbox One', 'PC', 'Nintendo Switch', 'IOS']\n random.shuffle(platform)\n platform = ', '.join(platform)\n description_temp = (\n \"\"\"Hey Guys!\n\nIn today's video I will show you how to get the XXXX skin for free in fortnite!\n\nThis is working on xbox, ps4, ios, pc and nintendo switch!\n\nThis method is 100% free and working as of 2018.\n\nThis is the best way to get a fortnite XXXX skin for free key code! \n\nThis is a working and legal method!\n\nHow To Get FREE SKINS In Fortnite: Battle Royale! [{0}]\"\"\"\n .format(platform))\n description_final = description_temp.replace('XXXX', name)\n return description_final\n\n @staticmethod\n def RandomTag(name):\n tag_temp = (\n 'XXXX, XXXX fortnite, XXXX free, XXXX skin,fortnite XXXX skin free, how to get the XXXX skin, iPhone XXXX free skins, iPad XXXX free skins'\n )\n tag_final = tag_temp.replace('XXXX', name)\n return tag_final\n\n\n<mask token>\n", "step-3": "<mask token>\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\n\nclass cRandomString:\n\n @staticmethod\n def RandomTitle(name):\n platform = ['PS4', 'XBOX', 'PC', 'NS', 'IOS']\n random.shuffle(platform)\n platform = '/'.join(platform)\n firstWord = ['Cool', 'Hot', 'New', '2018', 'Gift', '*Cool*',\n '*Hot*', '*New*', '$Cool$', '$Hot$', '$New$']\n firstWord = random.choice(firstWord)\n title = firstWord + ' 🤑 FREE Fortnite XXXX SKIN ' + platform\n title = title.replace('XXXX', name)\n return title\n\n @staticmethod\n def RandomDescription(name):\n platform = ['PS4', 'Xbox One', 'PC', 'Nintendo Switch', 'IOS']\n random.shuffle(platform)\n platform = ', '.join(platform)\n description_temp = (\n \"\"\"Hey Guys!\n\nIn today's video I will show you how to get the XXXX skin for free in fortnite!\n\nThis is working on xbox, ps4, ios, pc and nintendo switch!\n\nThis method is 100% free and working as of 2018.\n\nThis is the best way to get a fortnite XXXX skin for free key code! \n\nThis is a working and legal method!\n\nHow To Get FREE SKINS In Fortnite: Battle Royale! [{0}]\"\"\"\n .format(platform))\n description_final = description_temp.replace('XXXX', name)\n return description_final\n\n @staticmethod\n def RandomTag(name):\n tag_temp = (\n 'XXXX, XXXX fortnite, XXXX free, XXXX skin,fortnite XXXX skin free, how to get the XXXX skin, iPhone XXXX free skins, iPad XXXX free skins'\n )\n tag_final = tag_temp.replace('XXXX', name)\n return tag_final\n\n\nif __name__ == '__main__':\n cRandomString.RandomDescription('123')\n", "step-4": "import random\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\n\nclass cRandomString:\n\n @staticmethod\n def RandomTitle(name):\n platform = ['PS4', 'XBOX', 'PC', 'NS', 'IOS']\n random.shuffle(platform)\n platform = '/'.join(platform)\n firstWord = ['Cool', 'Hot', 'New', '2018', 'Gift', '*Cool*',\n '*Hot*', '*New*', '$Cool$', '$Hot$', '$New$']\n firstWord = random.choice(firstWord)\n title = firstWord + ' 🤑 FREE Fortnite XXXX SKIN ' + platform\n title = title.replace('XXXX', name)\n return title\n\n @staticmethod\n def RandomDescription(name):\n platform = ['PS4', 'Xbox One', 'PC', 'Nintendo Switch', 'IOS']\n random.shuffle(platform)\n platform = ', '.join(platform)\n description_temp = (\n \"\"\"Hey Guys!\n\nIn today's video I will show you how to get the XXXX skin for free in fortnite!\n\nThis is working on xbox, ps4, ios, pc and nintendo switch!\n\nThis method is 100% free and working as of 2018.\n\nThis is the best way to get a fortnite XXXX skin for free key code! \n\nThis is a working and legal method!\n\nHow To Get FREE SKINS In Fortnite: Battle Royale! [{0}]\"\"\"\n .format(platform))\n description_final = description_temp.replace('XXXX', name)\n return description_final\n\n @staticmethod\n def RandomTag(name):\n tag_temp = (\n 'XXXX, XXXX fortnite, XXXX free, XXXX skin,fortnite XXXX skin free, how to get the XXXX skin, iPhone XXXX free skins, iPad XXXX free skins'\n )\n tag_final = tag_temp.replace('XXXX', name)\n return tag_final\n\n\nif __name__ == '__main__':\n cRandomString.RandomDescription('123')\n", "step-5": "# -*- coding:utf-8 -*-\n# author:Kyseng\n# file: cRandomString.py\n# time: 2018/11/8 11:41 PM\n# functhion:\nimport random\nimport sys\n\nreload(sys)\n\nsys.setdefaultencoding('utf-8')\n\nclass cRandomString():\n @staticmethod\n def RandomTitle(name):\n # name = name.decode('utf8')\n # print name\n platform = [\"PS4\", \"XBOX\", \"PC\", \"NS\", \"IOS\"]\n random.shuffle(platform)\n platform = \"/\".join(platform)\n\n\n firstWord = ['Cool', 'Hot', 'New', '2018', 'Gift', '*Cool*', '*Hot*', '*New*', '$Cool$', '$Hot$', '$New$']\n firstWord = random.choice(firstWord)\n\n title = firstWord + ' 🤑 FREE Fortnite XXXX SKIN ' + platform\n\n title = title.replace('XXXX', name)\n\n return title\n\n @staticmethod\n def RandomDescription(name):\n platform = [\"PS4\", \"Xbox One\", \"PC\", \"Nintendo Switch\", \"IOS\"]\n random.shuffle(platform)\n platform = \", \".join(platform)\n\n description_temp = \"Hey Guys!\\n\\nIn today's video I will show you how to get the XXXX skin for free in fortnite!\\n\\nThis is working on xbox, ps4, ios, pc and nintendo switch!\\n\\nThis method is 100% free and working as of 2018.\\n\\nThis is the best way to get a fortnite XXXX skin for free key code! \\n\\nThis is a working and legal method!\\n\\nHow To Get FREE SKINS In Fortnite: Battle Royale! [{0}]\".format(platform)\n\n description_final = description_temp.replace('XXXX', name)\n\n return description_final\n\n @staticmethod\n def RandomTag(name):\n tag_temp = \"XXXX, XXXX fortnite, XXXX free, XXXX skin,fortnite XXXX skin free, how to get the XXXX skin, iPhone XXXX free skins, iPad XXXX free skins\"\n tag_final = tag_temp.replace('XXXX', name)\n\n return tag_final\n\nif __name__ == \"__main__\":\n cRandomString.RandomDescription(\"123\")", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> setup(name='supermodule', version='1.0', ext_modules=[Extension( 'supermodule', ['main.c'])]) <|reserved_special_token_1|> from distutils.core import setup, Extension setup(name='supermodule', version='1.0', ext_modules=[Extension( 'supermodule', ['main.c'])]) <|reserved_special_token_1|> from distutils.core import setup, Extension setup(name='supermodule', version='1.0', \ ext_modules=[Extension('supermodule', ['main.c'])])
flexible
{ "blob_id": "78c8f953b924f3e664570b844bf736a788e9cfb7", "index": 3607, "step-1": "<mask token>\n", "step-2": "<mask token>\nsetup(name='supermodule', version='1.0', ext_modules=[Extension(\n 'supermodule', ['main.c'])])\n", "step-3": "from distutils.core import setup, Extension\nsetup(name='supermodule', version='1.0', ext_modules=[Extension(\n 'supermodule', ['main.c'])])\n", "step-4": "from distutils.core import setup, Extension\nsetup(name='supermodule', version='1.0', \\\n ext_modules=[Extension('supermodule', ['main.c'])])\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from ui.pages import BasePage from ui.locators.login_page_locators import LoginPageLocators class LoginPage(BasePage, LoginPageLocators): def __init__(self, driver=None): super(LoginPage, self).__init__(driver=driver) self.identifier = self.IDENTIFIER def login(self, email=None, password=None, remember_me=False): self.navigate() if not self.wait_for_page_to_load(): return False if not email: email = self.std.login_user if not password: password = self.std.login_password if not self.set_text(self.USERNAME_INPUT, email): return False if not self.set_text(self.PASSWORD_INPUT, password): return False if remember_me: if not self.click(self.REMEMBER_CHECKBOX): return False if not self.click(self.SIGN_IN_BTN): return False return True def get_error_messages(self): invalid_user = self.get_text(self.USERNAME_MISSING_DIV) invalid_pass = self.get_text(self.PASSWORD_MISSING_DIV) if not (invalid_pass or invalid_user): return False return invalid_pass, invalid_user def forgot_password(self): if not self.click(self.FORGOT_PASSWORD_LINK): return False return True
normal
{ "blob_id": "c1bcce809aa073ecd6e64dfa65ead9bd48aee3ff", "index": 7406, "step-1": "<mask token>\n\n\nclass LoginPage(BasePage, LoginPageLocators):\n\n def __init__(self, driver=None):\n super(LoginPage, self).__init__(driver=driver)\n self.identifier = self.IDENTIFIER\n <mask token>\n\n def get_error_messages(self):\n invalid_user = self.get_text(self.USERNAME_MISSING_DIV)\n invalid_pass = self.get_text(self.PASSWORD_MISSING_DIV)\n if not (invalid_pass or invalid_user):\n return False\n return invalid_pass, invalid_user\n <mask token>\n", "step-2": "<mask token>\n\n\nclass LoginPage(BasePage, LoginPageLocators):\n\n def __init__(self, driver=None):\n super(LoginPage, self).__init__(driver=driver)\n self.identifier = self.IDENTIFIER\n <mask token>\n\n def get_error_messages(self):\n invalid_user = self.get_text(self.USERNAME_MISSING_DIV)\n invalid_pass = self.get_text(self.PASSWORD_MISSING_DIV)\n if not (invalid_pass or invalid_user):\n return False\n return invalid_pass, invalid_user\n\n def forgot_password(self):\n if not self.click(self.FORGOT_PASSWORD_LINK):\n return False\n return True\n", "step-3": "<mask token>\n\n\nclass LoginPage(BasePage, LoginPageLocators):\n\n def __init__(self, driver=None):\n super(LoginPage, self).__init__(driver=driver)\n self.identifier = self.IDENTIFIER\n\n def login(self, email=None, password=None, remember_me=False):\n self.navigate()\n if not self.wait_for_page_to_load():\n return False\n if not email:\n email = self.std.login_user\n if not password:\n password = self.std.login_password\n if not self.set_text(self.USERNAME_INPUT, email):\n return False\n if not self.set_text(self.PASSWORD_INPUT, password):\n return False\n if remember_me:\n if not self.click(self.REMEMBER_CHECKBOX):\n return False\n if not self.click(self.SIGN_IN_BTN):\n return False\n return True\n\n def get_error_messages(self):\n invalid_user = self.get_text(self.USERNAME_MISSING_DIV)\n invalid_pass = self.get_text(self.PASSWORD_MISSING_DIV)\n if not (invalid_pass or invalid_user):\n return False\n return invalid_pass, invalid_user\n\n def forgot_password(self):\n if not self.click(self.FORGOT_PASSWORD_LINK):\n return False\n return True\n", "step-4": "from ui.pages import BasePage\nfrom ui.locators.login_page_locators import LoginPageLocators\n\n\nclass LoginPage(BasePage, LoginPageLocators):\n\n def __init__(self, driver=None):\n super(LoginPage, self).__init__(driver=driver)\n self.identifier = self.IDENTIFIER\n\n def login(self, email=None, password=None, remember_me=False):\n self.navigate()\n if not self.wait_for_page_to_load():\n return False\n if not email:\n email = self.std.login_user\n if not password:\n password = self.std.login_password\n if not self.set_text(self.USERNAME_INPUT, email):\n return False\n if not self.set_text(self.PASSWORD_INPUT, password):\n return False\n if remember_me:\n if not self.click(self.REMEMBER_CHECKBOX):\n return False\n if not self.click(self.SIGN_IN_BTN):\n return False\n return True\n\n def get_error_messages(self):\n invalid_user = self.get_text(self.USERNAME_MISSING_DIV)\n invalid_pass = self.get_text(self.PASSWORD_MISSING_DIV)\n if not (invalid_pass or invalid_user):\n return False\n return invalid_pass, invalid_user\n\n def forgot_password(self):\n if not self.click(self.FORGOT_PASSWORD_LINK):\n return False\n return True\n", "step-5": null, "step-ids": [ 3, 4, 5, 6 ] }
[ 3, 4, 5, 6 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> m.sort(reverse=True) <|reserved_special_token_0|> while x > 0: res += max(0, m[i]) m[i] -= 1 x -= 1 if m[i % n] < m[(i + 1) % n]: i = (i + 1) % n print(res) <|reserved_special_token_1|> n, x = input().split() n = int(n) x = int(x) m = [int(i) for i in input().split()] m.sort(reverse=True) i = 0 res = 0 while x > 0: res += max(0, m[i]) m[i] -= 1 x -= 1 if m[i % n] < m[(i + 1) % n]: i = (i + 1) % n print(res)
flexible
{ "blob_id": "9d3439a2be1f22c8ec59923b88ac22877a4f13e8", "index": 663, "step-1": "<mask token>\n", "step-2": "<mask token>\nm.sort(reverse=True)\n<mask token>\nwhile x > 0:\n res += max(0, m[i])\n m[i] -= 1\n x -= 1\n if m[i % n] < m[(i + 1) % n]:\n i = (i + 1) % n\nprint(res)\n", "step-3": "n, x = input().split()\nn = int(n)\nx = int(x)\nm = [int(i) for i in input().split()]\nm.sort(reverse=True)\ni = 0\nres = 0\nwhile x > 0:\n res += max(0, m[i])\n m[i] -= 1\n x -= 1\n if m[i % n] < m[(i + 1) % n]:\n i = (i + 1) % n\nprint(res)\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
"""Project agnostic helper functions that could be migrated to and external lib. """
normal
{ "blob_id": "f15bb4ab93ecb2689bf74687852e60dfa98caea9", "index": 7374, "step-1": "<mask token>\n", "step-2": "\"\"\"Project agnostic helper functions that could be migrated to and external lib.\n\"\"\"\n", "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0, 1 ] }
[ 0, 1 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> if use_gpu: img0 = img0.cuda() <|reserved_special_token_0|> if use_gpu: img1 = img1.cuda() <|reserved_special_token_0|> plt.figure(figsize=[9, 3.5]) plt.subplot(131) plt.imshow(img0_) plt.subplot(132) plt.imshow(img1_) plt.subplot(133) plt.pcolor(dist01.cpu().detach().squeeze()) plt.axis('image') plt.gca().invert_yaxis() plt.title('Dist %.2f' % dist_sum) plt.savefig(join(fig_outdir, 'Diff1212_1896_1900_%s.png' % net_name)) plt.show() <|reserved_special_token_1|> <|reserved_special_token_0|> use_gpu = True fig_outdir = ( 'C:\\Users\\ponce\\OneDrive - Washington University in St. Louis\\ImageDiffMetric' ) net_name = 'squeeze' SpatialDist = models.PerceptualLoss(model='net-lin', net=net_name, colorspace='rgb', spatial=True, use_gpu=True, gpu_ids=[0]) PerceptLoss = models.PerceptualLoss(model='net-lin', net=net_name, colorspace='rgb', spatial=False, use_gpu=True, gpu_ids=[0]) imgdir = ( '\\\\storage1.ris.wustl.edu\\crponce\\Active\\Stimuli\\2019-06-Evolutions\\beto-191212a\\backup_12_12_2019_10_47_39' ) file0 = 'block048_thread000_gen_gen047_001896.jpg' file1 = 'block048_thread000_gen_gen047_001900.jpg' img0_ = util.load_image(join(imgdir, file0)) img1_ = util.load_image(join(imgdir, file1)) img0 = util.im2tensor(img0_) if use_gpu: img0 = img0.cuda() img1 = util.im2tensor(img1_) if use_gpu: img1 = img1.cuda() dist01 = SpatialDist.forward(img0, img1) dist_sum = PerceptLoss.forward(img0, img1).item() plt.figure(figsize=[9, 3.5]) plt.subplot(131) plt.imshow(img0_) plt.subplot(132) plt.imshow(img1_) plt.subplot(133) plt.pcolor(dist01.cpu().detach().squeeze()) plt.axis('image') plt.gca().invert_yaxis() plt.title('Dist %.2f' % dist_sum) plt.savefig(join(fig_outdir, 'Diff1212_1896_1900_%s.png' % net_name)) plt.show() <|reserved_special_token_1|> from os.path import join import models import util.util as util import matplotlib.pylab as plt use_gpu = True fig_outdir = ( 'C:\\Users\\ponce\\OneDrive - Washington University in St. Louis\\ImageDiffMetric' ) net_name = 'squeeze' SpatialDist = models.PerceptualLoss(model='net-lin', net=net_name, colorspace='rgb', spatial=True, use_gpu=True, gpu_ids=[0]) PerceptLoss = models.PerceptualLoss(model='net-lin', net=net_name, colorspace='rgb', spatial=False, use_gpu=True, gpu_ids=[0]) imgdir = ( '\\\\storage1.ris.wustl.edu\\crponce\\Active\\Stimuli\\2019-06-Evolutions\\beto-191212a\\backup_12_12_2019_10_47_39' ) file0 = 'block048_thread000_gen_gen047_001896.jpg' file1 = 'block048_thread000_gen_gen047_001900.jpg' img0_ = util.load_image(join(imgdir, file0)) img1_ = util.load_image(join(imgdir, file1)) img0 = util.im2tensor(img0_) if use_gpu: img0 = img0.cuda() img1 = util.im2tensor(img1_) if use_gpu: img1 = img1.cuda() dist01 = SpatialDist.forward(img0, img1) dist_sum = PerceptLoss.forward(img0, img1).item() plt.figure(figsize=[9, 3.5]) plt.subplot(131) plt.imshow(img0_) plt.subplot(132) plt.imshow(img1_) plt.subplot(133) plt.pcolor(dist01.cpu().detach().squeeze()) plt.axis('image') plt.gca().invert_yaxis() plt.title('Dist %.2f' % dist_sum) plt.savefig(join(fig_outdir, 'Diff1212_1896_1900_%s.png' % net_name)) plt.show() <|reserved_special_token_1|> # from models import dist_model # model = dist_model.DistModel() from os.path import join import models import util.util as util import matplotlib.pylab as plt use_gpu = True fig_outdir = r"C:\Users\ponce\OneDrive - Washington University in St. Louis\ImageDiffMetric" #%% net_name = 'squeeze' SpatialDist = models.PerceptualLoss(model='net-lin', net=net_name, colorspace='rgb', spatial=True, use_gpu=True, gpu_ids=[0]) PerceptLoss = models.PerceptualLoss(model='net-lin', net=net_name, colorspace='rgb', spatial=False, use_gpu=True, gpu_ids=[0]) #%% imgdir = r"\\storage1.ris.wustl.edu\crponce\Active\Stimuli\2019-06-Evolutions\beto-191212a\backup_12_12_2019_10_47_39" file0 = "block048_thread000_gen_gen047_001896.jpg" file1 = "block048_thread000_gen_gen047_001900.jpg" img0_ = util.load_image(join(imgdir,file0)) img1_ = util.load_image(join(imgdir,file1)) img0 = util.im2tensor(img0_) # RGB image from [-1,1] if(use_gpu): img0 = img0.cuda() img1 = util.im2tensor(img1_) if(use_gpu): img1 = img1.cuda() #% # Compute distance dist01 = SpatialDist.forward(img0,img1)#.item() dist_sum = PerceptLoss.forward(img0,img1).item() # dists.append(dist01) # print('(%s, %s): %.3f'%(file0,file1,dist01)) # f.writelines('(%s, %s): %.3f'%(file0,file1,dist01)) # % plt.figure(figsize=[9,3.5]) plt.subplot(131) plt.imshow(img0_) plt.subplot(132) plt.imshow(img1_) plt.subplot(133) plt.pcolor(dist01.cpu().detach().squeeze()) plt.axis('image') plt.gca().invert_yaxis() plt.title("Dist %.2f"%dist_sum) plt.savefig(join(fig_outdir,"Diff1212_1896_1900_%s.png" % net_name)) plt.show()
flexible
{ "blob_id": "8fcbaf2663c22015a0c47f00c2d4fb8db6a5c308", "index": 6209, "step-1": "<mask token>\n", "step-2": "<mask token>\nif use_gpu:\n img0 = img0.cuda()\n<mask token>\nif use_gpu:\n img1 = img1.cuda()\n<mask token>\nplt.figure(figsize=[9, 3.5])\nplt.subplot(131)\nplt.imshow(img0_)\nplt.subplot(132)\nplt.imshow(img1_)\nplt.subplot(133)\nplt.pcolor(dist01.cpu().detach().squeeze())\nplt.axis('image')\nplt.gca().invert_yaxis()\nplt.title('Dist %.2f' % dist_sum)\nplt.savefig(join(fig_outdir, 'Diff1212_1896_1900_%s.png' % net_name))\nplt.show()\n", "step-3": "<mask token>\nuse_gpu = True\nfig_outdir = (\n 'C:\\\\Users\\\\ponce\\\\OneDrive - Washington University in St. Louis\\\\ImageDiffMetric'\n )\nnet_name = 'squeeze'\nSpatialDist = models.PerceptualLoss(model='net-lin', net=net_name,\n colorspace='rgb', spatial=True, use_gpu=True, gpu_ids=[0])\nPerceptLoss = models.PerceptualLoss(model='net-lin', net=net_name,\n colorspace='rgb', spatial=False, use_gpu=True, gpu_ids=[0])\nimgdir = (\n '\\\\\\\\storage1.ris.wustl.edu\\\\crponce\\\\Active\\\\Stimuli\\\\2019-06-Evolutions\\\\beto-191212a\\\\backup_12_12_2019_10_47_39'\n )\nfile0 = 'block048_thread000_gen_gen047_001896.jpg'\nfile1 = 'block048_thread000_gen_gen047_001900.jpg'\nimg0_ = util.load_image(join(imgdir, file0))\nimg1_ = util.load_image(join(imgdir, file1))\nimg0 = util.im2tensor(img0_)\nif use_gpu:\n img0 = img0.cuda()\nimg1 = util.im2tensor(img1_)\nif use_gpu:\n img1 = img1.cuda()\ndist01 = SpatialDist.forward(img0, img1)\ndist_sum = PerceptLoss.forward(img0, img1).item()\nplt.figure(figsize=[9, 3.5])\nplt.subplot(131)\nplt.imshow(img0_)\nplt.subplot(132)\nplt.imshow(img1_)\nplt.subplot(133)\nplt.pcolor(dist01.cpu().detach().squeeze())\nplt.axis('image')\nplt.gca().invert_yaxis()\nplt.title('Dist %.2f' % dist_sum)\nplt.savefig(join(fig_outdir, 'Diff1212_1896_1900_%s.png' % net_name))\nplt.show()\n", "step-4": "from os.path import join\nimport models\nimport util.util as util\nimport matplotlib.pylab as plt\nuse_gpu = True\nfig_outdir = (\n 'C:\\\\Users\\\\ponce\\\\OneDrive - Washington University in St. Louis\\\\ImageDiffMetric'\n )\nnet_name = 'squeeze'\nSpatialDist = models.PerceptualLoss(model='net-lin', net=net_name,\n colorspace='rgb', spatial=True, use_gpu=True, gpu_ids=[0])\nPerceptLoss = models.PerceptualLoss(model='net-lin', net=net_name,\n colorspace='rgb', spatial=False, use_gpu=True, gpu_ids=[0])\nimgdir = (\n '\\\\\\\\storage1.ris.wustl.edu\\\\crponce\\\\Active\\\\Stimuli\\\\2019-06-Evolutions\\\\beto-191212a\\\\backup_12_12_2019_10_47_39'\n )\nfile0 = 'block048_thread000_gen_gen047_001896.jpg'\nfile1 = 'block048_thread000_gen_gen047_001900.jpg'\nimg0_ = util.load_image(join(imgdir, file0))\nimg1_ = util.load_image(join(imgdir, file1))\nimg0 = util.im2tensor(img0_)\nif use_gpu:\n img0 = img0.cuda()\nimg1 = util.im2tensor(img1_)\nif use_gpu:\n img1 = img1.cuda()\ndist01 = SpatialDist.forward(img0, img1)\ndist_sum = PerceptLoss.forward(img0, img1).item()\nplt.figure(figsize=[9, 3.5])\nplt.subplot(131)\nplt.imshow(img0_)\nplt.subplot(132)\nplt.imshow(img1_)\nplt.subplot(133)\nplt.pcolor(dist01.cpu().detach().squeeze())\nplt.axis('image')\nplt.gca().invert_yaxis()\nplt.title('Dist %.2f' % dist_sum)\nplt.savefig(join(fig_outdir, 'Diff1212_1896_1900_%s.png' % net_name))\nplt.show()\n", "step-5": "# from models import dist_model\n# model = dist_model.DistModel()\nfrom os.path import join\nimport models\nimport util.util as util\nimport matplotlib.pylab as plt\nuse_gpu = True\nfig_outdir = r\"C:\\Users\\ponce\\OneDrive - Washington University in St. Louis\\ImageDiffMetric\"\n#%%\nnet_name = 'squeeze'\nSpatialDist = models.PerceptualLoss(model='net-lin', net=net_name, colorspace='rgb', spatial=True, use_gpu=True, gpu_ids=[0])\nPerceptLoss = models.PerceptualLoss(model='net-lin', net=net_name, colorspace='rgb', spatial=False, use_gpu=True, gpu_ids=[0])\n#%%\nimgdir = r\"\\\\storage1.ris.wustl.edu\\crponce\\Active\\Stimuli\\2019-06-Evolutions\\beto-191212a\\backup_12_12_2019_10_47_39\"\nfile0 = \"block048_thread000_gen_gen047_001896.jpg\"\nfile1 = \"block048_thread000_gen_gen047_001900.jpg\"\nimg0_ = util.load_image(join(imgdir,file0))\nimg1_ = util.load_image(join(imgdir,file1))\nimg0 = util.im2tensor(img0_) # RGB image from [-1,1]\nif(use_gpu):\n img0 = img0.cuda()\nimg1 = util.im2tensor(img1_)\nif(use_gpu):\n img1 = img1.cuda()\n#%\n# Compute distance\ndist01 = SpatialDist.forward(img0,img1)#.item()\ndist_sum = PerceptLoss.forward(img0,img1).item()\n# dists.append(dist01)\n# print('(%s, %s): %.3f'%(file0,file1,dist01))\n# f.writelines('(%s, %s): %.3f'%(file0,file1,dist01))\n# %\nplt.figure(figsize=[9,3.5])\nplt.subplot(131)\nplt.imshow(img0_)\nplt.subplot(132)\nplt.imshow(img1_)\nplt.subplot(133)\nplt.pcolor(dist01.cpu().detach().squeeze())\nplt.axis('image')\nplt.gca().invert_yaxis()\nplt.title(\"Dist %.2f\"%dist_sum)\nplt.savefig(join(fig_outdir,\"Diff1212_1896_1900_%s.png\" % net_name))\nplt.show()", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/python3 """ request api and write in JSON file all tasks todo for every users """ import json import requests import sys if __name__ == "__main__": req = "https://jsonplaceholder.typicode.com/todos" response = requests.get(req).json() d = {} req_user = "https://jsonplaceholder.typicode.com/users" users = requests.get(req_user).json() for user in users: reso_todos = "https://jsonplaceholder.typicode.com/users/{}/todos"\ .format(user['id']) rq = requests.get(reso_todos).json() list_tasks = [] for content in rq: d_task = {} d_task['task'] = content['title'] d_task['completed'] = content['completed'] d_task['username'] = user['username'] list_tasks.append(d_task) d[user['id']] = list_tasks with open('todo_all_employees.json', 'w') as f: json.dump(d, f)
normal
{ "blob_id": "53de53614b3c503a4232c00e8f2fd5a0f4cb6615", "index": 1624, "step-1": "<mask token>\n", "step-2": "<mask token>\nif __name__ == '__main__':\n req = 'https://jsonplaceholder.typicode.com/todos'\n response = requests.get(req).json()\n d = {}\n req_user = 'https://jsonplaceholder.typicode.com/users'\n users = requests.get(req_user).json()\n for user in users:\n reso_todos = ('https://jsonplaceholder.typicode.com/users/{}/todos'\n .format(user['id']))\n rq = requests.get(reso_todos).json()\n list_tasks = []\n for content in rq:\n d_task = {}\n d_task['task'] = content['title']\n d_task['completed'] = content['completed']\n d_task['username'] = user['username']\n list_tasks.append(d_task)\n d[user['id']] = list_tasks\n with open('todo_all_employees.json', 'w') as f:\n json.dump(d, f)\n", "step-3": "<mask token>\nimport json\nimport requests\nimport sys\nif __name__ == '__main__':\n req = 'https://jsonplaceholder.typicode.com/todos'\n response = requests.get(req).json()\n d = {}\n req_user = 'https://jsonplaceholder.typicode.com/users'\n users = requests.get(req_user).json()\n for user in users:\n reso_todos = ('https://jsonplaceholder.typicode.com/users/{}/todos'\n .format(user['id']))\n rq = requests.get(reso_todos).json()\n list_tasks = []\n for content in rq:\n d_task = {}\n d_task['task'] = content['title']\n d_task['completed'] = content['completed']\n d_task['username'] = user['username']\n list_tasks.append(d_task)\n d[user['id']] = list_tasks\n with open('todo_all_employees.json', 'w') as f:\n json.dump(d, f)\n", "step-4": "#!/usr/bin/python3\n\"\"\"\n request api and write in JSON file\n all tasks todo for every users\n\"\"\"\nimport json\nimport requests\nimport sys\n\n\nif __name__ == \"__main__\":\n req = \"https://jsonplaceholder.typicode.com/todos\"\n response = requests.get(req).json()\n d = {}\n req_user = \"https://jsonplaceholder.typicode.com/users\"\n users = requests.get(req_user).json()\n for user in users:\n reso_todos = \"https://jsonplaceholder.typicode.com/users/{}/todos\"\\\n .format(user['id'])\n rq = requests.get(reso_todos).json()\n list_tasks = []\n for content in rq:\n d_task = {}\n d_task['task'] = content['title']\n d_task['completed'] = content['completed']\n d_task['username'] = user['username']\n list_tasks.append(d_task)\n d[user['id']] = list_tasks\n with open('todo_all_employees.json', 'w') as f:\n json.dump(d, f)\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
""" You have a map that marks the locations of treasure islands. Some of the map area has jagged rocks and dangerous reefs. Other areas are safe to sail in. There are other explorers trying to find the treasure. So you must figure out a shortest route to one of the treasure islands. Assume the map area is a two dimensional grid, represented by a matrix of characters. You must start from one of the starting point (marked as S) of the map and can move one block up, down, left or right at a time. The treasure island is marked as X. Any block with dangerous rocks or reefs will be marked as D. You must not enter dangerous blocks. You cannot leave the map area. Other areas O are safe to sail in. Output the minimum number of steps to get to any of the treasure islands. """ import math def find_treasure_util(grid, i, j): rows, columns = len(grid), len(grid[0]) queue = [((i, j), 0)] directions = [[0, 1], [0, -1], [1, 0], [-1, 0]] visited = [[-1 for _ in range(columns)] for _ in range(rows)] while queue: (x, y), step = queue.pop() visited[x][y] = step for direction in directions: curr_x = x + direction[0] curr_y = y + direction[1] if 0 <= curr_x < rows and 0 <= curr_y < columns and grid[curr_x][curr_y] == 'X': return step + 1 elif 0 <= curr_x < rows and 0 <= curr_y < columns \ and grid[curr_x][curr_y] != 'D' \ and visited[curr_x][curr_y] == -1: queue.append(((curr_x, curr_y), step + 1)) return -1 def find_treasure(grid): if not len(grid) or not len(grid[0]): return -1 minimum_steps = math.inf for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] == 'S': minimum_steps = min(minimum_steps, find_treasure_util(grid, i, j)) return minimum_steps if __name__ == '__main__': grid = [['S', 'O', 'O', 'S', 'S'], ['D', 'O', 'D', 'O', 'D'], ['O', 'O', 'O', 'O', 'X'], ['X', 'D', 'D', 'O', 'O'], ['X', 'D', 'D', 'D', 'O']] print(find_treasure(grid))
normal
{ "blob_id": "e6851e86fa86ab2096f059218b2b8a2994642807", "index": 3717, "step-1": "<mask token>\n\n\ndef find_treasure(grid):\n if not len(grid) or not len(grid[0]):\n return -1\n minimum_steps = math.inf\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if grid[i][j] == 'S':\n minimum_steps = min(minimum_steps, find_treasure_util(grid,\n i, j))\n return minimum_steps\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef find_treasure_util(grid, i, j):\n rows, columns = len(grid), len(grid[0])\n queue = [((i, j), 0)]\n directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n visited = [[(-1) for _ in range(columns)] for _ in range(rows)]\n while queue:\n (x, y), step = queue.pop()\n visited[x][y] = step\n for direction in directions:\n curr_x = x + direction[0]\n curr_y = y + direction[1]\n if 0 <= curr_x < rows and 0 <= curr_y < columns and grid[curr_x][\n curr_y] == 'X':\n return step + 1\n elif 0 <= curr_x < rows and 0 <= curr_y < columns and grid[curr_x][\n curr_y] != 'D' and visited[curr_x][curr_y] == -1:\n queue.append(((curr_x, curr_y), step + 1))\n return -1\n\n\ndef find_treasure(grid):\n if not len(grid) or not len(grid[0]):\n return -1\n minimum_steps = math.inf\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if grid[i][j] == 'S':\n minimum_steps = min(minimum_steps, find_treasure_util(grid,\n i, j))\n return minimum_steps\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef find_treasure_util(grid, i, j):\n rows, columns = len(grid), len(grid[0])\n queue = [((i, j), 0)]\n directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n visited = [[(-1) for _ in range(columns)] for _ in range(rows)]\n while queue:\n (x, y), step = queue.pop()\n visited[x][y] = step\n for direction in directions:\n curr_x = x + direction[0]\n curr_y = y + direction[1]\n if 0 <= curr_x < rows and 0 <= curr_y < columns and grid[curr_x][\n curr_y] == 'X':\n return step + 1\n elif 0 <= curr_x < rows and 0 <= curr_y < columns and grid[curr_x][\n curr_y] != 'D' and visited[curr_x][curr_y] == -1:\n queue.append(((curr_x, curr_y), step + 1))\n return -1\n\n\ndef find_treasure(grid):\n if not len(grid) or not len(grid[0]):\n return -1\n minimum_steps = math.inf\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if grid[i][j] == 'S':\n minimum_steps = min(minimum_steps, find_treasure_util(grid,\n i, j))\n return minimum_steps\n\n\nif __name__ == '__main__':\n grid = [['S', 'O', 'O', 'S', 'S'], ['D', 'O', 'D', 'O', 'D'], ['O', 'O',\n 'O', 'O', 'X'], ['X', 'D', 'D', 'O', 'O'], ['X', 'D', 'D', 'D', 'O']]\n print(find_treasure(grid))\n", "step-4": "<mask token>\nimport math\n\n\ndef find_treasure_util(grid, i, j):\n rows, columns = len(grid), len(grid[0])\n queue = [((i, j), 0)]\n directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n visited = [[(-1) for _ in range(columns)] for _ in range(rows)]\n while queue:\n (x, y), step = queue.pop()\n visited[x][y] = step\n for direction in directions:\n curr_x = x + direction[0]\n curr_y = y + direction[1]\n if 0 <= curr_x < rows and 0 <= curr_y < columns and grid[curr_x][\n curr_y] == 'X':\n return step + 1\n elif 0 <= curr_x < rows and 0 <= curr_y < columns and grid[curr_x][\n curr_y] != 'D' and visited[curr_x][curr_y] == -1:\n queue.append(((curr_x, curr_y), step + 1))\n return -1\n\n\ndef find_treasure(grid):\n if not len(grid) or not len(grid[0]):\n return -1\n minimum_steps = math.inf\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if grid[i][j] == 'S':\n minimum_steps = min(minimum_steps, find_treasure_util(grid,\n i, j))\n return minimum_steps\n\n\nif __name__ == '__main__':\n grid = [['S', 'O', 'O', 'S', 'S'], ['D', 'O', 'D', 'O', 'D'], ['O', 'O',\n 'O', 'O', 'X'], ['X', 'D', 'D', 'O', 'O'], ['X', 'D', 'D', 'D', 'O']]\n print(find_treasure(grid))\n", "step-5": "\"\"\"\nYou have a map that marks the locations of treasure islands. Some of the map area has jagged rocks and dangerous reefs.\nOther areas are safe to sail in. There are other explorers trying to find the treasure.\nSo you must figure out a shortest route to one of the treasure islands.\n\nAssume the map area is a two dimensional grid, represented by a matrix of characters.\nYou must start from one of the starting point (marked as S) of the map and can move one block up, down,\nleft or right at a time. The treasure island is marked as X. Any block with dangerous rocks or reefs will be marked as\nD. You must not enter dangerous blocks. You cannot leave the map area. Other areas O are safe to sail in.\nOutput the minimum number of steps to get to any of the treasure islands.\n\"\"\"\n\nimport math\n\n\ndef find_treasure_util(grid, i, j):\n rows, columns = len(grid), len(grid[0])\n queue = [((i, j), 0)]\n directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]\n visited = [[-1 for _ in range(columns)] for _ in range(rows)]\n while queue:\n (x, y), step = queue.pop()\n visited[x][y] = step\n for direction in directions:\n curr_x = x + direction[0]\n curr_y = y + direction[1]\n if 0 <= curr_x < rows and 0 <= curr_y < columns and grid[curr_x][curr_y] == 'X':\n return step + 1\n elif 0 <= curr_x < rows and 0 <= curr_y < columns \\\n and grid[curr_x][curr_y] != 'D' \\\n and visited[curr_x][curr_y] == -1:\n queue.append(((curr_x, curr_y), step + 1))\n return -1\n\n\ndef find_treasure(grid):\n if not len(grid) or not len(grid[0]):\n return -1\n minimum_steps = math.inf\n for i in range(len(grid)):\n for j in range(len(grid[i])):\n if grid[i][j] == 'S':\n minimum_steps = min(minimum_steps, find_treasure_util(grid, i, j))\n return minimum_steps\n\n\nif __name__ == '__main__':\n grid = [['S', 'O', 'O', 'S', 'S'],\n ['D', 'O', 'D', 'O', 'D'],\n ['O', 'O', 'O', 'O', 'X'],\n ['X', 'D', 'D', 'O', 'O'],\n ['X', 'D', 'D', 'D', 'O']]\n print(find_treasure(grid))", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
# -*- coding: utf-8 -*- """ Created on Tue Aug 10 17:48:19 2021 @author: LESLY """ from PICO_PLACA_class import PICO_PLACA """ Main program of "Pico y Placa" predictor""" def main(): print("Predictor") placa = input("Enter the license of your vehicle in the following format AAA-####: ") fecha = input("Enter the date in the following format AA/MM/DD: ") hora = input("Enter the time in the following format 00:00: ") prog =PICO_PLACA(placa,fecha,hora) estado = prog.verificar() if estado == "continue": estado = prog.validar() print("Your vehicle " + estado ) else: print(estado) if __name__ == '__main__': main()
normal
{ "blob_id": "c7e5851a41e1cdb33cd0daa103fbf702da6e5ff7", "index": 9818, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef main():\n print('Predictor')\n placa = input(\n 'Enter the license of your vehicle in the following format AAA-####: '\n )\n fecha = input('Enter the date in the following format AA/MM/DD: ')\n hora = input('Enter the time in the following format 00:00: ')\n prog = PICO_PLACA(placa, fecha, hora)\n estado = prog.verificar()\n if estado == 'continue':\n estado = prog.validar()\n print('Your vehicle ' + estado)\n else:\n print(estado)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef main():\n print('Predictor')\n placa = input(\n 'Enter the license of your vehicle in the following format AAA-####: '\n )\n fecha = input('Enter the date in the following format AA/MM/DD: ')\n hora = input('Enter the time in the following format 00:00: ')\n prog = PICO_PLACA(placa, fecha, hora)\n estado = prog.verificar()\n if estado == 'continue':\n estado = prog.validar()\n print('Your vehicle ' + estado)\n else:\n print(estado)\n\n\nif __name__ == '__main__':\n main()\n", "step-4": "<mask token>\nfrom PICO_PLACA_class import PICO_PLACA\n<mask token>\n\n\ndef main():\n print('Predictor')\n placa = input(\n 'Enter the license of your vehicle in the following format AAA-####: '\n )\n fecha = input('Enter the date in the following format AA/MM/DD: ')\n hora = input('Enter the time in the following format 00:00: ')\n prog = PICO_PLACA(placa, fecha, hora)\n estado = prog.verificar()\n if estado == 'continue':\n estado = prog.validar()\n print('Your vehicle ' + estado)\n else:\n print(estado)\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Aug 10 17:48:19 2021\r\n\r\n@author: LESLY\r\n\"\"\"\r\n\r\n\r\nfrom PICO_PLACA_class import PICO_PLACA \r\n\r\n\"\"\" Main program of \"Pico y Placa\" predictor\"\"\"\r\ndef main():\r\n \r\n print(\"Predictor\")\r\n \r\n placa = input(\"Enter the license of your vehicle in the following format AAA-####: \")\r\n \r\n fecha = input(\"Enter the date in the following format AA/MM/DD: \") \r\n \r\n hora = input(\"Enter the time in the following format 00:00: \") \r\n\r\n \r\n prog =PICO_PLACA(placa,fecha,hora)\r\n estado = prog.verificar() \r\n \r\n if estado == \"continue\":\r\n estado = prog.validar()\r\n print(\"Your vehicle \" + estado ) \r\n else: \r\n print(estado)\r\n\r\nif __name__ == '__main__':\r\n main()", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import csv import json import re import itertools import pandas as pd import networkx as nx import matplotlib.pyplot as plt from networkx.algorithms import community import snap import numpy # setting up data structures to map actor IDs to objects in order to increase run time. csv.field_size_limit(100000000) curr_actor_id = 1 all_actors = dict() all_actors_id_map = dict() all_actors_frequencies = dict() edges = set() weights = dict() movies = list() movies_dict = dict() edges_last_60_20 = set() comm = list() PG = nx.Graph() class Actor: def __init__(self, name: str, id:int): self.filmography = set() self.name = name self.id = id def getFilms(self): return self.filmography def getName(self): return self.name def getId(self): return self.id def updateFilms(self, film:int): self.filmography.add(film) class Movie: def __init__(self, id: int): self.actors = set() self.name = "" self.id = id self.year = 0 def getName(self): return self.name def getActors(self): return self.actors def getId(self): return self.id def getDate(self): return self.year def updateActors(self, actor:Actor): self.actors.add(actor) def updateActors(self, actors_to_add:set()): for x in actors_to_add: self.actors.add(x) def setDate(self, i: int): self.year = i #parsing data from csv and dropping crew column reader = pd.read_csv('credits.csv', header = 0) crewless = reader.drop('crew', axis = 1) cleanup = re.compile('[^a-zA-Z\s]') #skip the header row row = crewless.iterrows() #loop through each row for x in range(len(reader.index)): cur_row = next(row) data = cur_row[1][0] id = cur_row[1][1] actors = set() #create an instance of a Movie for each row movie = Movie(int(id)) movies.append(movie) movies_dict[id] = movie #split the string around each name split_around_names = data.split('name') #parse actors, and create an instance of Actor for each actor in each movie for y in range(1, len(split_around_names)): #Cleaning up characters and spaces around the actor's name actorName = str(split_around_names[y].split('order')[0]) actorName = cleanup.sub(' ', actorName) actorName = actorName.strip() #Create the Actor and update his/her filmography if actorName not in all_actors.keys(): a = Actor(actorName, curr_actor_id) curr_actor_id += 1 a.updateFilms(movie) actors.add(a) all_actors[actorName] = a all_actors_frequencies[a] = 1 all_actors_id_map[curr_actor_id] = a else: all_actors[actorName].updateFilms(movie) all_actors_frequencies[a] += 1 actors.add(all_actors[actorName]) #Update the set of actors per movie movie.updateActors(actors) reader = pd.read_csv('movies_metadata.csv', header = 0) reader.drop(reader.columns.difference(['id', 'release_date']), 1, inplace=True) row = reader.iterrows() cleaned_actors = set() cleaned_movies_1 = set() cleaned_movies = set() # adding ids to movies from movie files for x in range(len(reader.index)): cur_row = next(row) id = cur_row[1][0] date = cur_row[1][1] id = int(id) year = date[:4] year_int = int(year) if id in movies_dict.keys(): movies_dict[id].setDate(year_int) cleaned_movies_1.add(movies_dict[id]) def clean(threshold: int): for actorName in all_actors.keys(): if len(all_actors[actorName].getFilms()) > threshold: cleaned_actors.add(all_actors[actorName]) else: for movie in all_actors[actorName].getFilms(): if all_actors[actorName] in movie.getActors(): movie.getActors().remove(all_actors[actorName]) def clean_movies(threshold: int): for movie in cleaned_movies_1: if 2017 - movie.getDate() <= threshold: cleaned_movies.add(movie) else: for actor in movie.getActors(): s = actor.getFilms() s.remove(movie) def createGraph(): counter = 0 G = nx.Graph() PG_actors = set() #fill graph with nodes for actor in cleaned_actors: G.add_node(actor.getId()) #generate a list of edges and weights based on frequencie of combination appearances for movie in cleaned_movies: actorIds = set() for actor in movie.getActors(): actorIds.add(actor.getId()) combinations = itertools.combinations(actorIds, 2) for comb in combinations: reverse = comb[::-1] if (comb not in edges) and (reverse not in edges): counter+=1 if (2017 - movie.getDate() < 60 and 2017 - movie.getDate() > 20): if (comb not in edges_last_60_20) and (reverse not in edges_last_60_20): edges_last_60_20.add(comb) edges.add(comb) weights[comb] = 1 else: if comb in edges: weights[comb] = weights[comb] + 1 elif reverse in edges: weights[reverse] = weights[reverse] + 1 G.add_edges_from(edges) for x in edges_last_60_20: if x[0] not in PG_actors: PG_actors.add(x[0]) if x[1] not in PG_actors: PG_actors.add(x[1]) PG.add_nodes_from(PG_actors) PG.add_edges_from(edges_last_60_20) return G def centrality_analysis(): types = [nx.eigenvector_centrality, nx.harmonic_centrality, nx.degree_centrality] for x in types: # based upon cleaning values chosen, choose a directory to store results to. file = open('./centrality/40_10/centrality_results_'+x.__name__+'.txt', 'w') nodes = x(graph) top_10 = list() top_10_ids = list() sorted_values = list(nodes.values()) sorted_values.sort() sorted_values.reverse() top_10 = sorted_values[0] # print(sorted_values) # for y in top_10: for x in nodes.keys(): if nodes[x] == top_10: top_10_ids.append(x) file.write(str(len(top_10_ids)) + '\n') for x in top_10_ids: for y in cleaned_actors: if x == y.getId(): print(y.getName()) #file.write(y.getName() + '\n') file.close() def community_analysis(): f = open('./community/communities_outputs.txt', 'w') communities_generator = nx.community.girvan_newman(graph) communities = next(communities_generator) size = len(communities) while size < 10: print(communities) communities = next(communities_generator) size = len(communities) f.write('community iteration: size = {}, {} \n'.format(size, communities)) def link_pred(): splPG = dict(nx.all_pairs_shortest_path_length(PG, cutoff=2)) friends_PG = list() for x in splPG.keys(): for y in splPG[x].keys(): if splPG[x][y] == 2: l = list() l.append(x) l.append(y) friends_PG.append(l) predictions = nx.jaccard_coefficient(PG, friends_PG) results = list() for x in predictions: results.append(x) results.sort(key=lambda x: x[2]) results.reverse() k_vals = [10,20,50,100] for k in k_vals: f = open('./link_pred/link_prediction_values_jaccard' + str(k) + '.txt', 'w') count = 0 while (count < k): print('({}, {}),jaccard: {}'.format(all_actors_id_map[results[count][0]].getName(), all_actors_id_map[results[count][1]].getName(), results[count][2])) f.write('({}, {}),jaccard: {}\n'.format(all_actors_id_map[results[count][0]].getName(),all_actors_id_map[results[count][1]].getName(),results[count][2])) count+=1 top_k = list() precision_at_k = 0 for x in range(k): top_k.append(results[x]) count = 0 for val in top_k: tup = (val[0], val[1]) if tup in edges: count += 1 precision_at_k = count / k print('precision @ K{}: {}\n'.format(k, precision_at_k)) f.write('precision @ K{}: {}'.format(k, precision_at_k)) f.close() #Convert community results from IDs to Actor name def convert_id_actor(): file = open('./community_/communities_outputs.txt') for row in file: items = row.split(', ') i = 0 while i < len(items): items[i].strip('\n') items[i] = int(items[i]) i+=1 i = 0 this_row = list() i= 0 while i < len(items): this_row.append(items[i]) i+=1 comm.append(this_row) file.close() file = open('./actorname_communities.txt', 'w') for x in range(len(comm)): for y in range(len(comm[x])): try: comm[x][y] = all_actors_id_map[comm[x][y]].getName() except: comm[x][y] = 'None' comm.reverse() for x in range(len(comm)): print("Community #{}: {}".format(x, comm[x])) file.write("Community #{}: {}\n".format(x, comm[x])) file.flush() file.close() clean_movies(60) clean(30) graph = createGraph() print(nx.info(graph)) print(nx.info(PG)) # To perform the analysis, uncomment the respective function(s); additionally, uncomment #convert_id_actor() for community_analysis. # centrality_analysis() # community_analysis() # convert_id_actor() # link_pred()
normal
{ "blob_id": "0934163fc6461e30a73c06e74b3a5e983ed2fa02", "index": 4211, "step-1": "<mask token>\n\n\nclass Movie:\n\n def __init__(self, id: int):\n self.actors = set()\n self.name = ''\n self.id = id\n self.year = 0\n\n def getName(self):\n return self.name\n\n def getActors(self):\n return self.actors\n\n def getId(self):\n return self.id\n\n def getDate(self):\n return self.year\n <mask token>\n\n def updateActors(self, actors_to_add: set()):\n for x in actors_to_add:\n self.actors.add(x)\n <mask token>\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass Actor:\n\n def __init__(self, name: str, id: int):\n self.filmography = set()\n self.name = name\n self.id = id\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Movie:\n\n def __init__(self, id: int):\n self.actors = set()\n self.name = ''\n self.id = id\n self.year = 0\n\n def getName(self):\n return self.name\n\n def getActors(self):\n return self.actors\n\n def getId(self):\n return self.id\n\n def getDate(self):\n return self.year\n\n def updateActors(self, actor: Actor):\n self.actors.add(actor)\n\n def updateActors(self, actors_to_add: set()):\n for x in actors_to_add:\n self.actors.add(x)\n\n def setDate(self, i: int):\n self.year = i\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass Actor:\n\n def __init__(self, name: str, id: int):\n self.filmography = set()\n self.name = name\n self.id = id\n\n def getFilms(self):\n return self.filmography\n\n def getName(self):\n return self.name\n\n def getId(self):\n return self.id\n\n def updateFilms(self, film: int):\n self.filmography.add(film)\n\n\nclass Movie:\n\n def __init__(self, id: int):\n self.actors = set()\n self.name = ''\n self.id = id\n self.year = 0\n\n def getName(self):\n return self.name\n\n def getActors(self):\n return self.actors\n\n def getId(self):\n return self.id\n\n def getDate(self):\n return self.year\n\n def updateActors(self, actor: Actor):\n self.actors.add(actor)\n\n def updateActors(self, actors_to_add: set()):\n for x in actors_to_add:\n self.actors.add(x)\n\n def setDate(self, i: int):\n self.year = i\n\n\n<mask token>\n\n\ndef community_analysis():\n f = open('./community/communities_outputs.txt', 'w')\n communities_generator = nx.community.girvan_newman(graph)\n communities = next(communities_generator)\n size = len(communities)\n while size < 10:\n print(communities)\n communities = next(communities_generator)\n size = len(communities)\n f.write('community iteration: size = {}, {} \\n'.format(size,\n communities))\n\n\ndef link_pred():\n splPG = dict(nx.all_pairs_shortest_path_length(PG, cutoff=2))\n friends_PG = list()\n for x in splPG.keys():\n for y in splPG[x].keys():\n if splPG[x][y] == 2:\n l = list()\n l.append(x)\n l.append(y)\n friends_PG.append(l)\n predictions = nx.jaccard_coefficient(PG, friends_PG)\n results = list()\n for x in predictions:\n results.append(x)\n results.sort(key=lambda x: x[2])\n results.reverse()\n k_vals = [10, 20, 50, 100]\n for k in k_vals:\n f = open('./link_pred/link_prediction_values_jaccard' + str(k) +\n '.txt', 'w')\n count = 0\n while count < k:\n print('({}, {}),jaccard: {}'.format(all_actors_id_map[results[\n count][0]].getName(), all_actors_id_map[results[count][1]].\n getName(), results[count][2]))\n f.write('({}, {}),jaccard: {}\\n'.format(all_actors_id_map[\n results[count][0]].getName(), all_actors_id_map[results[\n count][1]].getName(), results[count][2]))\n count += 1\n top_k = list()\n precision_at_k = 0\n for x in range(k):\n top_k.append(results[x])\n count = 0\n for val in top_k:\n tup = val[0], val[1]\n if tup in edges:\n count += 1\n precision_at_k = count / k\n print('precision @ K{}: {}\\n'.format(k, precision_at_k))\n f.write('precision @ K{}: {}'.format(k, precision_at_k))\n f.close()\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass Actor:\n\n def __init__(self, name: str, id: int):\n self.filmography = set()\n self.name = name\n self.id = id\n\n def getFilms(self):\n return self.filmography\n\n def getName(self):\n return self.name\n\n def getId(self):\n return self.id\n\n def updateFilms(self, film: int):\n self.filmography.add(film)\n\n\nclass Movie:\n\n def __init__(self, id: int):\n self.actors = set()\n self.name = ''\n self.id = id\n self.year = 0\n\n def getName(self):\n return self.name\n\n def getActors(self):\n return self.actors\n\n def getId(self):\n return self.id\n\n def getDate(self):\n return self.year\n\n def updateActors(self, actor: Actor):\n self.actors.add(actor)\n\n def updateActors(self, actors_to_add: set()):\n for x in actors_to_add:\n self.actors.add(x)\n\n def setDate(self, i: int):\n self.year = i\n\n\n<mask token>\n\n\ndef clean(threshold: int):\n for actorName in all_actors.keys():\n if len(all_actors[actorName].getFilms()) > threshold:\n cleaned_actors.add(all_actors[actorName])\n else:\n for movie in all_actors[actorName].getFilms():\n if all_actors[actorName] in movie.getActors():\n movie.getActors().remove(all_actors[actorName])\n\n\ndef clean_movies(threshold: int):\n for movie in cleaned_movies_1:\n if 2017 - movie.getDate() <= threshold:\n cleaned_movies.add(movie)\n else:\n for actor in movie.getActors():\n s = actor.getFilms()\n s.remove(movie)\n\n\ndef createGraph():\n counter = 0\n G = nx.Graph()\n PG_actors = set()\n for actor in cleaned_actors:\n G.add_node(actor.getId())\n for movie in cleaned_movies:\n actorIds = set()\n for actor in movie.getActors():\n actorIds.add(actor.getId())\n combinations = itertools.combinations(actorIds, 2)\n for comb in combinations:\n reverse = comb[::-1]\n if comb not in edges and reverse not in edges:\n counter += 1\n if 2017 - movie.getDate() < 60 and 2017 - movie.getDate() > 20:\n if (comb not in edges_last_60_20 and reverse not in\n edges_last_60_20):\n edges_last_60_20.add(comb)\n edges.add(comb)\n weights[comb] = 1\n elif comb in edges:\n weights[comb] = weights[comb] + 1\n elif reverse in edges:\n weights[reverse] = weights[reverse] + 1\n G.add_edges_from(edges)\n for x in edges_last_60_20:\n if x[0] not in PG_actors:\n PG_actors.add(x[0])\n if x[1] not in PG_actors:\n PG_actors.add(x[1])\n PG.add_nodes_from(PG_actors)\n PG.add_edges_from(edges_last_60_20)\n return G\n\n\ndef centrality_analysis():\n types = [nx.eigenvector_centrality, nx.harmonic_centrality, nx.\n degree_centrality]\n for x in types:\n file = open('./centrality/40_10/centrality_results_' + x.__name__ +\n '.txt', 'w')\n nodes = x(graph)\n top_10 = list()\n top_10_ids = list()\n sorted_values = list(nodes.values())\n sorted_values.sort()\n sorted_values.reverse()\n top_10 = sorted_values[0]\n for x in nodes.keys():\n if nodes[x] == top_10:\n top_10_ids.append(x)\n file.write(str(len(top_10_ids)) + '\\n')\n for x in top_10_ids:\n for y in cleaned_actors:\n if x == y.getId():\n print(y.getName())\n file.close()\n\n\ndef community_analysis():\n f = open('./community/communities_outputs.txt', 'w')\n communities_generator = nx.community.girvan_newman(graph)\n communities = next(communities_generator)\n size = len(communities)\n while size < 10:\n print(communities)\n communities = next(communities_generator)\n size = len(communities)\n f.write('community iteration: size = {}, {} \\n'.format(size,\n communities))\n\n\ndef link_pred():\n splPG = dict(nx.all_pairs_shortest_path_length(PG, cutoff=2))\n friends_PG = list()\n for x in splPG.keys():\n for y in splPG[x].keys():\n if splPG[x][y] == 2:\n l = list()\n l.append(x)\n l.append(y)\n friends_PG.append(l)\n predictions = nx.jaccard_coefficient(PG, friends_PG)\n results = list()\n for x in predictions:\n results.append(x)\n results.sort(key=lambda x: x[2])\n results.reverse()\n k_vals = [10, 20, 50, 100]\n for k in k_vals:\n f = open('./link_pred/link_prediction_values_jaccard' + str(k) +\n '.txt', 'w')\n count = 0\n while count < k:\n print('({}, {}),jaccard: {}'.format(all_actors_id_map[results[\n count][0]].getName(), all_actors_id_map[results[count][1]].\n getName(), results[count][2]))\n f.write('({}, {}),jaccard: {}\\n'.format(all_actors_id_map[\n results[count][0]].getName(), all_actors_id_map[results[\n count][1]].getName(), results[count][2]))\n count += 1\n top_k = list()\n precision_at_k = 0\n for x in range(k):\n top_k.append(results[x])\n count = 0\n for val in top_k:\n tup = val[0], val[1]\n if tup in edges:\n count += 1\n precision_at_k = count / k\n print('precision @ K{}: {}\\n'.format(k, precision_at_k))\n f.write('precision @ K{}: {}'.format(k, precision_at_k))\n f.close()\n\n\ndef convert_id_actor():\n file = open('./community_/communities_outputs.txt')\n for row in file:\n items = row.split(', ')\n i = 0\n while i < len(items):\n items[i].strip('\\n')\n items[i] = int(items[i])\n i += 1\n i = 0\n this_row = list()\n i = 0\n while i < len(items):\n this_row.append(items[i])\n i += 1\n comm.append(this_row)\n file.close()\n file = open('./actorname_communities.txt', 'w')\n for x in range(len(comm)):\n for y in range(len(comm[x])):\n try:\n comm[x][y] = all_actors_id_map[comm[x][y]].getName()\n except:\n comm[x][y] = 'None'\n comm.reverse()\n for x in range(len(comm)):\n print('Community #{}: {}'.format(x, comm[x]))\n file.write('Community #{}: {}\\n'.format(x, comm[x]))\n file.flush()\n file.close()\n\n\n<mask token>\n", "step-5": "import csv\nimport json\nimport re\nimport itertools\nimport pandas as pd\nimport networkx as nx\nimport matplotlib.pyplot as plt\nfrom networkx.algorithms import community\nimport snap\nimport numpy\n\n# setting up data structures to map actor IDs to objects in order to increase run time.\ncsv.field_size_limit(100000000)\ncurr_actor_id = 1\nall_actors = dict()\nall_actors_id_map = dict()\nall_actors_frequencies = dict()\nedges = set()\nweights = dict()\nmovies = list()\nmovies_dict = dict()\nedges_last_60_20 = set()\ncomm = list()\nPG = nx.Graph()\n\nclass Actor:\n\n def __init__(self, name: str, id:int):\n self.filmography = set()\n self.name = name\n self.id = id\n def getFilms(self):\n return self.filmography\n\n def getName(self):\n return self.name\n\n def getId(self):\n return self.id\n\n def updateFilms(self, film:int):\n self.filmography.add(film)\n\n\nclass Movie:\n\n def __init__(self, id: int):\n self.actors = set()\n self.name = \"\"\n self.id = id\n self.year = 0\n\n def getName(self):\n return self.name\n\n def getActors(self):\n return self.actors\n\n def getId(self):\n return self.id\n\n def getDate(self):\n return self.year\n\n def updateActors(self, actor:Actor):\n self.actors.add(actor)\n\n def updateActors(self, actors_to_add:set()):\n for x in actors_to_add:\n self.actors.add(x)\n\n def setDate(self, i: int):\n self.year = i\n\n#parsing data from csv and dropping crew column\nreader = pd.read_csv('credits.csv', header = 0)\ncrewless = reader.drop('crew', axis = 1)\ncleanup = re.compile('[^a-zA-Z\\s]')\n\n#skip the header row\nrow = crewless.iterrows()\n\n#loop through each row\nfor x in range(len(reader.index)):\n cur_row = next(row)\n data = cur_row[1][0]\n id = cur_row[1][1]\n actors = set()\n\n #create an instance of a Movie for each row\n movie = Movie(int(id))\n movies.append(movie)\n movies_dict[id] = movie\n\n #split the string around each name\n split_around_names = data.split('name')\n\n #parse actors, and create an instance of Actor for each actor in each movie\n for y in range(1, len(split_around_names)):\n #Cleaning up characters and spaces around the actor's name\n actorName = str(split_around_names[y].split('order')[0])\n actorName = cleanup.sub(' ', actorName)\n actorName = actorName.strip()\n #Create the Actor and update his/her filmography\n if actorName not in all_actors.keys():\n a = Actor(actorName, curr_actor_id)\n curr_actor_id += 1\n a.updateFilms(movie)\n actors.add(a)\n all_actors[actorName] = a\n all_actors_frequencies[a] = 1\n all_actors_id_map[curr_actor_id] = a\n else:\n all_actors[actorName].updateFilms(movie)\n all_actors_frequencies[a] += 1\n actors.add(all_actors[actorName])\n #Update the set of actors per movie\n movie.updateActors(actors)\n\nreader = pd.read_csv('movies_metadata.csv', header = 0)\nreader.drop(reader.columns.difference(['id', 'release_date']), 1, inplace=True)\nrow = reader.iterrows()\n\ncleaned_actors = set()\ncleaned_movies_1 = set()\ncleaned_movies = set()\n\n# adding ids to movies from movie files\nfor x in range(len(reader.index)):\n cur_row = next(row)\n id = cur_row[1][0]\n date = cur_row[1][1]\n id = int(id)\n year = date[:4]\n year_int = int(year)\n if id in movies_dict.keys():\n movies_dict[id].setDate(year_int)\n cleaned_movies_1.add(movies_dict[id])\n\n\ndef clean(threshold: int):\n for actorName in all_actors.keys():\n if len(all_actors[actorName].getFilms()) > threshold:\n cleaned_actors.add(all_actors[actorName])\n else:\n for movie in all_actors[actorName].getFilms():\n if all_actors[actorName] in movie.getActors():\n movie.getActors().remove(all_actors[actorName])\n\n\ndef clean_movies(threshold: int):\n for movie in cleaned_movies_1:\n if 2017 - movie.getDate() <= threshold:\n cleaned_movies.add(movie)\n else:\n for actor in movie.getActors():\n s = actor.getFilms()\n s.remove(movie)\n\n\ndef createGraph():\n counter = 0\n G = nx.Graph()\n PG_actors = set()\n\n #fill graph with nodes\n for actor in cleaned_actors:\n G.add_node(actor.getId())\n\n #generate a list of edges and weights based on frequencie of combination appearances\n for movie in cleaned_movies:\n actorIds = set()\n for actor in movie.getActors():\n actorIds.add(actor.getId())\n combinations = itertools.combinations(actorIds, 2)\n for comb in combinations:\n reverse = comb[::-1]\n if (comb not in edges) and (reverse not in edges):\n counter+=1\n if (2017 - movie.getDate() < 60 and 2017 - movie.getDate() > 20):\n if (comb not in edges_last_60_20) and (reverse not in edges_last_60_20):\n edges_last_60_20.add(comb)\n edges.add(comb)\n weights[comb] = 1\n else:\n if comb in edges:\n weights[comb] = weights[comb] + 1\n elif reverse in edges:\n weights[reverse] = weights[reverse] + 1\n G.add_edges_from(edges)\n for x in edges_last_60_20:\n if x[0] not in PG_actors:\n PG_actors.add(x[0])\n if x[1] not in PG_actors:\n PG_actors.add(x[1])\n PG.add_nodes_from(PG_actors)\n PG.add_edges_from(edges_last_60_20)\n return G\n\n\ndef centrality_analysis():\n types = [nx.eigenvector_centrality, nx.harmonic_centrality, nx.degree_centrality]\n\n for x in types:\n\n # based upon cleaning values chosen, choose a directory to store results to.\n file = open('./centrality/40_10/centrality_results_'+x.__name__+'.txt', 'w')\n nodes = x(graph)\n top_10 = list()\n top_10_ids = list()\n\n sorted_values = list(nodes.values())\n sorted_values.sort()\n sorted_values.reverse()\n\n top_10 = sorted_values[0]\n # print(sorted_values)\n\n # for y in top_10:\n for x in nodes.keys():\n if nodes[x] == top_10:\n top_10_ids.append(x)\n\n file.write(str(len(top_10_ids)) + '\\n')\n for x in top_10_ids:\n for y in cleaned_actors:\n if x == y.getId():\n print(y.getName())\n #file.write(y.getName() + '\\n')\n file.close()\n\n\ndef community_analysis():\n f = open('./community/communities_outputs.txt', 'w')\n communities_generator = nx.community.girvan_newman(graph)\n communities = next(communities_generator)\n size = len(communities)\n while size < 10:\n print(communities)\n communities = next(communities_generator)\n size = len(communities)\n f.write('community iteration: size = {}, {} \\n'.format(size, communities))\n\n\ndef link_pred():\n splPG = dict(nx.all_pairs_shortest_path_length(PG, cutoff=2))\n friends_PG = list()\n for x in splPG.keys():\n for y in splPG[x].keys():\n if splPG[x][y] == 2:\n l = list()\n l.append(x)\n l.append(y)\n friends_PG.append(l)\n predictions = nx.jaccard_coefficient(PG, friends_PG)\n results = list()\n for x in predictions:\n results.append(x)\n results.sort(key=lambda x: x[2])\n results.reverse()\n\n k_vals = [10,20,50,100]\n for k in k_vals:\n f = open('./link_pred/link_prediction_values_jaccard' + str(k) + '.txt', 'w')\n count = 0\n while (count < k):\n print('({}, {}),jaccard: {}'.format(all_actors_id_map[results[count][0]].getName(), all_actors_id_map[results[count][1]].getName(), results[count][2]))\n f.write('({}, {}),jaccard: {}\\n'.format(all_actors_id_map[results[count][0]].getName(),all_actors_id_map[results[count][1]].getName(),results[count][2]))\n count+=1\n top_k = list()\n precision_at_k = 0\n for x in range(k):\n top_k.append(results[x])\n count = 0\n for val in top_k:\n tup = (val[0], val[1])\n if tup in edges:\n count += 1\n precision_at_k = count / k\n print('precision @ K{}: {}\\n'.format(k, precision_at_k))\n f.write('precision @ K{}: {}'.format(k, precision_at_k))\n f.close()\n\n#Convert community results from IDs to Actor name\ndef convert_id_actor():\n file = open('./community_/communities_outputs.txt')\n for row in file:\n items = row.split(', ')\n i = 0\n while i < len(items):\n items[i].strip('\\n')\n items[i] = int(items[i])\n i+=1\n i = 0\n this_row = list()\n i= 0\n while i < len(items):\n this_row.append(items[i])\n i+=1\n comm.append(this_row)\n file.close()\n file = open('./actorname_communities.txt', 'w')\n for x in range(len(comm)):\n for y in range(len(comm[x])):\n try:\n comm[x][y] = all_actors_id_map[comm[x][y]].getName()\n except:\n comm[x][y] = 'None'\n comm.reverse()\n for x in range(len(comm)):\n print(\"Community #{}: {}\".format(x, comm[x]))\n file.write(\"Community #{}: {}\\n\".format(x, comm[x]))\n file.flush()\n file.close()\n\n\nclean_movies(60)\nclean(30)\n\ngraph = createGraph()\nprint(nx.info(graph))\nprint(nx.info(PG))\n\n\n# To perform the analysis, uncomment the respective function(s); additionally, uncomment #convert_id_actor() for community_analysis.\n# centrality_analysis()\n# community_analysis()\n# convert_id_actor()\n# link_pred()\n", "step-ids": [ 7, 11, 17, 22, 26 ] }
[ 7, 11, 17, 22, 26 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> try: new = list(map(lambda x: 2 / x, new_list)) except ZeroDivisionError: pass print(new) <|reserved_special_token_1|> my_list = [1, 2, 4, 0, 4, 0, 10, 20, 0, 1] new_list = list(filter(lambda x: x != 0, my_list)) try: new = list(map(lambda x: 2 / x, new_list)) except ZeroDivisionError: pass print(new) <|reserved_special_token_1|> my_list = [1, 2, 4, 0, 4, 0, 10, 20, 0, 1] new_list = list(filter(lambda x: x != 0, my_list)) try: new = list(map(lambda x: 2 / x, new_list)) except ZeroDivisionError: pass print(new) # def devis(n, list): # new_list = [] # for i, m_list in enumerate(list): # try: # new_list.append(n/m_list) # except ZeroDivisionError: # new_list.append(None) # return new_list # print(devis(2, my_list))
flexible
{ "blob_id": "46f3d3681343d96889ddb073f17ff7f225486f35", "index": 8005, "step-1": "<mask token>\n", "step-2": "<mask token>\ntry:\n new = list(map(lambda x: 2 / x, new_list))\nexcept ZeroDivisionError:\n pass\nprint(new)\n", "step-3": "my_list = [1, 2, 4, 0, 4, 0, 10, 20, 0, 1]\nnew_list = list(filter(lambda x: x != 0, my_list))\ntry:\n new = list(map(lambda x: 2 / x, new_list))\nexcept ZeroDivisionError:\n pass\nprint(new)\n", "step-4": "my_list = [1, 2, 4, 0, 4, 0, 10, 20, 0, 1]\nnew_list = list(filter(lambda x: x != 0, my_list))\n\ntry:\n new = list(map(lambda x: 2 / x, new_list))\nexcept ZeroDivisionError:\n pass\n\nprint(new)\n\n\n\n\n\n# def devis(n, list):\n# new_list = []\n# for i, m_list in enumerate(list):\n# try:\n# new_list.append(n/m_list)\n# except ZeroDivisionError:\n# new_list.append(None)\n# return new_list\n# print(devis(2, my_list))\n\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from ctypes import CDLL svg2pdf = CDLL("./libsvg2pdf.so") svg2pdf.svg2pdf("report.svg", "teste2.pdf") svg2pdf.svg2pdf2("report.svg", "teste3.pdf")
normal
{ "blob_id": "9c85252b4048b5412978b3ac05cd6dde4479e3bf", "index": 3333, "step-1": "<mask token>\n", "step-2": "<mask token>\nsvg2pdf.svg2pdf('report.svg', 'teste2.pdf')\nsvg2pdf.svg2pdf2('report.svg', 'teste3.pdf')\n", "step-3": "<mask token>\nsvg2pdf = CDLL('./libsvg2pdf.so')\nsvg2pdf.svg2pdf('report.svg', 'teste2.pdf')\nsvg2pdf.svg2pdf2('report.svg', 'teste3.pdf')\n", "step-4": "from ctypes import CDLL\nsvg2pdf = CDLL('./libsvg2pdf.so')\nsvg2pdf.svg2pdf('report.svg', 'teste2.pdf')\nsvg2pdf.svg2pdf2('report.svg', 'teste3.pdf')\n", "step-5": "from ctypes import CDLL\nsvg2pdf = CDLL(\"./libsvg2pdf.so\")\nsvg2pdf.svg2pdf(\"report.svg\", \"teste2.pdf\")\nsvg2pdf.svg2pdf2(\"report.svg\", \"teste3.pdf\")\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> class StatsControllerTestCase(unittest.TestCase): def setUp(self): pR = PersonRepository() aR = ActivityRepository() self.L = StatsController(pR, aR) self.p = Person(1, 'John', '1', 'A') self.q = Person(2, 'Mary', '1', 'B') self.a1 = Activity(self.p, '2015.12.20', '12:12', 'Swimming') self.a2 = Activity(self.p, '2016.01.20', '12:12', 'Mapping') self.a3 = Activity(self.q, '2015.12.21', '12:12', 'Swimming') self.a4 = Activity(self.q, '2015.12.20', '10:12', 'Reading') pR.add(self.p) pR.add(self.q) aR.add(self.a1) aR.add(self.a2) aR.add(self.a3) aR.add(self.a4) <|reserved_special_token_0|> <|reserved_special_token_0|> def test_people_with_activities_in_interval(self): L = self.L p = self.p q = self.q assert L.people_with_activities_in_interval('2015.12.20', '2016.01.01' ) == [p, q] assert L.people_with_activities_in_interval('2000.01.01', '2010.01.01' ) == [] assert L.people_with_activities_in_interval('2016.01.01', '2017.01.01' ) == [p] assert L.people_with_activities_in_interval('2015.12.21', '2015.12.21' ) == [q] <|reserved_special_token_0|> def test_activities_in_interval_by_date(self): L = self.L a1 = self.a1 a2 = self.a2 a3 = self.a3 a4 = self.a4 assert L.activities_in_interval_by_date('2015.12.20', '2016.01.01' ) == [a4, a1, a3] assert L.activities_in_interval_by_date('2000.01.01', '2010.01.01' ) == [] assert L.activities_in_interval_by_date('2016.01.01', '2017.01.01' ) == [a2] assert L.activities_in_interval_by_date('2015.12.21', '2015.12.21' ) == [a3] <|reserved_special_token_1|> <|reserved_special_token_0|> class StatsControllerTestCase(unittest.TestCase): def setUp(self): pR = PersonRepository() aR = ActivityRepository() self.L = StatsController(pR, aR) self.p = Person(1, 'John', '1', 'A') self.q = Person(2, 'Mary', '1', 'B') self.a1 = Activity(self.p, '2015.12.20', '12:12', 'Swimming') self.a2 = Activity(self.p, '2016.01.20', '12:12', 'Mapping') self.a3 = Activity(self.q, '2015.12.21', '12:12', 'Swimming') self.a4 = Activity(self.q, '2015.12.20', '10:12', 'Reading') pR.add(self.p) pR.add(self.q) aR.add(self.a1) aR.add(self.a2) aR.add(self.a3) aR.add(self.a4) <|reserved_special_token_0|> def test_activities_for_person_by_date(self): L = self.L a1 = self.a1 a2 = self.a2 a3 = self.a3 a4 = self.a4 assert L.activities_for_person_by_date(1) == [a1, a2] assert L.activities_for_person_by_date(2) == [a4, a3] assert L.activities_for_person_by_date(4) == [] def test_people_with_activities_in_interval(self): L = self.L p = self.p q = self.q assert L.people_with_activities_in_interval('2015.12.20', '2016.01.01' ) == [p, q] assert L.people_with_activities_in_interval('2000.01.01', '2010.01.01' ) == [] assert L.people_with_activities_in_interval('2016.01.01', '2017.01.01' ) == [p] assert L.people_with_activities_in_interval('2015.12.21', '2015.12.21' ) == [q] <|reserved_special_token_0|> def test_activities_in_interval_by_date(self): L = self.L a1 = self.a1 a2 = self.a2 a3 = self.a3 a4 = self.a4 assert L.activities_in_interval_by_date('2015.12.20', '2016.01.01' ) == [a4, a1, a3] assert L.activities_in_interval_by_date('2000.01.01', '2010.01.01' ) == [] assert L.activities_in_interval_by_date('2016.01.01', '2017.01.01' ) == [a2] assert L.activities_in_interval_by_date('2015.12.21', '2015.12.21' ) == [a3] <|reserved_special_token_1|> <|reserved_special_token_0|> class StatsControllerTestCase(unittest.TestCase): def setUp(self): pR = PersonRepository() aR = ActivityRepository() self.L = StatsController(pR, aR) self.p = Person(1, 'John', '1', 'A') self.q = Person(2, 'Mary', '1', 'B') self.a1 = Activity(self.p, '2015.12.20', '12:12', 'Swimming') self.a2 = Activity(self.p, '2016.01.20', '12:12', 'Mapping') self.a3 = Activity(self.q, '2015.12.21', '12:12', 'Swimming') self.a4 = Activity(self.q, '2015.12.20', '10:12', 'Reading') pR.add(self.p) pR.add(self.q) aR.add(self.a1) aR.add(self.a2) aR.add(self.a3) aR.add(self.a4) def test_activities_for_person_alphabetically(self): L = self.L a1 = self.a1 a2 = self.a2 a3 = self.a3 a4 = self.a4 assert L.activities_for_person_alphabetically(1) == [a2, a1] assert L.activities_for_person_alphabetically(2) == [a4, a3] assert L.activities_for_person_alphabetically(4) == [] def test_activities_for_person_by_date(self): L = self.L a1 = self.a1 a2 = self.a2 a3 = self.a3 a4 = self.a4 assert L.activities_for_person_by_date(1) == [a1, a2] assert L.activities_for_person_by_date(2) == [a4, a3] assert L.activities_for_person_by_date(4) == [] def test_people_with_activities_in_interval(self): L = self.L p = self.p q = self.q assert L.people_with_activities_in_interval('2015.12.20', '2016.01.01' ) == [p, q] assert L.people_with_activities_in_interval('2000.01.01', '2010.01.01' ) == [] assert L.people_with_activities_in_interval('2016.01.01', '2017.01.01' ) == [p] assert L.people_with_activities_in_interval('2015.12.21', '2015.12.21' ) == [q] <|reserved_special_token_0|> def test_activities_in_interval_by_date(self): L = self.L a1 = self.a1 a2 = self.a2 a3 = self.a3 a4 = self.a4 assert L.activities_in_interval_by_date('2015.12.20', '2016.01.01' ) == [a4, a1, a3] assert L.activities_in_interval_by_date('2000.01.01', '2010.01.01' ) == [] assert L.activities_in_interval_by_date('2016.01.01', '2017.01.01' ) == [a2] assert L.activities_in_interval_by_date('2015.12.21', '2015.12.21' ) == [a3] <|reserved_special_token_1|> <|reserved_special_token_0|> class StatsControllerTestCase(unittest.TestCase): def setUp(self): pR = PersonRepository() aR = ActivityRepository() self.L = StatsController(pR, aR) self.p = Person(1, 'John', '1', 'A') self.q = Person(2, 'Mary', '1', 'B') self.a1 = Activity(self.p, '2015.12.20', '12:12', 'Swimming') self.a2 = Activity(self.p, '2016.01.20', '12:12', 'Mapping') self.a3 = Activity(self.q, '2015.12.21', '12:12', 'Swimming') self.a4 = Activity(self.q, '2015.12.20', '10:12', 'Reading') pR.add(self.p) pR.add(self.q) aR.add(self.a1) aR.add(self.a2) aR.add(self.a3) aR.add(self.a4) def test_activities_for_person_alphabetically(self): L = self.L a1 = self.a1 a2 = self.a2 a3 = self.a3 a4 = self.a4 assert L.activities_for_person_alphabetically(1) == [a2, a1] assert L.activities_for_person_alphabetically(2) == [a4, a3] assert L.activities_for_person_alphabetically(4) == [] def test_activities_for_person_by_date(self): L = self.L a1 = self.a1 a2 = self.a2 a3 = self.a3 a4 = self.a4 assert L.activities_for_person_by_date(1) == [a1, a2] assert L.activities_for_person_by_date(2) == [a4, a3] assert L.activities_for_person_by_date(4) == [] def test_people_with_activities_in_interval(self): L = self.L p = self.p q = self.q assert L.people_with_activities_in_interval('2015.12.20', '2016.01.01' ) == [p, q] assert L.people_with_activities_in_interval('2000.01.01', '2010.01.01' ) == [] assert L.people_with_activities_in_interval('2016.01.01', '2017.01.01' ) == [p] assert L.people_with_activities_in_interval('2015.12.21', '2015.12.21' ) == [q] def test_activities_in_interval_alphabetically(self): L = self.L a1 = self.a1 a2 = self.a2 a3 = self.a3 a4 = self.a4 assert L.activities_in_interval_alphabetically('2015.12.20', '2016.01.01') == [a4, a1, a3] assert L.activities_in_interval_alphabetically('2000.01.01', '2010.01.01') == [] assert L.activities_in_interval_alphabetically('2016.01.01', '2017.01.01') == [a2] assert L.activities_in_interval_alphabetically('2015.12.21', '2015.12.21') == [a3] def test_activities_in_interval_by_date(self): L = self.L a1 = self.a1 a2 = self.a2 a3 = self.a3 a4 = self.a4 assert L.activities_in_interval_by_date('2015.12.20', '2016.01.01' ) == [a4, a1, a3] assert L.activities_in_interval_by_date('2000.01.01', '2010.01.01' ) == [] assert L.activities_in_interval_by_date('2016.01.01', '2017.01.01' ) == [a2] assert L.activities_in_interval_by_date('2015.12.21', '2015.12.21' ) == [a3] <|reserved_special_token_1|> import unittest from domain.Activity import Activity from domain.NABException import NABException from domain.Person import Person from domain.ActivityValidator import ActivityValidator from repository.PersonRepository import PersonRepository from repository.PersonFileRepository import PersonFileRepository from repository.ActivityRepository import ActivityRepository from repository.ActivityFileRepository import ActivityFileRepository from controller.StatsController import StatsController class StatsControllerTestCase(unittest.TestCase): def setUp(self): pR = PersonRepository() aR = ActivityRepository() self.L = StatsController(pR, aR) self.p = Person(1, "John", "1", "A") self.q = Person(2, "Mary", "1", "B") self.a1 = Activity(self.p, "2015.12.20", "12:12", "Swimming") self.a2 = Activity(self.p, "2016.01.20", "12:12", "Mapping") self.a3 = Activity(self.q, "2015.12.21", "12:12", "Swimming") self.a4 = Activity(self.q, "2015.12.20", "10:12", "Reading") pR.add(self.p) pR.add(self.q) aR.add(self.a1) aR.add(self.a2) aR.add(self.a3) aR.add(self.a4) def test_activities_for_person_alphabetically(self): L = self.L a1 = self.a1 a2 = self.a2 a3 = self.a3 a4 = self.a4 assert L.activities_for_person_alphabetically(1) == [a2, a1] assert L.activities_for_person_alphabetically(2) == [a4, a3] assert L.activities_for_person_alphabetically(4) == [] def test_activities_for_person_by_date(self): L = self.L a1 = self.a1 a2 = self.a2 a3 = self.a3 a4 = self.a4 assert L.activities_for_person_by_date(1) == [a1, a2] assert L.activities_for_person_by_date(2) == [a4, a3] assert L.activities_for_person_by_date(4) == [] def test_people_with_activities_in_interval(self): L = self.L p = self.p q = self.q assert L.people_with_activities_in_interval("2015.12.20", "2016.01.01") == [p, q] assert L.people_with_activities_in_interval("2000.01.01", "2010.01.01") == [] assert L.people_with_activities_in_interval("2016.01.01", "2017.01.01") == [p] assert L.people_with_activities_in_interval("2015.12.21", "2015.12.21") == [q] def test_activities_in_interval_alphabetically(self): L = self.L a1 = self.a1 a2 = self.a2 a3 = self.a3 a4 = self.a4 assert L.activities_in_interval_alphabetically("2015.12.20", "2016.01.01") == [a4, a1, a3] assert L.activities_in_interval_alphabetically("2000.01.01", "2010.01.01") == [] assert L.activities_in_interval_alphabetically("2016.01.01", "2017.01.01") == [a2] assert L.activities_in_interval_alphabetically("2015.12.21", "2015.12.21") == [a3] def test_activities_in_interval_by_date(self): L = self.L a1 = self.a1 a2 = self.a2 a3 = self.a3 a4 = self.a4 assert L.activities_in_interval_by_date("2015.12.20", "2016.01.01") == [a4, a1, a3] assert L.activities_in_interval_by_date("2000.01.01", "2010.01.01") == [] assert L.activities_in_interval_by_date("2016.01.01", "2017.01.01") == [a2] assert L.activities_in_interval_by_date("2015.12.21", "2015.12.21") == [a3]
flexible
{ "blob_id": "130581ddb0394dcceabc316468385d4e21959b63", "index": 8682, "step-1": "<mask token>\n\n\nclass StatsControllerTestCase(unittest.TestCase):\n\n def setUp(self):\n pR = PersonRepository()\n aR = ActivityRepository()\n self.L = StatsController(pR, aR)\n self.p = Person(1, 'John', '1', 'A')\n self.q = Person(2, 'Mary', '1', 'B')\n self.a1 = Activity(self.p, '2015.12.20', '12:12', 'Swimming')\n self.a2 = Activity(self.p, '2016.01.20', '12:12', 'Mapping')\n self.a3 = Activity(self.q, '2015.12.21', '12:12', 'Swimming')\n self.a4 = Activity(self.q, '2015.12.20', '10:12', 'Reading')\n pR.add(self.p)\n pR.add(self.q)\n aR.add(self.a1)\n aR.add(self.a2)\n aR.add(self.a3)\n aR.add(self.a4)\n <mask token>\n <mask token>\n\n def test_people_with_activities_in_interval(self):\n L = self.L\n p = self.p\n q = self.q\n assert L.people_with_activities_in_interval('2015.12.20', '2016.01.01'\n ) == [p, q]\n assert L.people_with_activities_in_interval('2000.01.01', '2010.01.01'\n ) == []\n assert L.people_with_activities_in_interval('2016.01.01', '2017.01.01'\n ) == [p]\n assert L.people_with_activities_in_interval('2015.12.21', '2015.12.21'\n ) == [q]\n <mask token>\n\n def test_activities_in_interval_by_date(self):\n L = self.L\n a1 = self.a1\n a2 = self.a2\n a3 = self.a3\n a4 = self.a4\n assert L.activities_in_interval_by_date('2015.12.20', '2016.01.01'\n ) == [a4, a1, a3]\n assert L.activities_in_interval_by_date('2000.01.01', '2010.01.01'\n ) == []\n assert L.activities_in_interval_by_date('2016.01.01', '2017.01.01'\n ) == [a2]\n assert L.activities_in_interval_by_date('2015.12.21', '2015.12.21'\n ) == [a3]\n", "step-2": "<mask token>\n\n\nclass StatsControllerTestCase(unittest.TestCase):\n\n def setUp(self):\n pR = PersonRepository()\n aR = ActivityRepository()\n self.L = StatsController(pR, aR)\n self.p = Person(1, 'John', '1', 'A')\n self.q = Person(2, 'Mary', '1', 'B')\n self.a1 = Activity(self.p, '2015.12.20', '12:12', 'Swimming')\n self.a2 = Activity(self.p, '2016.01.20', '12:12', 'Mapping')\n self.a3 = Activity(self.q, '2015.12.21', '12:12', 'Swimming')\n self.a4 = Activity(self.q, '2015.12.20', '10:12', 'Reading')\n pR.add(self.p)\n pR.add(self.q)\n aR.add(self.a1)\n aR.add(self.a2)\n aR.add(self.a3)\n aR.add(self.a4)\n <mask token>\n\n def test_activities_for_person_by_date(self):\n L = self.L\n a1 = self.a1\n a2 = self.a2\n a3 = self.a3\n a4 = self.a4\n assert L.activities_for_person_by_date(1) == [a1, a2]\n assert L.activities_for_person_by_date(2) == [a4, a3]\n assert L.activities_for_person_by_date(4) == []\n\n def test_people_with_activities_in_interval(self):\n L = self.L\n p = self.p\n q = self.q\n assert L.people_with_activities_in_interval('2015.12.20', '2016.01.01'\n ) == [p, q]\n assert L.people_with_activities_in_interval('2000.01.01', '2010.01.01'\n ) == []\n assert L.people_with_activities_in_interval('2016.01.01', '2017.01.01'\n ) == [p]\n assert L.people_with_activities_in_interval('2015.12.21', '2015.12.21'\n ) == [q]\n <mask token>\n\n def test_activities_in_interval_by_date(self):\n L = self.L\n a1 = self.a1\n a2 = self.a2\n a3 = self.a3\n a4 = self.a4\n assert L.activities_in_interval_by_date('2015.12.20', '2016.01.01'\n ) == [a4, a1, a3]\n assert L.activities_in_interval_by_date('2000.01.01', '2010.01.01'\n ) == []\n assert L.activities_in_interval_by_date('2016.01.01', '2017.01.01'\n ) == [a2]\n assert L.activities_in_interval_by_date('2015.12.21', '2015.12.21'\n ) == [a3]\n", "step-3": "<mask token>\n\n\nclass StatsControllerTestCase(unittest.TestCase):\n\n def setUp(self):\n pR = PersonRepository()\n aR = ActivityRepository()\n self.L = StatsController(pR, aR)\n self.p = Person(1, 'John', '1', 'A')\n self.q = Person(2, 'Mary', '1', 'B')\n self.a1 = Activity(self.p, '2015.12.20', '12:12', 'Swimming')\n self.a2 = Activity(self.p, '2016.01.20', '12:12', 'Mapping')\n self.a3 = Activity(self.q, '2015.12.21', '12:12', 'Swimming')\n self.a4 = Activity(self.q, '2015.12.20', '10:12', 'Reading')\n pR.add(self.p)\n pR.add(self.q)\n aR.add(self.a1)\n aR.add(self.a2)\n aR.add(self.a3)\n aR.add(self.a4)\n\n def test_activities_for_person_alphabetically(self):\n L = self.L\n a1 = self.a1\n a2 = self.a2\n a3 = self.a3\n a4 = self.a4\n assert L.activities_for_person_alphabetically(1) == [a2, a1]\n assert L.activities_for_person_alphabetically(2) == [a4, a3]\n assert L.activities_for_person_alphabetically(4) == []\n\n def test_activities_for_person_by_date(self):\n L = self.L\n a1 = self.a1\n a2 = self.a2\n a3 = self.a3\n a4 = self.a4\n assert L.activities_for_person_by_date(1) == [a1, a2]\n assert L.activities_for_person_by_date(2) == [a4, a3]\n assert L.activities_for_person_by_date(4) == []\n\n def test_people_with_activities_in_interval(self):\n L = self.L\n p = self.p\n q = self.q\n assert L.people_with_activities_in_interval('2015.12.20', '2016.01.01'\n ) == [p, q]\n assert L.people_with_activities_in_interval('2000.01.01', '2010.01.01'\n ) == []\n assert L.people_with_activities_in_interval('2016.01.01', '2017.01.01'\n ) == [p]\n assert L.people_with_activities_in_interval('2015.12.21', '2015.12.21'\n ) == [q]\n <mask token>\n\n def test_activities_in_interval_by_date(self):\n L = self.L\n a1 = self.a1\n a2 = self.a2\n a3 = self.a3\n a4 = self.a4\n assert L.activities_in_interval_by_date('2015.12.20', '2016.01.01'\n ) == [a4, a1, a3]\n assert L.activities_in_interval_by_date('2000.01.01', '2010.01.01'\n ) == []\n assert L.activities_in_interval_by_date('2016.01.01', '2017.01.01'\n ) == [a2]\n assert L.activities_in_interval_by_date('2015.12.21', '2015.12.21'\n ) == [a3]\n", "step-4": "<mask token>\n\n\nclass StatsControllerTestCase(unittest.TestCase):\n\n def setUp(self):\n pR = PersonRepository()\n aR = ActivityRepository()\n self.L = StatsController(pR, aR)\n self.p = Person(1, 'John', '1', 'A')\n self.q = Person(2, 'Mary', '1', 'B')\n self.a1 = Activity(self.p, '2015.12.20', '12:12', 'Swimming')\n self.a2 = Activity(self.p, '2016.01.20', '12:12', 'Mapping')\n self.a3 = Activity(self.q, '2015.12.21', '12:12', 'Swimming')\n self.a4 = Activity(self.q, '2015.12.20', '10:12', 'Reading')\n pR.add(self.p)\n pR.add(self.q)\n aR.add(self.a1)\n aR.add(self.a2)\n aR.add(self.a3)\n aR.add(self.a4)\n\n def test_activities_for_person_alphabetically(self):\n L = self.L\n a1 = self.a1\n a2 = self.a2\n a3 = self.a3\n a4 = self.a4\n assert L.activities_for_person_alphabetically(1) == [a2, a1]\n assert L.activities_for_person_alphabetically(2) == [a4, a3]\n assert L.activities_for_person_alphabetically(4) == []\n\n def test_activities_for_person_by_date(self):\n L = self.L\n a1 = self.a1\n a2 = self.a2\n a3 = self.a3\n a4 = self.a4\n assert L.activities_for_person_by_date(1) == [a1, a2]\n assert L.activities_for_person_by_date(2) == [a4, a3]\n assert L.activities_for_person_by_date(4) == []\n\n def test_people_with_activities_in_interval(self):\n L = self.L\n p = self.p\n q = self.q\n assert L.people_with_activities_in_interval('2015.12.20', '2016.01.01'\n ) == [p, q]\n assert L.people_with_activities_in_interval('2000.01.01', '2010.01.01'\n ) == []\n assert L.people_with_activities_in_interval('2016.01.01', '2017.01.01'\n ) == [p]\n assert L.people_with_activities_in_interval('2015.12.21', '2015.12.21'\n ) == [q]\n\n def test_activities_in_interval_alphabetically(self):\n L = self.L\n a1 = self.a1\n a2 = self.a2\n a3 = self.a3\n a4 = self.a4\n assert L.activities_in_interval_alphabetically('2015.12.20',\n '2016.01.01') == [a4, a1, a3]\n assert L.activities_in_interval_alphabetically('2000.01.01',\n '2010.01.01') == []\n assert L.activities_in_interval_alphabetically('2016.01.01',\n '2017.01.01') == [a2]\n assert L.activities_in_interval_alphabetically('2015.12.21',\n '2015.12.21') == [a3]\n\n def test_activities_in_interval_by_date(self):\n L = self.L\n a1 = self.a1\n a2 = self.a2\n a3 = self.a3\n a4 = self.a4\n assert L.activities_in_interval_by_date('2015.12.20', '2016.01.01'\n ) == [a4, a1, a3]\n assert L.activities_in_interval_by_date('2000.01.01', '2010.01.01'\n ) == []\n assert L.activities_in_interval_by_date('2016.01.01', '2017.01.01'\n ) == [a2]\n assert L.activities_in_interval_by_date('2015.12.21', '2015.12.21'\n ) == [a3]\n", "step-5": "import unittest\nfrom domain.Activity import Activity\nfrom domain.NABException import NABException\nfrom domain.Person import Person\nfrom domain.ActivityValidator import ActivityValidator\nfrom repository.PersonRepository import PersonRepository\nfrom repository.PersonFileRepository import PersonFileRepository\nfrom repository.ActivityRepository import ActivityRepository\nfrom repository.ActivityFileRepository import ActivityFileRepository\nfrom controller.StatsController import StatsController\n\n\nclass StatsControllerTestCase(unittest.TestCase):\n\n def setUp(self):\n pR = PersonRepository()\n aR = ActivityRepository()\n self.L = StatsController(pR, aR)\n self.p = Person(1, \"John\", \"1\", \"A\")\n self.q = Person(2, \"Mary\", \"1\", \"B\")\n self.a1 = Activity(self.p, \"2015.12.20\", \"12:12\", \"Swimming\")\n self.a2 = Activity(self.p, \"2016.01.20\", \"12:12\", \"Mapping\")\n self.a3 = Activity(self.q, \"2015.12.21\", \"12:12\", \"Swimming\")\n self.a4 = Activity(self.q, \"2015.12.20\", \"10:12\", \"Reading\")\n\n pR.add(self.p)\n pR.add(self.q)\n aR.add(self.a1)\n aR.add(self.a2)\n aR.add(self.a3)\n aR.add(self.a4)\n\n\n def test_activities_for_person_alphabetically(self):\n L = self.L\n a1 = self.a1\n a2 = self.a2\n a3 = self.a3\n a4 = self.a4\n\n assert L.activities_for_person_alphabetically(1) == [a2, a1]\n assert L.activities_for_person_alphabetically(2) == [a4, a3]\n assert L.activities_for_person_alphabetically(4) == []\n\n\n def test_activities_for_person_by_date(self):\n L = self.L\n a1 = self.a1\n a2 = self.a2\n a3 = self.a3\n a4 = self.a4\n\n assert L.activities_for_person_by_date(1) == [a1, a2]\n assert L.activities_for_person_by_date(2) == [a4, a3]\n assert L.activities_for_person_by_date(4) == []\n\n\n def test_people_with_activities_in_interval(self):\n L = self.L\n p = self.p\n q = self.q\n\n assert L.people_with_activities_in_interval(\"2015.12.20\", \"2016.01.01\") == [p, q]\n assert L.people_with_activities_in_interval(\"2000.01.01\", \"2010.01.01\") == []\n assert L.people_with_activities_in_interval(\"2016.01.01\", \"2017.01.01\") == [p]\n assert L.people_with_activities_in_interval(\"2015.12.21\", \"2015.12.21\") == [q]\n\n\n def test_activities_in_interval_alphabetically(self):\n L = self.L\n a1 = self.a1\n a2 = self.a2\n a3 = self.a3\n a4 = self.a4\n\n assert L.activities_in_interval_alphabetically(\"2015.12.20\", \"2016.01.01\") == [a4, a1, a3]\n assert L.activities_in_interval_alphabetically(\"2000.01.01\", \"2010.01.01\") == []\n assert L.activities_in_interval_alphabetically(\"2016.01.01\", \"2017.01.01\") == [a2]\n assert L.activities_in_interval_alphabetically(\"2015.12.21\", \"2015.12.21\") == [a3]\n\n\n def test_activities_in_interval_by_date(self):\n L = self.L\n a1 = self.a1\n a2 = self.a2\n a3 = self.a3\n a4 = self.a4\n\n assert L.activities_in_interval_by_date(\"2015.12.20\", \"2016.01.01\") == [a4, a1, a3]\n assert L.activities_in_interval_by_date(\"2000.01.01\", \"2010.01.01\") == []\n assert L.activities_in_interval_by_date(\"2016.01.01\", \"2017.01.01\") == [a2]\n assert L.activities_in_interval_by_date(\"2015.12.21\", \"2015.12.21\") == [a3]", "step-ids": [ 4, 5, 6, 7, 9 ] }
[ 4, 5, 6, 7, 9 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> print(stems1) print(stems2) print(stems3) <|reserved_special_token_1|> <|reserved_special_token_0|> stemmer = SnowballStemmer('english', ignore_stopwords=True) lemmatizer = WordNetLemmatizer() source = ['having', 'have', 'needs', 'need', 'inflation', 'inflate', 'developments', 'developing', 'aggregation', 'aggregated', 'population', 'poverty', 'poor', 'poorer', 'men', 'man', 'gases', 'gas', 'sues', 'utilized', 'damaged'] stems1 = [stemmer.stem(word) for word in source] stems2 = [lemmatizer.lemmatize(word) for word in source] stems3 = [stemmer.stem(word) for word in stems2] print(stems1) print(stems2) print(stems3) <|reserved_special_token_1|> from nltk.stem.snowball import SnowballStemmer from nltk.stem.wordnet import WordNetLemmatizer stemmer = SnowballStemmer('english', ignore_stopwords=True) lemmatizer = WordNetLemmatizer() source = ['having', 'have', 'needs', 'need', 'inflation', 'inflate', 'developments', 'developing', 'aggregation', 'aggregated', 'population', 'poverty', 'poor', 'poorer', 'men', 'man', 'gases', 'gas', 'sues', 'utilized', 'damaged'] stems1 = [stemmer.stem(word) for word in source] stems2 = [lemmatizer.lemmatize(word) for word in source] stems3 = [stemmer.stem(word) for word in stems2] print(stems1) print(stems2) print(stems3) <|reserved_special_token_1|> #Voir paragraphe "3.6 Normalizing Text", page 107 de NLP with Python from nltk.stem.snowball import SnowballStemmer from nltk.stem.wordnet import WordNetLemmatizer # Il faut retirer les stopwords avant de stemmer stemmer = SnowballStemmer("english", ignore_stopwords=True) lemmatizer = WordNetLemmatizer() source = ["having", "have", "needs", "need", "inflation", "inflate", "developments", "developing", "aggregation", "aggregated", "population", "poverty", "poor", "poorer", "men", "man", "gases", "gas", "sues", "utilized", "damaged"] stems1 = [stemmer.stem(word) for word in source] stems2 = [lemmatizer.lemmatize(word) for word in source] stems3 = [stemmer.stem(word) for word in stems2] print(stems1) print(stems2) print(stems3)
flexible
{ "blob_id": "1f1677687ba6ca47b18728b0fd3b9926436e9796", "index": 2949, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(stems1)\nprint(stems2)\nprint(stems3)\n", "step-3": "<mask token>\nstemmer = SnowballStemmer('english', ignore_stopwords=True)\nlemmatizer = WordNetLemmatizer()\nsource = ['having', 'have', 'needs', 'need', 'inflation', 'inflate',\n 'developments', 'developing', 'aggregation', 'aggregated', 'population',\n 'poverty', 'poor', 'poorer', 'men', 'man', 'gases', 'gas', 'sues',\n 'utilized', 'damaged']\nstems1 = [stemmer.stem(word) for word in source]\nstems2 = [lemmatizer.lemmatize(word) for word in source]\nstems3 = [stemmer.stem(word) for word in stems2]\nprint(stems1)\nprint(stems2)\nprint(stems3)\n", "step-4": "from nltk.stem.snowball import SnowballStemmer\nfrom nltk.stem.wordnet import WordNetLemmatizer\nstemmer = SnowballStemmer('english', ignore_stopwords=True)\nlemmatizer = WordNetLemmatizer()\nsource = ['having', 'have', 'needs', 'need', 'inflation', 'inflate',\n 'developments', 'developing', 'aggregation', 'aggregated', 'population',\n 'poverty', 'poor', 'poorer', 'men', 'man', 'gases', 'gas', 'sues',\n 'utilized', 'damaged']\nstems1 = [stemmer.stem(word) for word in source]\nstems2 = [lemmatizer.lemmatize(word) for word in source]\nstems3 = [stemmer.stem(word) for word in stems2]\nprint(stems1)\nprint(stems2)\nprint(stems3)\n", "step-5": "#Voir paragraphe \"3.6 Normalizing Text\", page 107 de NLP with Python\n\n\nfrom nltk.stem.snowball import SnowballStemmer\nfrom nltk.stem.wordnet import WordNetLemmatizer\n\n# Il faut retirer les stopwords avant de stemmer\n\nstemmer = SnowballStemmer(\"english\", ignore_stopwords=True)\nlemmatizer = WordNetLemmatizer()\n\nsource = [\"having\", \"have\", \"needs\", \"need\", \"inflation\", \"inflate\", \"developments\", \"developing\", \"aggregation\",\n \"aggregated\", \"population\", \"poverty\", \"poor\", \"poorer\", \"men\", \"man\", \"gases\", \"gas\", \"sues\", \"utilized\",\n \"damaged\"]\n\nstems1 = [stemmer.stem(word) for word in source]\nstems2 = [lemmatizer.lemmatize(word) for word in source]\nstems3 = [stemmer.stem(word) for word in stems2]\n\nprint(stems1)\nprint(stems2)\nprint(stems3)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> def GetAtomFeatInfo(factory, mol): res = [None] * mol.GetNumAtoms() feats = factory.GetFeaturesForMol(mol) for feat in feats: ids = feat.GetAtomIds() feature = '%s-%s' % (feat.GetFamily(), feat.GetType()) for id_ in ids: if res[id_] is None: res[id_] = [] res[id_].append(feature) return res def initParser(): """ Initialize the parser """ parser = argparse.ArgumentParser(description= 'Determine pharmacophore features of molecules', epilog= _splashMessage, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-r', dest='reverseIt', default=False, action= 'store_true', help='Set to get atoms lists for each feature.') parser.add_argument('-n', dest='maxLines', default=-1, help=argparse. SUPPRESS, type=int) parser.add_argument('fdefFilename', type=existingFile, help= 'Pharmacophore feature definition file') parser.add_argument('smilesFilename', type=existingFile, help= 'The smiles file should have SMILES in the first column') return parser <|reserved_special_token_0|> def existingFile(filename): """ 'type' for argparse - check that filename exists """ if not os.path.exists(filename): raise argparse.ArgumentTypeError('{0} does not exist'.format(filename)) return filename def processArgs(args, parser): try: factory = ChemicalFeatures.BuildFeatureFactory(args.fdefFilename) except Exception: parser.error('Could not parse Fdef file {0.fdefFilename}.'.format(args) ) with open(args.smilesFilename) as inF: for lineNo, line in enumerate(inF, 1): if lineNo == args.maxLines + 1: break smi = splitExpr.split(line.strip())[0].strip() mol = Chem.MolFromSmiles(smi) if mol is None: logger.warning("Could not process smiles '%s' on line %d." % (smi, lineNo)) continue print('Mol-%d\t%s' % (lineNo, smi)) if args.reverseIt: feats = factory.GetFeaturesForMol(mol) for feat in feats: print('\t%s-%s: ' % (feat.GetFamily(), feat.GetType()), end='') print(', '.join([str(x) for x in feat.GetAtomIds()])) else: featInfo = GetAtomFeatInfo(factory, mol) for i, v in enumerate(featInfo): print('\t% 2s(%d)' % (mol.GetAtomWithIdx(i).GetSymbol(), i + 1), end='') if v: print('\t', ', '.join(v)) else: print() def main(): """ Main application """ parser = initParser() args = parser.parse_args() processArgs(args, parser) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def GetAtomFeatInfo(factory, mol): res = [None] * mol.GetNumAtoms() feats = factory.GetFeaturesForMol(mol) for feat in feats: ids = feat.GetAtomIds() feature = '%s-%s' % (feat.GetFamily(), feat.GetType()) for id_ in ids: if res[id_] is None: res[id_] = [] res[id_].append(feature) return res def initParser(): """ Initialize the parser """ parser = argparse.ArgumentParser(description= 'Determine pharmacophore features of molecules', epilog= _splashMessage, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-r', dest='reverseIt', default=False, action= 'store_true', help='Set to get atoms lists for each feature.') parser.add_argument('-n', dest='maxLines', default=-1, help=argparse. SUPPRESS, type=int) parser.add_argument('fdefFilename', type=existingFile, help= 'Pharmacophore feature definition file') parser.add_argument('smilesFilename', type=existingFile, help= 'The smiles file should have SMILES in the first column') return parser <|reserved_special_token_0|> def existingFile(filename): """ 'type' for argparse - check that filename exists """ if not os.path.exists(filename): raise argparse.ArgumentTypeError('{0} does not exist'.format(filename)) return filename def processArgs(args, parser): try: factory = ChemicalFeatures.BuildFeatureFactory(args.fdefFilename) except Exception: parser.error('Could not parse Fdef file {0.fdefFilename}.'.format(args) ) with open(args.smilesFilename) as inF: for lineNo, line in enumerate(inF, 1): if lineNo == args.maxLines + 1: break smi = splitExpr.split(line.strip())[0].strip() mol = Chem.MolFromSmiles(smi) if mol is None: logger.warning("Could not process smiles '%s' on line %d." % (smi, lineNo)) continue print('Mol-%d\t%s' % (lineNo, smi)) if args.reverseIt: feats = factory.GetFeaturesForMol(mol) for feat in feats: print('\t%s-%s: ' % (feat.GetFamily(), feat.GetType()), end='') print(', '.join([str(x) for x in feat.GetAtomIds()])) else: featInfo = GetAtomFeatInfo(factory, mol) for i, v in enumerate(featInfo): print('\t% 2s(%d)' % (mol.GetAtomWithIdx(i).GetSymbol(), i + 1), end='') if v: print('\t', ', '.join(v)) else: print() def main(): """ Main application """ parser = initParser() args = parser.parse_args() processArgs(args, parser) if __name__ == '__main__': main() <|reserved_special_token_1|> <|reserved_special_token_0|> logger = RDLogger.logger() splitExpr = re.compile('[ \\t,]') def GetAtomFeatInfo(factory, mol): res = [None] * mol.GetNumAtoms() feats = factory.GetFeaturesForMol(mol) for feat in feats: ids = feat.GetAtomIds() feature = '%s-%s' % (feat.GetFamily(), feat.GetType()) for id_ in ids: if res[id_] is None: res[id_] = [] res[id_].append(feature) return res def initParser(): """ Initialize the parser """ parser = argparse.ArgumentParser(description= 'Determine pharmacophore features of molecules', epilog= _splashMessage, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-r', dest='reverseIt', default=False, action= 'store_true', help='Set to get atoms lists for each feature.') parser.add_argument('-n', dest='maxLines', default=-1, help=argparse. SUPPRESS, type=int) parser.add_argument('fdefFilename', type=existingFile, help= 'Pharmacophore feature definition file') parser.add_argument('smilesFilename', type=existingFile, help= 'The smiles file should have SMILES in the first column') return parser _splashMessage = """ -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* FeatFinderCLI Part of the RDKit (http://www.rdkit.org) -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* """ def existingFile(filename): """ 'type' for argparse - check that filename exists """ if not os.path.exists(filename): raise argparse.ArgumentTypeError('{0} does not exist'.format(filename)) return filename def processArgs(args, parser): try: factory = ChemicalFeatures.BuildFeatureFactory(args.fdefFilename) except Exception: parser.error('Could not parse Fdef file {0.fdefFilename}.'.format(args) ) with open(args.smilesFilename) as inF: for lineNo, line in enumerate(inF, 1): if lineNo == args.maxLines + 1: break smi = splitExpr.split(line.strip())[0].strip() mol = Chem.MolFromSmiles(smi) if mol is None: logger.warning("Could not process smiles '%s' on line %d." % (smi, lineNo)) continue print('Mol-%d\t%s' % (lineNo, smi)) if args.reverseIt: feats = factory.GetFeaturesForMol(mol) for feat in feats: print('\t%s-%s: ' % (feat.GetFamily(), feat.GetType()), end='') print(', '.join([str(x) for x in feat.GetAtomIds()])) else: featInfo = GetAtomFeatInfo(factory, mol) for i, v in enumerate(featInfo): print('\t% 2s(%d)' % (mol.GetAtomWithIdx(i).GetSymbol(), i + 1), end='') if v: print('\t', ', '.join(v)) else: print() def main(): """ Main application """ parser = initParser() args = parser.parse_args() processArgs(args, parser) if __name__ == '__main__': main() <|reserved_special_token_1|> import argparse import re import os from rdkit import Chem from rdkit import RDLogger from rdkit.Chem import ChemicalFeatures logger = RDLogger.logger() splitExpr = re.compile('[ \\t,]') def GetAtomFeatInfo(factory, mol): res = [None] * mol.GetNumAtoms() feats = factory.GetFeaturesForMol(mol) for feat in feats: ids = feat.GetAtomIds() feature = '%s-%s' % (feat.GetFamily(), feat.GetType()) for id_ in ids: if res[id_] is None: res[id_] = [] res[id_].append(feature) return res def initParser(): """ Initialize the parser """ parser = argparse.ArgumentParser(description= 'Determine pharmacophore features of molecules', epilog= _splashMessage, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-r', dest='reverseIt', default=False, action= 'store_true', help='Set to get atoms lists for each feature.') parser.add_argument('-n', dest='maxLines', default=-1, help=argparse. SUPPRESS, type=int) parser.add_argument('fdefFilename', type=existingFile, help= 'Pharmacophore feature definition file') parser.add_argument('smilesFilename', type=existingFile, help= 'The smiles file should have SMILES in the first column') return parser _splashMessage = """ -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* FeatFinderCLI Part of the RDKit (http://www.rdkit.org) -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* """ def existingFile(filename): """ 'type' for argparse - check that filename exists """ if not os.path.exists(filename): raise argparse.ArgumentTypeError('{0} does not exist'.format(filename)) return filename def processArgs(args, parser): try: factory = ChemicalFeatures.BuildFeatureFactory(args.fdefFilename) except Exception: parser.error('Could not parse Fdef file {0.fdefFilename}.'.format(args) ) with open(args.smilesFilename) as inF: for lineNo, line in enumerate(inF, 1): if lineNo == args.maxLines + 1: break smi = splitExpr.split(line.strip())[0].strip() mol = Chem.MolFromSmiles(smi) if mol is None: logger.warning("Could not process smiles '%s' on line %d." % (smi, lineNo)) continue print('Mol-%d\t%s' % (lineNo, smi)) if args.reverseIt: feats = factory.GetFeaturesForMol(mol) for feat in feats: print('\t%s-%s: ' % (feat.GetFamily(), feat.GetType()), end='') print(', '.join([str(x) for x in feat.GetAtomIds()])) else: featInfo = GetAtomFeatInfo(factory, mol) for i, v in enumerate(featInfo): print('\t% 2s(%d)' % (mol.GetAtomWithIdx(i).GetSymbol(), i + 1), end='') if v: print('\t', ', '.join(v)) else: print() def main(): """ Main application """ parser = initParser() args = parser.parse_args() processArgs(args, parser) if __name__ == '__main__': main() <|reserved_special_token_1|> # # Copyright (C) 2005-2006 Rational Discovery LLC # # @@ All Rights Reserved @@ # This file is part of the RDKit. # The contents are covered by the terms of the BSD license # which is included in the file license.txt, found at the root # of the RDKit source tree. # import argparse import re import os from rdkit import Chem from rdkit import RDLogger from rdkit.Chem import ChemicalFeatures logger = RDLogger.logger() splitExpr = re.compile(r'[ \t,]') def GetAtomFeatInfo(factory, mol): res = [None] * mol.GetNumAtoms() feats = factory.GetFeaturesForMol(mol) for feat in feats: ids = feat.GetAtomIds() feature = "%s-%s" % (feat.GetFamily(), feat.GetType()) for id_ in ids: if res[id_] is None: res[id_] = [] res[id_].append(feature) return res def initParser(): """ Initialize the parser """ parser = argparse.ArgumentParser(description='Determine pharmacophore features of molecules', epilog=_splashMessage, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-r', dest='reverseIt', default=False, action='store_true', help='Set to get atoms lists for each feature.') parser.add_argument('-n', dest='maxLines', default=-1, help=argparse.SUPPRESS, type=int) parser.add_argument('fdefFilename', type=existingFile, help='Pharmacophore feature definition file') parser.add_argument('smilesFilename', type=existingFile, help='The smiles file should have SMILES in the first column') return parser _splashMessage = """ -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* FeatFinderCLI Part of the RDKit (http://www.rdkit.org) -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* """ def existingFile(filename): """ 'type' for argparse - check that filename exists """ if not os.path.exists(filename): raise argparse.ArgumentTypeError("{0} does not exist".format(filename)) return filename def processArgs(args, parser): try: factory = ChemicalFeatures.BuildFeatureFactory(args.fdefFilename) except Exception: parser.error("Could not parse Fdef file {0.fdefFilename}.".format(args)) with open(args.smilesFilename) as inF: for lineNo, line in enumerate(inF, 1): if lineNo == args.maxLines + 1: break smi = splitExpr.split(line.strip())[0].strip() mol = Chem.MolFromSmiles(smi) if mol is None: logger.warning("Could not process smiles '%s' on line %d." % (smi, lineNo)) continue print('Mol-%d\t%s' % (lineNo, smi)) if args.reverseIt: feats = factory.GetFeaturesForMol(mol) for feat in feats: print('\t%s-%s: ' % (feat.GetFamily(), feat.GetType()), end='') print(', '.join([str(x) for x in feat.GetAtomIds()])) else: featInfo = GetAtomFeatInfo(factory, mol) for i, v in enumerate(featInfo): print('\t% 2s(%d)' % (mol.GetAtomWithIdx(i).GetSymbol(), i + 1), end='') if v: print('\t', ', '.join(v)) else: print() def main(): """ Main application """ parser = initParser() args = parser.parse_args() processArgs(args, parser) if __name__ == '__main__': main()
flexible
{ "blob_id": "4b63df35b36b35f1b886b8981519921a9e697a42", "index": 4840, "step-1": "<mask token>\n\n\ndef GetAtomFeatInfo(factory, mol):\n res = [None] * mol.GetNumAtoms()\n feats = factory.GetFeaturesForMol(mol)\n for feat in feats:\n ids = feat.GetAtomIds()\n feature = '%s-%s' % (feat.GetFamily(), feat.GetType())\n for id_ in ids:\n if res[id_] is None:\n res[id_] = []\n res[id_].append(feature)\n return res\n\n\ndef initParser():\n \"\"\" Initialize the parser \"\"\"\n parser = argparse.ArgumentParser(description=\n 'Determine pharmacophore features of molecules', epilog=\n _splashMessage, formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument('-r', dest='reverseIt', default=False, action=\n 'store_true', help='Set to get atoms lists for each feature.')\n parser.add_argument('-n', dest='maxLines', default=-1, help=argparse.\n SUPPRESS, type=int)\n parser.add_argument('fdefFilename', type=existingFile, help=\n 'Pharmacophore feature definition file')\n parser.add_argument('smilesFilename', type=existingFile, help=\n 'The smiles file should have SMILES in the first column')\n return parser\n\n\n<mask token>\n\n\ndef existingFile(filename):\n \"\"\" 'type' for argparse - check that filename exists \"\"\"\n if not os.path.exists(filename):\n raise argparse.ArgumentTypeError('{0} does not exist'.format(filename))\n return filename\n\n\ndef processArgs(args, parser):\n try:\n factory = ChemicalFeatures.BuildFeatureFactory(args.fdefFilename)\n except Exception:\n parser.error('Could not parse Fdef file {0.fdefFilename}.'.format(args)\n )\n with open(args.smilesFilename) as inF:\n for lineNo, line in enumerate(inF, 1):\n if lineNo == args.maxLines + 1:\n break\n smi = splitExpr.split(line.strip())[0].strip()\n mol = Chem.MolFromSmiles(smi)\n if mol is None:\n logger.warning(\"Could not process smiles '%s' on line %d.\" %\n (smi, lineNo))\n continue\n print('Mol-%d\\t%s' % (lineNo, smi))\n if args.reverseIt:\n feats = factory.GetFeaturesForMol(mol)\n for feat in feats:\n print('\\t%s-%s: ' % (feat.GetFamily(), feat.GetType()),\n end='')\n print(', '.join([str(x) for x in feat.GetAtomIds()]))\n else:\n featInfo = GetAtomFeatInfo(factory, mol)\n for i, v in enumerate(featInfo):\n print('\\t% 2s(%d)' % (mol.GetAtomWithIdx(i).GetSymbol(),\n i + 1), end='')\n if v:\n print('\\t', ', '.join(v))\n else:\n print()\n\n\ndef main():\n \"\"\" Main application \"\"\"\n parser = initParser()\n args = parser.parse_args()\n processArgs(args, parser)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef GetAtomFeatInfo(factory, mol):\n res = [None] * mol.GetNumAtoms()\n feats = factory.GetFeaturesForMol(mol)\n for feat in feats:\n ids = feat.GetAtomIds()\n feature = '%s-%s' % (feat.GetFamily(), feat.GetType())\n for id_ in ids:\n if res[id_] is None:\n res[id_] = []\n res[id_].append(feature)\n return res\n\n\ndef initParser():\n \"\"\" Initialize the parser \"\"\"\n parser = argparse.ArgumentParser(description=\n 'Determine pharmacophore features of molecules', epilog=\n _splashMessage, formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument('-r', dest='reverseIt', default=False, action=\n 'store_true', help='Set to get atoms lists for each feature.')\n parser.add_argument('-n', dest='maxLines', default=-1, help=argparse.\n SUPPRESS, type=int)\n parser.add_argument('fdefFilename', type=existingFile, help=\n 'Pharmacophore feature definition file')\n parser.add_argument('smilesFilename', type=existingFile, help=\n 'The smiles file should have SMILES in the first column')\n return parser\n\n\n<mask token>\n\n\ndef existingFile(filename):\n \"\"\" 'type' for argparse - check that filename exists \"\"\"\n if not os.path.exists(filename):\n raise argparse.ArgumentTypeError('{0} does not exist'.format(filename))\n return filename\n\n\ndef processArgs(args, parser):\n try:\n factory = ChemicalFeatures.BuildFeatureFactory(args.fdefFilename)\n except Exception:\n parser.error('Could not parse Fdef file {0.fdefFilename}.'.format(args)\n )\n with open(args.smilesFilename) as inF:\n for lineNo, line in enumerate(inF, 1):\n if lineNo == args.maxLines + 1:\n break\n smi = splitExpr.split(line.strip())[0].strip()\n mol = Chem.MolFromSmiles(smi)\n if mol is None:\n logger.warning(\"Could not process smiles '%s' on line %d.\" %\n (smi, lineNo))\n continue\n print('Mol-%d\\t%s' % (lineNo, smi))\n if args.reverseIt:\n feats = factory.GetFeaturesForMol(mol)\n for feat in feats:\n print('\\t%s-%s: ' % (feat.GetFamily(), feat.GetType()),\n end='')\n print(', '.join([str(x) for x in feat.GetAtomIds()]))\n else:\n featInfo = GetAtomFeatInfo(factory, mol)\n for i, v in enumerate(featInfo):\n print('\\t% 2s(%d)' % (mol.GetAtomWithIdx(i).GetSymbol(),\n i + 1), end='')\n if v:\n print('\\t', ', '.join(v))\n else:\n print()\n\n\ndef main():\n \"\"\" Main application \"\"\"\n parser = initParser()\n args = parser.parse_args()\n processArgs(args, parser)\n\n\nif __name__ == '__main__':\n main()\n", "step-3": "<mask token>\nlogger = RDLogger.logger()\nsplitExpr = re.compile('[ \\\\t,]')\n\n\ndef GetAtomFeatInfo(factory, mol):\n res = [None] * mol.GetNumAtoms()\n feats = factory.GetFeaturesForMol(mol)\n for feat in feats:\n ids = feat.GetAtomIds()\n feature = '%s-%s' % (feat.GetFamily(), feat.GetType())\n for id_ in ids:\n if res[id_] is None:\n res[id_] = []\n res[id_].append(feature)\n return res\n\n\ndef initParser():\n \"\"\" Initialize the parser \"\"\"\n parser = argparse.ArgumentParser(description=\n 'Determine pharmacophore features of molecules', epilog=\n _splashMessage, formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument('-r', dest='reverseIt', default=False, action=\n 'store_true', help='Set to get atoms lists for each feature.')\n parser.add_argument('-n', dest='maxLines', default=-1, help=argparse.\n SUPPRESS, type=int)\n parser.add_argument('fdefFilename', type=existingFile, help=\n 'Pharmacophore feature definition file')\n parser.add_argument('smilesFilename', type=existingFile, help=\n 'The smiles file should have SMILES in the first column')\n return parser\n\n\n_splashMessage = \"\"\"\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n FeatFinderCLI\n Part of the RDKit (http://www.rdkit.org)\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\"\"\"\n\n\ndef existingFile(filename):\n \"\"\" 'type' for argparse - check that filename exists \"\"\"\n if not os.path.exists(filename):\n raise argparse.ArgumentTypeError('{0} does not exist'.format(filename))\n return filename\n\n\ndef processArgs(args, parser):\n try:\n factory = ChemicalFeatures.BuildFeatureFactory(args.fdefFilename)\n except Exception:\n parser.error('Could not parse Fdef file {0.fdefFilename}.'.format(args)\n )\n with open(args.smilesFilename) as inF:\n for lineNo, line in enumerate(inF, 1):\n if lineNo == args.maxLines + 1:\n break\n smi = splitExpr.split(line.strip())[0].strip()\n mol = Chem.MolFromSmiles(smi)\n if mol is None:\n logger.warning(\"Could not process smiles '%s' on line %d.\" %\n (smi, lineNo))\n continue\n print('Mol-%d\\t%s' % (lineNo, smi))\n if args.reverseIt:\n feats = factory.GetFeaturesForMol(mol)\n for feat in feats:\n print('\\t%s-%s: ' % (feat.GetFamily(), feat.GetType()),\n end='')\n print(', '.join([str(x) for x in feat.GetAtomIds()]))\n else:\n featInfo = GetAtomFeatInfo(factory, mol)\n for i, v in enumerate(featInfo):\n print('\\t% 2s(%d)' % (mol.GetAtomWithIdx(i).GetSymbol(),\n i + 1), end='')\n if v:\n print('\\t', ', '.join(v))\n else:\n print()\n\n\ndef main():\n \"\"\" Main application \"\"\"\n parser = initParser()\n args = parser.parse_args()\n processArgs(args, parser)\n\n\nif __name__ == '__main__':\n main()\n", "step-4": "import argparse\nimport re\nimport os\nfrom rdkit import Chem\nfrom rdkit import RDLogger\nfrom rdkit.Chem import ChemicalFeatures\nlogger = RDLogger.logger()\nsplitExpr = re.compile('[ \\\\t,]')\n\n\ndef GetAtomFeatInfo(factory, mol):\n res = [None] * mol.GetNumAtoms()\n feats = factory.GetFeaturesForMol(mol)\n for feat in feats:\n ids = feat.GetAtomIds()\n feature = '%s-%s' % (feat.GetFamily(), feat.GetType())\n for id_ in ids:\n if res[id_] is None:\n res[id_] = []\n res[id_].append(feature)\n return res\n\n\ndef initParser():\n \"\"\" Initialize the parser \"\"\"\n parser = argparse.ArgumentParser(description=\n 'Determine pharmacophore features of molecules', epilog=\n _splashMessage, formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument('-r', dest='reverseIt', default=False, action=\n 'store_true', help='Set to get atoms lists for each feature.')\n parser.add_argument('-n', dest='maxLines', default=-1, help=argparse.\n SUPPRESS, type=int)\n parser.add_argument('fdefFilename', type=existingFile, help=\n 'Pharmacophore feature definition file')\n parser.add_argument('smilesFilename', type=existingFile, help=\n 'The smiles file should have SMILES in the first column')\n return parser\n\n\n_splashMessage = \"\"\"\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n FeatFinderCLI\n Part of the RDKit (http://www.rdkit.org)\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\"\"\"\n\n\ndef existingFile(filename):\n \"\"\" 'type' for argparse - check that filename exists \"\"\"\n if not os.path.exists(filename):\n raise argparse.ArgumentTypeError('{0} does not exist'.format(filename))\n return filename\n\n\ndef processArgs(args, parser):\n try:\n factory = ChemicalFeatures.BuildFeatureFactory(args.fdefFilename)\n except Exception:\n parser.error('Could not parse Fdef file {0.fdefFilename}.'.format(args)\n )\n with open(args.smilesFilename) as inF:\n for lineNo, line in enumerate(inF, 1):\n if lineNo == args.maxLines + 1:\n break\n smi = splitExpr.split(line.strip())[0].strip()\n mol = Chem.MolFromSmiles(smi)\n if mol is None:\n logger.warning(\"Could not process smiles '%s' on line %d.\" %\n (smi, lineNo))\n continue\n print('Mol-%d\\t%s' % (lineNo, smi))\n if args.reverseIt:\n feats = factory.GetFeaturesForMol(mol)\n for feat in feats:\n print('\\t%s-%s: ' % (feat.GetFamily(), feat.GetType()),\n end='')\n print(', '.join([str(x) for x in feat.GetAtomIds()]))\n else:\n featInfo = GetAtomFeatInfo(factory, mol)\n for i, v in enumerate(featInfo):\n print('\\t% 2s(%d)' % (mol.GetAtomWithIdx(i).GetSymbol(),\n i + 1), end='')\n if v:\n print('\\t', ', '.join(v))\n else:\n print()\n\n\ndef main():\n \"\"\" Main application \"\"\"\n parser = initParser()\n args = parser.parse_args()\n processArgs(args, parser)\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "#\n# Copyright (C) 2005-2006 Rational Discovery LLC\n#\n# @@ All Rights Reserved @@\n# This file is part of the RDKit.\n# The contents are covered by the terms of the BSD license\n# which is included in the file license.txt, found at the root\n# of the RDKit source tree.\n#\n\n\nimport argparse\nimport re\nimport os\n\nfrom rdkit import Chem\nfrom rdkit import RDLogger\nfrom rdkit.Chem import ChemicalFeatures\n\nlogger = RDLogger.logger()\nsplitExpr = re.compile(r'[ \\t,]')\n\n\ndef GetAtomFeatInfo(factory, mol):\n res = [None] * mol.GetNumAtoms()\n feats = factory.GetFeaturesForMol(mol)\n for feat in feats:\n ids = feat.GetAtomIds()\n feature = \"%s-%s\" % (feat.GetFamily(), feat.GetType())\n for id_ in ids:\n if res[id_] is None:\n res[id_] = []\n res[id_].append(feature)\n return res\n\n\ndef initParser():\n \"\"\" Initialize the parser \"\"\"\n parser = argparse.ArgumentParser(description='Determine pharmacophore features of molecules',\n epilog=_splashMessage,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument('-r', dest='reverseIt', default=False, action='store_true',\n help='Set to get atoms lists for each feature.')\n parser.add_argument('-n', dest='maxLines', default=-1, help=argparse.SUPPRESS, type=int)\n parser.add_argument('fdefFilename', type=existingFile,\n help='Pharmacophore feature definition file')\n parser.add_argument('smilesFilename', type=existingFile,\n help='The smiles file should have SMILES in the first column')\n return parser\n\n\n_splashMessage = \"\"\"\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n FeatFinderCLI\n Part of the RDKit (http://www.rdkit.org)\n-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n\"\"\"\n\n\ndef existingFile(filename):\n \"\"\" 'type' for argparse - check that filename exists \"\"\"\n if not os.path.exists(filename):\n raise argparse.ArgumentTypeError(\"{0} does not exist\".format(filename))\n return filename\n\n\ndef processArgs(args, parser):\n try:\n factory = ChemicalFeatures.BuildFeatureFactory(args.fdefFilename)\n except Exception:\n parser.error(\"Could not parse Fdef file {0.fdefFilename}.\".format(args))\n\n with open(args.smilesFilename) as inF:\n for lineNo, line in enumerate(inF, 1):\n if lineNo == args.maxLines + 1:\n break\n smi = splitExpr.split(line.strip())[0].strip()\n mol = Chem.MolFromSmiles(smi)\n if mol is None:\n logger.warning(\"Could not process smiles '%s' on line %d.\" % (smi, lineNo))\n continue\n\n print('Mol-%d\\t%s' % (lineNo, smi))\n if args.reverseIt:\n feats = factory.GetFeaturesForMol(mol)\n for feat in feats:\n print('\\t%s-%s: ' % (feat.GetFamily(), feat.GetType()), end='')\n print(', '.join([str(x) for x in feat.GetAtomIds()]))\n else:\n featInfo = GetAtomFeatInfo(factory, mol)\n for i, v in enumerate(featInfo):\n print('\\t% 2s(%d)' % (mol.GetAtomWithIdx(i).GetSymbol(), i + 1), end='')\n if v:\n print('\\t', ', '.join(v))\n else:\n print()\n\n\ndef main():\n \"\"\" Main application \"\"\"\n parser = initParser()\n args = parser.parse_args()\n processArgs(args, parser)\n\n\nif __name__ == '__main__':\n main()\n", "step-ids": [ 5, 6, 7, 8, 9 ] }
[ 5, 6, 7, 8, 9 ]
import torch from torchvision import datasets, transforms from torch.utils.data import Dataset, DataLoader # load the data Set from torch.utils.data import random_split from torchvision.datasets import ImageFolder batch_size = 256 data_dir = 'nut_snacks/dataset/' data_transforms = transforms.Compose( [transforms.RandomResizedCrop(128), transforms.ToTensor(), ]) dataset = ImageFolder(data_dir, transform=data_transforms) print('Total dataset images: ',len(dataset)) loader = torch.utils.data.DataLoader( dataset, batch_size=batch_size) def mean_std(loader): mean = 0 std = 0 for images, _ in loader : batch_samples = images.size(0) images = images.view(batch_samples, images.size(1), -1) mean += images.mean(2).sum(0) std += images.std(2).sum(0) mean /= len(loader.dataset) std /= len(loader.dataset) return mean,std mean, std = mean_std(loader) print(f'Mean: {mean}') print(f'Std: {std}')
normal
{ "blob_id": "4156b003210a41d6ec8f30e2d20adfb1f4b3deb0", "index": 6024, "step-1": "<mask token>\n\n\ndef mean_std(loader):\n mean = 0\n std = 0\n for images, _ in loader:\n batch_samples = images.size(0)\n images = images.view(batch_samples, images.size(1), -1)\n mean += images.mean(2).sum(0)\n std += images.std(2).sum(0)\n mean /= len(loader.dataset)\n std /= len(loader.dataset)\n return mean, std\n\n\n<mask token>\n", "step-2": "<mask token>\nprint('Total dataset images: ', len(dataset))\n<mask token>\n\n\ndef mean_std(loader):\n mean = 0\n std = 0\n for images, _ in loader:\n batch_samples = images.size(0)\n images = images.view(batch_samples, images.size(1), -1)\n mean += images.mean(2).sum(0)\n std += images.std(2).sum(0)\n mean /= len(loader.dataset)\n std /= len(loader.dataset)\n return mean, std\n\n\n<mask token>\nprint(f'Mean: {mean}')\nprint(f'Std: {std}')\n", "step-3": "<mask token>\nbatch_size = 256\ndata_dir = 'nut_snacks/dataset/'\ndata_transforms = transforms.Compose([transforms.RandomResizedCrop(128),\n transforms.ToTensor()])\ndataset = ImageFolder(data_dir, transform=data_transforms)\nprint('Total dataset images: ', len(dataset))\nloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size)\n\n\ndef mean_std(loader):\n mean = 0\n std = 0\n for images, _ in loader:\n batch_samples = images.size(0)\n images = images.view(batch_samples, images.size(1), -1)\n mean += images.mean(2).sum(0)\n std += images.std(2).sum(0)\n mean /= len(loader.dataset)\n std /= len(loader.dataset)\n return mean, std\n\n\nmean, std = mean_std(loader)\nprint(f'Mean: {mean}')\nprint(f'Std: {std}')\n", "step-4": "import torch\nfrom torchvision import datasets, transforms\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.utils.data import random_split\nfrom torchvision.datasets import ImageFolder\nbatch_size = 256\ndata_dir = 'nut_snacks/dataset/'\ndata_transforms = transforms.Compose([transforms.RandomResizedCrop(128),\n transforms.ToTensor()])\ndataset = ImageFolder(data_dir, transform=data_transforms)\nprint('Total dataset images: ', len(dataset))\nloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size)\n\n\ndef mean_std(loader):\n mean = 0\n std = 0\n for images, _ in loader:\n batch_samples = images.size(0)\n images = images.view(batch_samples, images.size(1), -1)\n mean += images.mean(2).sum(0)\n std += images.std(2).sum(0)\n mean /= len(loader.dataset)\n std /= len(loader.dataset)\n return mean, std\n\n\nmean, std = mean_std(loader)\nprint(f'Mean: {mean}')\nprint(f'Std: {std}')\n", "step-5": "import torch\nfrom torchvision import datasets, transforms\nfrom torch.utils.data import Dataset, DataLoader\n # load the data Set\n\nfrom torch.utils.data import random_split\nfrom torchvision.datasets import ImageFolder\n\n\nbatch_size = 256\ndata_dir = 'nut_snacks/dataset/'\n\ndata_transforms = transforms.Compose(\n [transforms.RandomResizedCrop(128),\n \n transforms.ToTensor(),\n ])\n\ndataset = ImageFolder(data_dir, transform=data_transforms)\nprint('Total dataset images: ',len(dataset))\n\n\nloader = torch.utils.data.DataLoader(\n dataset, batch_size=batch_size)\n\n\n\n\ndef mean_std(loader):\n\tmean = 0\n\tstd = 0\n\tfor images, _ in loader :\n\t\tbatch_samples = images.size(0)\n\t\timages = images.view(batch_samples, images.size(1), -1)\n\t\tmean += images.mean(2).sum(0)\n\t\tstd += images.std(2).sum(0)\n\tmean /= len(loader.dataset)\n\tstd /= len(loader.dataset) \n\treturn mean,std\n\nmean, std = mean_std(loader)\n\nprint(f'Mean: {mean}')\n\nprint(f'Std: {std}')\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
class Solution: ''' 先遍历整个string,并记录最小的character的出现次数。 如果最小character出现次数都不小于k,那么说明整个string就是满足条件的longest substring,返回原string的长度即可; 如果character的出现次数小于k,假设这个character是c,因为满足条件的substring永远不会包含c,所以满足条件的substring一定是在以c为分割参考下的某个substring中。所以我们需要做的就是把c当做是split的参考,在得到的String[]中再次调用我们的method,找到最大的返回值即可。 ''' def longestSubstring(self, s: str, k: int) -> int: def helper(s, k): if len(s) < k: return 0 ch = min(set(s), key=s.count) if s.count(ch) >= k: return len(s) else: return max(helper(t, k) for t in s.split(ch)) return helper(s, k)
normal
{ "blob_id": "6ba830aafbe8e4b42a0b927328ebcad1424cda5e", "index": 8381, "step-1": "<mask token>\n", "step-2": "class Solution:\n <mask token>\n <mask token>\n", "step-3": "class Solution:\n <mask token>\n\n def longestSubstring(self, s: str, k: int) ->int:\n\n def helper(s, k):\n if len(s) < k:\n return 0\n ch = min(set(s), key=s.count)\n if s.count(ch) >= k:\n return len(s)\n else:\n return max(helper(t, k) for t in s.split(ch))\n return helper(s, k)\n", "step-4": "class Solution:\n \"\"\"\n 先遍历整个string,并记录最小的character的出现次数。\n 如果最小character出现次数都不小于k,那么说明整个string就是满足条件的longest substring,返回原string的长度即可;\n 如果character的出现次数小于k,假设这个character是c,因为满足条件的substring永远不会包含c,所以满足条件的substring一定是在以c为分割参考下的某个substring中。所以我们需要做的就是把c当做是split的参考,在得到的String[]中再次调用我们的method,找到最大的返回值即可。\n \"\"\"\n\n def longestSubstring(self, s: str, k: int) ->int:\n\n def helper(s, k):\n if len(s) < k:\n return 0\n ch = min(set(s), key=s.count)\n if s.count(ch) >= k:\n return len(s)\n else:\n return max(helper(t, k) for t in s.split(ch))\n return helper(s, k)\n", "step-5": "class Solution:\n '''\n 先遍历整个string,并记录最小的character的出现次数。\n 如果最小character出现次数都不小于k,那么说明整个string就是满足条件的longest substring,返回原string的长度即可;\n 如果character的出现次数小于k,假设这个character是c,因为满足条件的substring永远不会包含c,所以满足条件的substring一定是在以c为分割参考下的某个substring中。所以我们需要做的就是把c当做是split的参考,在得到的String[]中再次调用我们的method,找到最大的返回值即可。\n '''\n\n def longestSubstring(self, s: str, k: int) -> int:\n def helper(s, k):\n if len(s) < k:\n return 0\n ch = min(set(s), key=s.count)\n if s.count(ch) >= k:\n return len(s)\n else:\n return max(helper(t, k) for t in s.split(ch))\n return helper(s, k)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def main(): hosts = {'127.0.0.1': 'carpenter'} myThread.messageListenThread(hosts) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def main(): hosts = {'127.0.0.1': 'carpenter'} myThread.messageListenThread(hosts) if __name__ == '__main__': main() <|reserved_special_token_1|> import myThread def main(): hosts = {'127.0.0.1': 'carpenter'} myThread.messageListenThread(hosts) if __name__ == '__main__': main() <|reserved_special_token_1|> import myThread def main(): hosts={"127.0.0.1":"carpenter"} myThread.messageListenThread(hosts) if __name__ == '__main__': main()
flexible
{ "blob_id": "b0a49f5876bc3837b69a6dc274f9587a37351495", "index": 8370, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef main():\n hosts = {'127.0.0.1': 'carpenter'}\n myThread.messageListenThread(hosts)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef main():\n hosts = {'127.0.0.1': 'carpenter'}\n myThread.messageListenThread(hosts)\n\n\nif __name__ == '__main__':\n main()\n", "step-4": "import myThread\n\n\ndef main():\n hosts = {'127.0.0.1': 'carpenter'}\n myThread.messageListenThread(hosts)\n\n\nif __name__ == '__main__':\n main()\n", "step-5": "import myThread\r\n\r\ndef main():\r\n\thosts={\"127.0.0.1\":\"carpenter\"}\r\n\tmyThread.messageListenThread(hosts)\r\n\r\n\r\nif __name__ == '__main__':\r\n\tmain()", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> class EuclideanLoss(nn.Module): <|reserved_special_token_0|> <|reserved_special_token_0|> class CostFunction(nn.Module): def __init__(self, c_p, c_h): super().__init__() self.c_p = c_p self.c_h = c_h def forward(self, y, d): """ y: prediction, size = (n_product, n_obs) d: actual sales, size = (n_product, n_obs) """ cost = torch.add(y, -d) cost = torch.add(torch.mul(torch.max(cost, torch.zeros(1)), self. c_p), torch.mul(torch.max(-cost, torch.zeros(1)), self.c_h)) cost = torch.sum(cost) return cost <|reserved_special_token_1|> <|reserved_special_token_0|> class EuclideanLoss(nn.Module): def __init__(self, c_p, c_h): super().__init__() self.c_p = c_p self.c_h = c_h <|reserved_special_token_0|> class CostFunction(nn.Module): def __init__(self, c_p, c_h): super().__init__() self.c_p = c_p self.c_h = c_h def forward(self, y, d): """ y: prediction, size = (n_product, n_obs) d: actual sales, size = (n_product, n_obs) """ cost = torch.add(y, -d) cost = torch.add(torch.mul(torch.max(cost, torch.zeros(1)), self. c_p), torch.mul(torch.max(-cost, torch.zeros(1)), self.c_h)) cost = torch.sum(cost) return cost <|reserved_special_token_1|> <|reserved_special_token_0|> class EuclideanLoss(nn.Module): def __init__(self, c_p, c_h): super().__init__() self.c_p = c_p self.c_h = c_h def forward(self, y, d): """ y: prediction, size = (n_product, n_obs) d: actual sales, size = (n_product, n_obs) """ diff = torch.add(y, -d) diff = torch.add(torch.mul(torch.max(diff, torch.zeros(1)), self. c_p), torch.mul(torch.max(-diff, torch.zeros(1)), self.c_h)) diff = torch.norm(diff) diff = torch.sum(diff) return diff class CostFunction(nn.Module): def __init__(self, c_p, c_h): super().__init__() self.c_p = c_p self.c_h = c_h def forward(self, y, d): """ y: prediction, size = (n_product, n_obs) d: actual sales, size = (n_product, n_obs) """ cost = torch.add(y, -d) cost = torch.add(torch.mul(torch.max(cost, torch.zeros(1)), self. c_p), torch.mul(torch.max(-cost, torch.zeros(1)), self.c_h)) cost = torch.sum(cost) return cost <|reserved_special_token_1|> import torch import torch.nn as nn import numpy as np class EuclideanLoss(nn.Module): def __init__(self, c_p, c_h): super().__init__() self.c_p = c_p self.c_h = c_h def forward(self, y, d): """ y: prediction, size = (n_product, n_obs) d: actual sales, size = (n_product, n_obs) """ diff = torch.add(y, -d) diff = torch.add(torch.mul(torch.max(diff, torch.zeros(1)), self. c_p), torch.mul(torch.max(-diff, torch.zeros(1)), self.c_h)) diff = torch.norm(diff) diff = torch.sum(diff) return diff class CostFunction(nn.Module): def __init__(self, c_p, c_h): super().__init__() self.c_p = c_p self.c_h = c_h def forward(self, y, d): """ y: prediction, size = (n_product, n_obs) d: actual sales, size = (n_product, n_obs) """ cost = torch.add(y, -d) cost = torch.add(torch.mul(torch.max(cost, torch.zeros(1)), self. c_p), torch.mul(torch.max(-cost, torch.zeros(1)), self.c_h)) cost = torch.sum(cost) return cost <|reserved_special_token_1|> import torch import torch.nn as nn import numpy as np class EuclideanLoss(nn.Module): def __init__(self, c_p, c_h): super().__init__() self.c_p = c_p self.c_h = c_h def forward(self, y, d): ''' y: prediction, size = (n_product, n_obs) d: actual sales, size = (n_product, n_obs) ''' diff = torch.add(y, -d) diff = torch.add(torch.mul(torch.max(diff, torch.zeros(1)), self.c_p), torch.mul(torch.max(-diff, torch.zeros(1)), self.c_h)) diff = torch.norm(diff) diff = torch.sum(diff) return diff class CostFunction(nn.Module): def __init__(self, c_p, c_h): super().__init__() self.c_p = c_p self.c_h = c_h def forward(self, y, d): ''' y: prediction, size = (n_product, n_obs) d: actual sales, size = (n_product, n_obs) ''' cost = torch.add(y, -d) cost = torch.add(torch.mul(torch.max(cost, torch.zeros(1)), self.c_p), torch.mul(torch.max(-cost, torch.zeros(1)), self.c_h)) cost = torch.sum(cost) return cost
flexible
{ "blob_id": "67be25e8fdf004515e18e1c20b8d0238222a2172", "index": 1401, "step-1": "<mask token>\n\n\nclass EuclideanLoss(nn.Module):\n <mask token>\n <mask token>\n\n\nclass CostFunction(nn.Module):\n\n def __init__(self, c_p, c_h):\n super().__init__()\n self.c_p = c_p\n self.c_h = c_h\n\n def forward(self, y, d):\n \"\"\"\n y: prediction, size = (n_product, n_obs)\n d: actual sales, size = (n_product, n_obs)\n \"\"\"\n cost = torch.add(y, -d)\n cost = torch.add(torch.mul(torch.max(cost, torch.zeros(1)), self.\n c_p), torch.mul(torch.max(-cost, torch.zeros(1)), self.c_h))\n cost = torch.sum(cost)\n return cost\n", "step-2": "<mask token>\n\n\nclass EuclideanLoss(nn.Module):\n\n def __init__(self, c_p, c_h):\n super().__init__()\n self.c_p = c_p\n self.c_h = c_h\n <mask token>\n\n\nclass CostFunction(nn.Module):\n\n def __init__(self, c_p, c_h):\n super().__init__()\n self.c_p = c_p\n self.c_h = c_h\n\n def forward(self, y, d):\n \"\"\"\n y: prediction, size = (n_product, n_obs)\n d: actual sales, size = (n_product, n_obs)\n \"\"\"\n cost = torch.add(y, -d)\n cost = torch.add(torch.mul(torch.max(cost, torch.zeros(1)), self.\n c_p), torch.mul(torch.max(-cost, torch.zeros(1)), self.c_h))\n cost = torch.sum(cost)\n return cost\n", "step-3": "<mask token>\n\n\nclass EuclideanLoss(nn.Module):\n\n def __init__(self, c_p, c_h):\n super().__init__()\n self.c_p = c_p\n self.c_h = c_h\n\n def forward(self, y, d):\n \"\"\"\n y: prediction, size = (n_product, n_obs)\n d: actual sales, size = (n_product, n_obs)\n \"\"\"\n diff = torch.add(y, -d)\n diff = torch.add(torch.mul(torch.max(diff, torch.zeros(1)), self.\n c_p), torch.mul(torch.max(-diff, torch.zeros(1)), self.c_h))\n diff = torch.norm(diff)\n diff = torch.sum(diff)\n return diff\n\n\nclass CostFunction(nn.Module):\n\n def __init__(self, c_p, c_h):\n super().__init__()\n self.c_p = c_p\n self.c_h = c_h\n\n def forward(self, y, d):\n \"\"\"\n y: prediction, size = (n_product, n_obs)\n d: actual sales, size = (n_product, n_obs)\n \"\"\"\n cost = torch.add(y, -d)\n cost = torch.add(torch.mul(torch.max(cost, torch.zeros(1)), self.\n c_p), torch.mul(torch.max(-cost, torch.zeros(1)), self.c_h))\n cost = torch.sum(cost)\n return cost\n", "step-4": "import torch\nimport torch.nn as nn\nimport numpy as np\n\n\nclass EuclideanLoss(nn.Module):\n\n def __init__(self, c_p, c_h):\n super().__init__()\n self.c_p = c_p\n self.c_h = c_h\n\n def forward(self, y, d):\n \"\"\"\n y: prediction, size = (n_product, n_obs)\n d: actual sales, size = (n_product, n_obs)\n \"\"\"\n diff = torch.add(y, -d)\n diff = torch.add(torch.mul(torch.max(diff, torch.zeros(1)), self.\n c_p), torch.mul(torch.max(-diff, torch.zeros(1)), self.c_h))\n diff = torch.norm(diff)\n diff = torch.sum(diff)\n return diff\n\n\nclass CostFunction(nn.Module):\n\n def __init__(self, c_p, c_h):\n super().__init__()\n self.c_p = c_p\n self.c_h = c_h\n\n def forward(self, y, d):\n \"\"\"\n y: prediction, size = (n_product, n_obs)\n d: actual sales, size = (n_product, n_obs)\n \"\"\"\n cost = torch.add(y, -d)\n cost = torch.add(torch.mul(torch.max(cost, torch.zeros(1)), self.\n c_p), torch.mul(torch.max(-cost, torch.zeros(1)), self.c_h))\n cost = torch.sum(cost)\n return cost\n", "step-5": "import torch\nimport torch.nn as nn\nimport numpy as np\n\nclass EuclideanLoss(nn.Module):\n\n def __init__(self, c_p, c_h):\n super().__init__()\n self.c_p = c_p\n self.c_h = c_h\n\n def forward(self, y, d):\n '''\n y: prediction, size = (n_product, n_obs)\n d: actual sales, size = (n_product, n_obs)\n '''\n\n diff = torch.add(y, -d)\n diff = torch.add(torch.mul(torch.max(diff, torch.zeros(1)), self.c_p), torch.mul(torch.max(-diff, torch.zeros(1)), self.c_h))\n diff = torch.norm(diff)\n diff = torch.sum(diff)\n return diff\n\nclass CostFunction(nn.Module):\n\n def __init__(self, c_p, c_h):\n super().__init__()\n self.c_p = c_p\n self.c_h = c_h\n\n def forward(self, y, d):\n '''\n y: prediction, size = (n_product, n_obs)\n d: actual sales, size = (n_product, n_obs)\n '''\n\n cost = torch.add(y, -d)\n cost = torch.add(torch.mul(torch.max(cost, torch.zeros(1)), self.c_p), torch.mul(torch.max(-cost, torch.zeros(1)), self.c_h))\n cost = torch.sum(cost)\n\n return cost", "step-ids": [ 4, 5, 6, 7, 8 ] }
[ 4, 5, 6, 7, 8 ]
<|reserved_special_token_0|> def sexpr_key(s_expr): return s_expr.strip('(').split(' ')[0] <|reserved_special_token_0|> def list_data(_list): if type(_list) is type(list()): return _list[1] else: temp = expr_data(_list) if temp: return temp[0] else: return [] <|reserved_special_token_0|> def mean(data): if data: return float(sum(data)) / len(data) else: return 0 <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def sexpr_key(s_expr): return s_expr.strip('(').split(' ')[0] def expr_key(expr): return expr.split(' ')[0] def expr_data(expr): return expr.split(' ')[1:] def list_key(_list): if type(_list) is type(list()): return _list[0] else: return expr_key(_list) def list_data(_list): if type(_list) is type(list()): return _list[1] else: temp = expr_data(_list) if temp: return temp[0] else: return [] <|reserved_special_token_0|> def mean(data): if data: return float(sum(data)) / len(data) else: return 0 <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def sexpr_key(s_expr): return s_expr.strip('(').split(' ')[0] def expr_key(expr): return expr.split(' ')[0] def expr_data(expr): return expr.split(' ')[1:] def list_key(_list): if type(_list) is type(list()): return _list[0] else: return expr_key(_list) def list_data(_list): if type(_list) is type(list()): return _list[1] else: temp = expr_data(_list) if temp: return temp[0] else: return [] <|reserved_special_token_0|> def mean(data): if data: return float(sum(data)) / len(data) else: return 0 def variance(data): if data: m_mean = mean(data) return sum([math.pow(i - m_mean, 2) for i in data]) / len(data) else: return 0 <|reserved_special_token_1|> <|reserved_special_token_0|> def sexpr_key(s_expr): return s_expr.strip('(').split(' ')[0] def expr_key(expr): return expr.split(' ')[0] def expr_data(expr): return expr.split(' ')[1:] def list_key(_list): if type(_list) is type(list()): return _list[0] else: return expr_key(_list) def list_data(_list): if type(_list) is type(list()): return _list[1] else: temp = expr_data(_list) if temp: return temp[0] else: return [] def extracted_data(string): t = string.split(' ') t.pop(0) return t def mean(data): if data: return float(sum(data)) / len(data) else: return 0 def variance(data): if data: m_mean = mean(data) return sum([math.pow(i - m_mean, 2) for i in data]) / len(data) else: return 0 <|reserved_special_token_1|> import math def sexpr_key(s_expr): return s_expr.strip('(').split(' ')[0] def expr_key(expr): return expr.split(' ')[0] def expr_data(expr): return expr.split(' ')[1:] def list_key(_list): if type(_list) is type(list()): return _list[0] else: return expr_key(_list) def list_data(_list): if type(_list) is type(list()): return _list[1] else: temp = expr_data(_list) if temp: return temp[0] else: return [] def extracted_data(string): t = string.split(' ') t.pop(0) return t def mean(data): if data: return float(sum(data))/len(data) else: return 0 def variance(data): if data: m_mean = mean(data) return sum([math.pow((i - m_mean), 2) for i in data])/len(data) else: return 0
flexible
{ "blob_id": "18789b5106d4be8a02197b165e16a74c08a58c66", "index": 8578, "step-1": "<mask token>\n\n\ndef sexpr_key(s_expr):\n return s_expr.strip('(').split(' ')[0]\n\n\n<mask token>\n\n\ndef list_data(_list):\n if type(_list) is type(list()):\n return _list[1]\n else:\n temp = expr_data(_list)\n if temp:\n return temp[0]\n else:\n return []\n\n\n<mask token>\n\n\ndef mean(data):\n if data:\n return float(sum(data)) / len(data)\n else:\n return 0\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef sexpr_key(s_expr):\n return s_expr.strip('(').split(' ')[0]\n\n\ndef expr_key(expr):\n return expr.split(' ')[0]\n\n\ndef expr_data(expr):\n return expr.split(' ')[1:]\n\n\ndef list_key(_list):\n if type(_list) is type(list()):\n return _list[0]\n else:\n return expr_key(_list)\n\n\ndef list_data(_list):\n if type(_list) is type(list()):\n return _list[1]\n else:\n temp = expr_data(_list)\n if temp:\n return temp[0]\n else:\n return []\n\n\n<mask token>\n\n\ndef mean(data):\n if data:\n return float(sum(data)) / len(data)\n else:\n return 0\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef sexpr_key(s_expr):\n return s_expr.strip('(').split(' ')[0]\n\n\ndef expr_key(expr):\n return expr.split(' ')[0]\n\n\ndef expr_data(expr):\n return expr.split(' ')[1:]\n\n\ndef list_key(_list):\n if type(_list) is type(list()):\n return _list[0]\n else:\n return expr_key(_list)\n\n\ndef list_data(_list):\n if type(_list) is type(list()):\n return _list[1]\n else:\n temp = expr_data(_list)\n if temp:\n return temp[0]\n else:\n return []\n\n\n<mask token>\n\n\ndef mean(data):\n if data:\n return float(sum(data)) / len(data)\n else:\n return 0\n\n\ndef variance(data):\n if data:\n m_mean = mean(data)\n return sum([math.pow(i - m_mean, 2) for i in data]) / len(data)\n else:\n return 0\n", "step-4": "<mask token>\n\n\ndef sexpr_key(s_expr):\n return s_expr.strip('(').split(' ')[0]\n\n\ndef expr_key(expr):\n return expr.split(' ')[0]\n\n\ndef expr_data(expr):\n return expr.split(' ')[1:]\n\n\ndef list_key(_list):\n if type(_list) is type(list()):\n return _list[0]\n else:\n return expr_key(_list)\n\n\ndef list_data(_list):\n if type(_list) is type(list()):\n return _list[1]\n else:\n temp = expr_data(_list)\n if temp:\n return temp[0]\n else:\n return []\n\n\ndef extracted_data(string):\n t = string.split(' ')\n t.pop(0)\n return t\n\n\ndef mean(data):\n if data:\n return float(sum(data)) / len(data)\n else:\n return 0\n\n\ndef variance(data):\n if data:\n m_mean = mean(data)\n return sum([math.pow(i - m_mean, 2) for i in data]) / len(data)\n else:\n return 0\n", "step-5": "import math\n\ndef sexpr_key(s_expr):\n return s_expr.strip('(').split(' ')[0]\n\ndef expr_key(expr):\n return expr.split(' ')[0]\n\ndef expr_data(expr):\n return expr.split(' ')[1:]\n\ndef list_key(_list):\n if type(_list) is type(list()):\n return _list[0]\n else:\n return expr_key(_list)\n \n\ndef list_data(_list):\n if type(_list) is type(list()):\n return _list[1]\n else:\n temp = expr_data(_list)\n if temp:\n return temp[0]\n else:\n return []\n\ndef extracted_data(string):\n t = string.split(' ')\n t.pop(0)\n return t\n\n\ndef mean(data):\n if data:\n return float(sum(data))/len(data)\n else:\n return 0\n\ndef variance(data):\n if data:\n m_mean = mean(data)\n return sum([math.pow((i - m_mean), 2) for i in data])/len(data)\n else:\n return 0\n \n", "step-ids": [ 3, 6, 7, 8, 10 ] }
[ 3, 6, 7, 8, 10 ]
import sys, os import cv2 # set the video reader video_path = 0 # camera number index # video_path = "/home/pacific/Documents/Work/Projects/Workflows/server/PycharmProjects/Pacific_AvatarGame_Host/humanpose_2d/LiveCamera/test.mp4" # real video file if type(video_path).__name__ == "str": videoReader = cv2.VideoCapture(video_path) print("Load live video from file...") elif type(video_path).__name__ == "int": videoReader = cv2.VideoCapture(video_path) print("Get live video from camera...") if videoReader.isOpened(): print("Camera staus ready...") else: print("Camera status fault...") exit() video_fps = videoReader.get(cv2.CAP_PROP_FPS) print("Live Video FPS: ", video_fps) video_width = videoReader.get(cv2.CAP_PROP_FRAME_WIDTH) video_height = videoReader.get(cv2.CAP_PROP_FRAME_HEIGHT) video_size = (int(video_width), int(video_height)) print("Live Video Size: ", video_size) # set the video writer videoWriter = cv2.VideoWriter('./save.avi', cv2.VideoWriter_fourcc('M', 'P', '4', '2'), int(video_fps), video_size) # read and write the video frame while videoReader.isOpened(): success, frame = videoReader.read() if success: # show the video frame print("Live Video Frame Shape: {}".format(frame.shape)) cv2.putText(frame, "Live Camera", (470,30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,255,255), 2) cv2.namedWindow("Live Video", 0) cv2.imshow("Live Video", frame) # save the video frame videoWriter.write(frame) cv2.waitKey(20) # wait 20 ms for next frame of the live video # check whether manual exit command entered if cv2.waitKey(1) & 0xFF == ord('q'): break else: continue videoReader.release() videoWriter.release() cv2.destroyAllWindows() print("Live Video Done.")
normal
{ "blob_id": "08408cf096bbe23f9a832cc0cf2e017abdbd359f", "index": 4591, "step-1": "<mask token>\n", "step-2": "<mask token>\nif type(video_path).__name__ == 'str':\n videoReader = cv2.VideoCapture(video_path)\n print('Load live video from file...')\nelif type(video_path).__name__ == 'int':\n videoReader = cv2.VideoCapture(video_path)\n print('Get live video from camera...')\nif videoReader.isOpened():\n print('Camera staus ready...')\nelse:\n print('Camera status fault...')\n exit()\n<mask token>\nprint('Live Video FPS: ', video_fps)\n<mask token>\nprint('Live Video Size: ', video_size)\n<mask token>\nwhile videoReader.isOpened():\n success, frame = videoReader.read()\n if success:\n print('Live Video Frame Shape: {}'.format(frame.shape))\n cv2.putText(frame, 'Live Camera', (470, 30), cv2.\n FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 2)\n cv2.namedWindow('Live Video', 0)\n cv2.imshow('Live Video', frame)\n videoWriter.write(frame)\n cv2.waitKey(20)\n if cv2.waitKey(1) & 255 == ord('q'):\n break\n else:\n continue\nvideoReader.release()\nvideoWriter.release()\ncv2.destroyAllWindows()\nprint('Live Video Done.')\n", "step-3": "<mask token>\nvideo_path = 0\nif type(video_path).__name__ == 'str':\n videoReader = cv2.VideoCapture(video_path)\n print('Load live video from file...')\nelif type(video_path).__name__ == 'int':\n videoReader = cv2.VideoCapture(video_path)\n print('Get live video from camera...')\nif videoReader.isOpened():\n print('Camera staus ready...')\nelse:\n print('Camera status fault...')\n exit()\nvideo_fps = videoReader.get(cv2.CAP_PROP_FPS)\nprint('Live Video FPS: ', video_fps)\nvideo_width = videoReader.get(cv2.CAP_PROP_FRAME_WIDTH)\nvideo_height = videoReader.get(cv2.CAP_PROP_FRAME_HEIGHT)\nvideo_size = int(video_width), int(video_height)\nprint('Live Video Size: ', video_size)\nvideoWriter = cv2.VideoWriter('./save.avi', cv2.VideoWriter_fourcc('M', 'P',\n '4', '2'), int(video_fps), video_size)\nwhile videoReader.isOpened():\n success, frame = videoReader.read()\n if success:\n print('Live Video Frame Shape: {}'.format(frame.shape))\n cv2.putText(frame, 'Live Camera', (470, 30), cv2.\n FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 2)\n cv2.namedWindow('Live Video', 0)\n cv2.imshow('Live Video', frame)\n videoWriter.write(frame)\n cv2.waitKey(20)\n if cv2.waitKey(1) & 255 == ord('q'):\n break\n else:\n continue\nvideoReader.release()\nvideoWriter.release()\ncv2.destroyAllWindows()\nprint('Live Video Done.')\n", "step-4": "import sys, os\nimport cv2\nvideo_path = 0\nif type(video_path).__name__ == 'str':\n videoReader = cv2.VideoCapture(video_path)\n print('Load live video from file...')\nelif type(video_path).__name__ == 'int':\n videoReader = cv2.VideoCapture(video_path)\n print('Get live video from camera...')\nif videoReader.isOpened():\n print('Camera staus ready...')\nelse:\n print('Camera status fault...')\n exit()\nvideo_fps = videoReader.get(cv2.CAP_PROP_FPS)\nprint('Live Video FPS: ', video_fps)\nvideo_width = videoReader.get(cv2.CAP_PROP_FRAME_WIDTH)\nvideo_height = videoReader.get(cv2.CAP_PROP_FRAME_HEIGHT)\nvideo_size = int(video_width), int(video_height)\nprint('Live Video Size: ', video_size)\nvideoWriter = cv2.VideoWriter('./save.avi', cv2.VideoWriter_fourcc('M', 'P',\n '4', '2'), int(video_fps), video_size)\nwhile videoReader.isOpened():\n success, frame = videoReader.read()\n if success:\n print('Live Video Frame Shape: {}'.format(frame.shape))\n cv2.putText(frame, 'Live Camera', (470, 30), cv2.\n FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 2)\n cv2.namedWindow('Live Video', 0)\n cv2.imshow('Live Video', frame)\n videoWriter.write(frame)\n cv2.waitKey(20)\n if cv2.waitKey(1) & 255 == ord('q'):\n break\n else:\n continue\nvideoReader.release()\nvideoWriter.release()\ncv2.destroyAllWindows()\nprint('Live Video Done.')\n", "step-5": "import sys, os\nimport cv2\n\n\n# set the video reader\nvideo_path = 0 # camera number index\n# video_path = \"/home/pacific/Documents/Work/Projects/Workflows/server/PycharmProjects/Pacific_AvatarGame_Host/humanpose_2d/LiveCamera/test.mp4\" # real video file\nif type(video_path).__name__ == \"str\":\n videoReader = cv2.VideoCapture(video_path)\n print(\"Load live video from file...\")\nelif type(video_path).__name__ == \"int\":\n videoReader = cv2.VideoCapture(video_path)\n print(\"Get live video from camera...\")\n\nif videoReader.isOpened():\n print(\"Camera staus ready...\")\nelse:\n print(\"Camera status fault...\")\n exit()\n\nvideo_fps = videoReader.get(cv2.CAP_PROP_FPS)\nprint(\"Live Video FPS: \", video_fps)\n\nvideo_width = videoReader.get(cv2.CAP_PROP_FRAME_WIDTH)\nvideo_height = videoReader.get(cv2.CAP_PROP_FRAME_HEIGHT)\nvideo_size = (int(video_width), int(video_height))\nprint(\"Live Video Size: \", video_size)\n\n# set the video writer\nvideoWriter = cv2.VideoWriter('./save.avi', cv2.VideoWriter_fourcc('M', 'P', '4', '2'), int(video_fps), video_size)\n\n# read and write the video frame\nwhile videoReader.isOpened():\n success, frame = videoReader.read()\n if success:\n # show the video frame\n print(\"Live Video Frame Shape: {}\".format(frame.shape))\n cv2.putText(frame, \"Live Camera\", (470,30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,255,255), 2)\n cv2.namedWindow(\"Live Video\", 0)\n cv2.imshow(\"Live Video\", frame)\n\n # save the video frame\n videoWriter.write(frame)\n cv2.waitKey(20) # wait 20 ms for next frame of the live video\n\n # check whether manual exit command entered\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n else:\n continue\n\nvideoReader.release()\nvideoWriter.release()\ncv2.destroyAllWindows()\nprint(\"Live Video Done.\")\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import numpy as np from PIL import Image, ImageDraw import torch from torchvision import transforms import cfg from label import point_inside_of_quad from model_VGG import advancedEAST from preprocess import resize_image from nms import nms def sigmoid(x): """`y = 1 / (1 + exp(-x))`""" return 1 / (1 + np.exp(-x)) def cut_text_line(geo, scale_ratio_w, scale_ratio_h, im_array, img_path, s): geo /= [scale_ratio_w, scale_ratio_h] p_min = np.amin(geo, axis=0) p_max = np.amax(geo, axis=0) min_xy = p_min.astype(int) max_xy = p_max.astype(int) + 2 sub_im_arr = im_array[min_xy[1]:max_xy[1], min_xy[0]:max_xy[0], :].copy() for m in range(min_xy[1], max_xy[1]): for n in range(min_xy[0], max_xy[0]): if not point_inside_of_quad(n, m, geo, p_min, p_max): sub_im_arr[m - min_xy[1], n - min_xy[0], :] = 255 sub_im = Image.fromarray(sub_im_arr.astype('uint8')).convert('RGB') sub_im.save(img_path + '_subim%d.jpg' % s) def predict(east_detect, img_path, pixel_threshold, quiet=False): img = Image.open(img_path) # 为PIL图像对象,默认RGB d_wight, d_height = resize_image(img, cfg.max_predict_img_size) img = img.resize((d_wight, d_height), Image.NEAREST).convert('RGB') x = transforms.ToTensor()(img) x = torch.unsqueeze(x, 0) # 增加一个维度 y = east_detect(x) y = torch.squeeze(y, 0) # 减少一个维度 print(y.shape) y = y.detach().numpy() # 7*64*64 if y.shape[0] == 7: y = y.transpose((1, 2, 0)) # CHW->HWC y[:, :, :3] = sigmoid(y[:, :, :3]) cond = np.greater_equal(y[:, :, 0], pixel_threshold) activation_pixels = np.where(cond) quad_scores, quad_after_nms = nms(y, activation_pixels) with Image.open(img_path) as im: im_array = np.array(im.convert('RGB')) # 图片转为numpy数组 d_wight, d_height = resize_image(im, cfg.max_predict_img_size) scale_ratio_w = d_wight / im.width scale_ratio_h = d_height / im.height im = im.resize((d_wight, d_height), Image.NEAREST).convert('RGB') quad_im = im.copy() draw = ImageDraw.Draw(im) for i, j in zip(activation_pixels[0], activation_pixels[1]): px = (j + 0.5) * cfg.pixel_size py = (i + 0.5) * cfg.pixel_size line_width, line_color = 1, 'red' if y[i, j, 1] >= cfg.side_vertex_pixel_threshold: if y[i, j, 2] < cfg.trunc_threshold: line_width, line_color = 2, 'yellow' elif y[i, j, 2] >= 1 - cfg.trunc_threshold: line_width, line_color = 2, 'green' draw.line([(px - 0.5 * cfg.pixel_size, py - 0.5 * cfg.pixel_size), (px + 0.5 * cfg.pixel_size, py - 0.5 * cfg.pixel_size), (px + 0.5 * cfg.pixel_size, py + 0.5 * cfg.pixel_size), (px - 0.5 * cfg.pixel_size, py + 0.5 * cfg.pixel_size), (px - 0.5 * cfg.pixel_size, py - 0.5 * cfg.pixel_size)], width=line_width, fill=line_color) im.save(img_path + '_act.jpg') quad_draw = ImageDraw.Draw(quad_im) txt_items = [] for score, geo, s in zip(quad_scores, quad_after_nms, range(len(quad_scores))): if np.amin(score) > 0: quad_draw.line([tuple(geo[0]), tuple(geo[1]), tuple(geo[2]), tuple(geo[3]), tuple(geo[0])], width=2, fill='red') if cfg.predict_cut_text_line: cut_text_line(geo, scale_ratio_w, scale_ratio_h, im_array, img_path, s) rescaled_geo = geo / [scale_ratio_w, scale_ratio_h] # (N, 4, 2)标签坐标 rescaled_geo_list = np.reshape(rescaled_geo, (8,)).tolist() txt_item = ','.join(map(str, rescaled_geo_list)) txt_items.append(txt_item + '\n') elif not quiet: print('quad invalid with vertex num less then 4.') quad_im.save(img_path + '_predict.jpg') if cfg.predict_write2txt and len(txt_items) > 0: with open(img_path[:-4] + '.txt', 'w') as f_txt: f_txt.writelines(txt_items) def predict_txt(east_detect, img_path, txt_path, pixel_threshold, quiet=False): img = Image.open(img_path) # 为PIL图像对象,默认RGB d_wight, d_height = resize_image(img, cfg.max_predict_img_size) scale_ratio_w = d_wight / img.width scale_ratio_h = d_height / img.height transform = transforms.Compose([ transforms.Resize((d_wight, d_height), interpolation=2), transforms.ToTensor() ]) x = transform(img) x = torch.unsqueeze(x, 0) # 增加一个维度 y = east_detect(x) y = torch.squeeze(y, 0) # 减少一个维度 print(y.shape) y = y.detach().numpy() # 7*64*64 if y.shape[0] == 7: y = y.transpose((1, 2, 0)) # CHW->HWC y[:, :, :3] = sigmoid(y[:, :, :3]) cond = np.greater_equal(y[:, :, 0], pixel_threshold) activation_pixels = np.where(cond) quad_scores, quad_after_nms = nms(y, activation_pixels) txt_items = [] for score, geo in zip(quad_scores, quad_after_nms): if np.amin(score) > 0: rescaled_geo = geo / [scale_ratio_w, scale_ratio_h] rescaled_geo_list = np.reshape(rescaled_geo, (8,)).tolist() txt_item = ','.join(map(str, rescaled_geo_list)) txt_items.append(txt_item + '\n') elif not quiet: print('quad invalid with vertex num less then 4.') if cfg.predict_write2txt and len(txt_items) > 0: with open(txt_path, 'w') as f_txt: f_txt.writelines(txt_items) if __name__ == '__main__': if not os.path.exists('demo'): os.makedirs('./demo', exist_ok=True) img_path = cfg.img_path threshold = float(cfg.predict_threshold) pth_path = cfg.pth_path if cfg.pth_path else 'saved_model/3T736_latest.pth' print(img_path, threshold) east = advancedEAST() state_dict = {k.replace('module.', ''): v for k, v in torch.load(pth_path, map_location='cpu').items()} east.load_state_dict(state_dict) predict(east, img_path, threshold)
normal
{ "blob_id": "48cef0377087d9245aad1fb759adf8ff07d2b66f", "index": 4464, "step-1": "<mask token>\n\n\ndef cut_text_line(geo, scale_ratio_w, scale_ratio_h, im_array, img_path, s):\n geo /= [scale_ratio_w, scale_ratio_h]\n p_min = np.amin(geo, axis=0)\n p_max = np.amax(geo, axis=0)\n min_xy = p_min.astype(int)\n max_xy = p_max.astype(int) + 2\n sub_im_arr = im_array[min_xy[1]:max_xy[1], min_xy[0]:max_xy[0], :].copy()\n for m in range(min_xy[1], max_xy[1]):\n for n in range(min_xy[0], max_xy[0]):\n if not point_inside_of_quad(n, m, geo, p_min, p_max):\n sub_im_arr[m - min_xy[1], n - min_xy[0], :] = 255\n sub_im = Image.fromarray(sub_im_arr.astype('uint8')).convert('RGB')\n sub_im.save(img_path + '_subim%d.jpg' % s)\n\n\n<mask token>\n\n\ndef predict_txt(east_detect, img_path, txt_path, pixel_threshold, quiet=False):\n img = Image.open(img_path)\n d_wight, d_height = resize_image(img, cfg.max_predict_img_size)\n scale_ratio_w = d_wight / img.width\n scale_ratio_h = d_height / img.height\n transform = transforms.Compose([transforms.Resize((d_wight, d_height),\n interpolation=2), transforms.ToTensor()])\n x = transform(img)\n x = torch.unsqueeze(x, 0)\n y = east_detect(x)\n y = torch.squeeze(y, 0)\n print(y.shape)\n y = y.detach().numpy()\n if y.shape[0] == 7:\n y = y.transpose((1, 2, 0))\n y[:, :, :3] = sigmoid(y[:, :, :3])\n cond = np.greater_equal(y[:, :, 0], pixel_threshold)\n activation_pixels = np.where(cond)\n quad_scores, quad_after_nms = nms(y, activation_pixels)\n txt_items = []\n for score, geo in zip(quad_scores, quad_after_nms):\n if np.amin(score) > 0:\n rescaled_geo = geo / [scale_ratio_w, scale_ratio_h]\n rescaled_geo_list = np.reshape(rescaled_geo, (8,)).tolist()\n txt_item = ','.join(map(str, rescaled_geo_list))\n txt_items.append(txt_item + '\\n')\n elif not quiet:\n print('quad invalid with vertex num less then 4.')\n if cfg.predict_write2txt and len(txt_items) > 0:\n with open(txt_path, 'w') as f_txt:\n f_txt.writelines(txt_items)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef sigmoid(x):\n \"\"\"`y = 1 / (1 + exp(-x))`\"\"\"\n return 1 / (1 + np.exp(-x))\n\n\ndef cut_text_line(geo, scale_ratio_w, scale_ratio_h, im_array, img_path, s):\n geo /= [scale_ratio_w, scale_ratio_h]\n p_min = np.amin(geo, axis=0)\n p_max = np.amax(geo, axis=0)\n min_xy = p_min.astype(int)\n max_xy = p_max.astype(int) + 2\n sub_im_arr = im_array[min_xy[1]:max_xy[1], min_xy[0]:max_xy[0], :].copy()\n for m in range(min_xy[1], max_xy[1]):\n for n in range(min_xy[0], max_xy[0]):\n if not point_inside_of_quad(n, m, geo, p_min, p_max):\n sub_im_arr[m - min_xy[1], n - min_xy[0], :] = 255\n sub_im = Image.fromarray(sub_im_arr.astype('uint8')).convert('RGB')\n sub_im.save(img_path + '_subim%d.jpg' % s)\n\n\ndef predict(east_detect, img_path, pixel_threshold, quiet=False):\n img = Image.open(img_path)\n d_wight, d_height = resize_image(img, cfg.max_predict_img_size)\n img = img.resize((d_wight, d_height), Image.NEAREST).convert('RGB')\n x = transforms.ToTensor()(img)\n x = torch.unsqueeze(x, 0)\n y = east_detect(x)\n y = torch.squeeze(y, 0)\n print(y.shape)\n y = y.detach().numpy()\n if y.shape[0] == 7:\n y = y.transpose((1, 2, 0))\n y[:, :, :3] = sigmoid(y[:, :, :3])\n cond = np.greater_equal(y[:, :, 0], pixel_threshold)\n activation_pixels = np.where(cond)\n quad_scores, quad_after_nms = nms(y, activation_pixels)\n with Image.open(img_path) as im:\n im_array = np.array(im.convert('RGB'))\n d_wight, d_height = resize_image(im, cfg.max_predict_img_size)\n scale_ratio_w = d_wight / im.width\n scale_ratio_h = d_height / im.height\n im = im.resize((d_wight, d_height), Image.NEAREST).convert('RGB')\n quad_im = im.copy()\n draw = ImageDraw.Draw(im)\n for i, j in zip(activation_pixels[0], activation_pixels[1]):\n px = (j + 0.5) * cfg.pixel_size\n py = (i + 0.5) * cfg.pixel_size\n line_width, line_color = 1, 'red'\n if y[i, j, 1] >= cfg.side_vertex_pixel_threshold:\n if y[i, j, 2] < cfg.trunc_threshold:\n line_width, line_color = 2, 'yellow'\n elif y[i, j, 2] >= 1 - cfg.trunc_threshold:\n line_width, line_color = 2, 'green'\n draw.line([(px - 0.5 * cfg.pixel_size, py - 0.5 * cfg.\n pixel_size), (px + 0.5 * cfg.pixel_size, py - 0.5 * cfg.\n pixel_size), (px + 0.5 * cfg.pixel_size, py + 0.5 * cfg.\n pixel_size), (px - 0.5 * cfg.pixel_size, py + 0.5 * cfg.\n pixel_size), (px - 0.5 * cfg.pixel_size, py - 0.5 * cfg.\n pixel_size)], width=line_width, fill=line_color)\n im.save(img_path + '_act.jpg')\n quad_draw = ImageDraw.Draw(quad_im)\n txt_items = []\n for score, geo, s in zip(quad_scores, quad_after_nms, range(len(\n quad_scores))):\n if np.amin(score) > 0:\n quad_draw.line([tuple(geo[0]), tuple(geo[1]), tuple(geo[2]),\n tuple(geo[3]), tuple(geo[0])], width=2, fill='red')\n if cfg.predict_cut_text_line:\n cut_text_line(geo, scale_ratio_w, scale_ratio_h,\n im_array, img_path, s)\n rescaled_geo = geo / [scale_ratio_w, scale_ratio_h]\n rescaled_geo_list = np.reshape(rescaled_geo, (8,)).tolist()\n txt_item = ','.join(map(str, rescaled_geo_list))\n txt_items.append(txt_item + '\\n')\n elif not quiet:\n print('quad invalid with vertex num less then 4.')\n quad_im.save(img_path + '_predict.jpg')\n if cfg.predict_write2txt and len(txt_items) > 0:\n with open(img_path[:-4] + '.txt', 'w') as f_txt:\n f_txt.writelines(txt_items)\n\n\ndef predict_txt(east_detect, img_path, txt_path, pixel_threshold, quiet=False):\n img = Image.open(img_path)\n d_wight, d_height = resize_image(img, cfg.max_predict_img_size)\n scale_ratio_w = d_wight / img.width\n scale_ratio_h = d_height / img.height\n transform = transforms.Compose([transforms.Resize((d_wight, d_height),\n interpolation=2), transforms.ToTensor()])\n x = transform(img)\n x = torch.unsqueeze(x, 0)\n y = east_detect(x)\n y = torch.squeeze(y, 0)\n print(y.shape)\n y = y.detach().numpy()\n if y.shape[0] == 7:\n y = y.transpose((1, 2, 0))\n y[:, :, :3] = sigmoid(y[:, :, :3])\n cond = np.greater_equal(y[:, :, 0], pixel_threshold)\n activation_pixels = np.where(cond)\n quad_scores, quad_after_nms = nms(y, activation_pixels)\n txt_items = []\n for score, geo in zip(quad_scores, quad_after_nms):\n if np.amin(score) > 0:\n rescaled_geo = geo / [scale_ratio_w, scale_ratio_h]\n rescaled_geo_list = np.reshape(rescaled_geo, (8,)).tolist()\n txt_item = ','.join(map(str, rescaled_geo_list))\n txt_items.append(txt_item + '\\n')\n elif not quiet:\n print('quad invalid with vertex num less then 4.')\n if cfg.predict_write2txt and len(txt_items) > 0:\n with open(txt_path, 'w') as f_txt:\n f_txt.writelines(txt_items)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef sigmoid(x):\n \"\"\"`y = 1 / (1 + exp(-x))`\"\"\"\n return 1 / (1 + np.exp(-x))\n\n\ndef cut_text_line(geo, scale_ratio_w, scale_ratio_h, im_array, img_path, s):\n geo /= [scale_ratio_w, scale_ratio_h]\n p_min = np.amin(geo, axis=0)\n p_max = np.amax(geo, axis=0)\n min_xy = p_min.astype(int)\n max_xy = p_max.astype(int) + 2\n sub_im_arr = im_array[min_xy[1]:max_xy[1], min_xy[0]:max_xy[0], :].copy()\n for m in range(min_xy[1], max_xy[1]):\n for n in range(min_xy[0], max_xy[0]):\n if not point_inside_of_quad(n, m, geo, p_min, p_max):\n sub_im_arr[m - min_xy[1], n - min_xy[0], :] = 255\n sub_im = Image.fromarray(sub_im_arr.astype('uint8')).convert('RGB')\n sub_im.save(img_path + '_subim%d.jpg' % s)\n\n\ndef predict(east_detect, img_path, pixel_threshold, quiet=False):\n img = Image.open(img_path)\n d_wight, d_height = resize_image(img, cfg.max_predict_img_size)\n img = img.resize((d_wight, d_height), Image.NEAREST).convert('RGB')\n x = transforms.ToTensor()(img)\n x = torch.unsqueeze(x, 0)\n y = east_detect(x)\n y = torch.squeeze(y, 0)\n print(y.shape)\n y = y.detach().numpy()\n if y.shape[0] == 7:\n y = y.transpose((1, 2, 0))\n y[:, :, :3] = sigmoid(y[:, :, :3])\n cond = np.greater_equal(y[:, :, 0], pixel_threshold)\n activation_pixels = np.where(cond)\n quad_scores, quad_after_nms = nms(y, activation_pixels)\n with Image.open(img_path) as im:\n im_array = np.array(im.convert('RGB'))\n d_wight, d_height = resize_image(im, cfg.max_predict_img_size)\n scale_ratio_w = d_wight / im.width\n scale_ratio_h = d_height / im.height\n im = im.resize((d_wight, d_height), Image.NEAREST).convert('RGB')\n quad_im = im.copy()\n draw = ImageDraw.Draw(im)\n for i, j in zip(activation_pixels[0], activation_pixels[1]):\n px = (j + 0.5) * cfg.pixel_size\n py = (i + 0.5) * cfg.pixel_size\n line_width, line_color = 1, 'red'\n if y[i, j, 1] >= cfg.side_vertex_pixel_threshold:\n if y[i, j, 2] < cfg.trunc_threshold:\n line_width, line_color = 2, 'yellow'\n elif y[i, j, 2] >= 1 - cfg.trunc_threshold:\n line_width, line_color = 2, 'green'\n draw.line([(px - 0.5 * cfg.pixel_size, py - 0.5 * cfg.\n pixel_size), (px + 0.5 * cfg.pixel_size, py - 0.5 * cfg.\n pixel_size), (px + 0.5 * cfg.pixel_size, py + 0.5 * cfg.\n pixel_size), (px - 0.5 * cfg.pixel_size, py + 0.5 * cfg.\n pixel_size), (px - 0.5 * cfg.pixel_size, py - 0.5 * cfg.\n pixel_size)], width=line_width, fill=line_color)\n im.save(img_path + '_act.jpg')\n quad_draw = ImageDraw.Draw(quad_im)\n txt_items = []\n for score, geo, s in zip(quad_scores, quad_after_nms, range(len(\n quad_scores))):\n if np.amin(score) > 0:\n quad_draw.line([tuple(geo[0]), tuple(geo[1]), tuple(geo[2]),\n tuple(geo[3]), tuple(geo[0])], width=2, fill='red')\n if cfg.predict_cut_text_line:\n cut_text_line(geo, scale_ratio_w, scale_ratio_h,\n im_array, img_path, s)\n rescaled_geo = geo / [scale_ratio_w, scale_ratio_h]\n rescaled_geo_list = np.reshape(rescaled_geo, (8,)).tolist()\n txt_item = ','.join(map(str, rescaled_geo_list))\n txt_items.append(txt_item + '\\n')\n elif not quiet:\n print('quad invalid with vertex num less then 4.')\n quad_im.save(img_path + '_predict.jpg')\n if cfg.predict_write2txt and len(txt_items) > 0:\n with open(img_path[:-4] + '.txt', 'w') as f_txt:\n f_txt.writelines(txt_items)\n\n\ndef predict_txt(east_detect, img_path, txt_path, pixel_threshold, quiet=False):\n img = Image.open(img_path)\n d_wight, d_height = resize_image(img, cfg.max_predict_img_size)\n scale_ratio_w = d_wight / img.width\n scale_ratio_h = d_height / img.height\n transform = transforms.Compose([transforms.Resize((d_wight, d_height),\n interpolation=2), transforms.ToTensor()])\n x = transform(img)\n x = torch.unsqueeze(x, 0)\n y = east_detect(x)\n y = torch.squeeze(y, 0)\n print(y.shape)\n y = y.detach().numpy()\n if y.shape[0] == 7:\n y = y.transpose((1, 2, 0))\n y[:, :, :3] = sigmoid(y[:, :, :3])\n cond = np.greater_equal(y[:, :, 0], pixel_threshold)\n activation_pixels = np.where(cond)\n quad_scores, quad_after_nms = nms(y, activation_pixels)\n txt_items = []\n for score, geo in zip(quad_scores, quad_after_nms):\n if np.amin(score) > 0:\n rescaled_geo = geo / [scale_ratio_w, scale_ratio_h]\n rescaled_geo_list = np.reshape(rescaled_geo, (8,)).tolist()\n txt_item = ','.join(map(str, rescaled_geo_list))\n txt_items.append(txt_item + '\\n')\n elif not quiet:\n print('quad invalid with vertex num less then 4.')\n if cfg.predict_write2txt and len(txt_items) > 0:\n with open(txt_path, 'w') as f_txt:\n f_txt.writelines(txt_items)\n\n\nif __name__ == '__main__':\n if not os.path.exists('demo'):\n os.makedirs('./demo', exist_ok=True)\n img_path = cfg.img_path\n threshold = float(cfg.predict_threshold)\n pth_path = cfg.pth_path if cfg.pth_path else 'saved_model/3T736_latest.pth'\n print(img_path, threshold)\n east = advancedEAST()\n state_dict = {k.replace('module.', ''): v for k, v in torch.load(\n pth_path, map_location='cpu').items()}\n east.load_state_dict(state_dict)\n predict(east, img_path, threshold)\n", "step-4": "import os\nimport numpy as np\nfrom PIL import Image, ImageDraw\nimport torch\nfrom torchvision import transforms\nimport cfg\nfrom label import point_inside_of_quad\nfrom model_VGG import advancedEAST\nfrom preprocess import resize_image\nfrom nms import nms\n\n\ndef sigmoid(x):\n \"\"\"`y = 1 / (1 + exp(-x))`\"\"\"\n return 1 / (1 + np.exp(-x))\n\n\ndef cut_text_line(geo, scale_ratio_w, scale_ratio_h, im_array, img_path, s):\n geo /= [scale_ratio_w, scale_ratio_h]\n p_min = np.amin(geo, axis=0)\n p_max = np.amax(geo, axis=0)\n min_xy = p_min.astype(int)\n max_xy = p_max.astype(int) + 2\n sub_im_arr = im_array[min_xy[1]:max_xy[1], min_xy[0]:max_xy[0], :].copy()\n for m in range(min_xy[1], max_xy[1]):\n for n in range(min_xy[0], max_xy[0]):\n if not point_inside_of_quad(n, m, geo, p_min, p_max):\n sub_im_arr[m - min_xy[1], n - min_xy[0], :] = 255\n sub_im = Image.fromarray(sub_im_arr.astype('uint8')).convert('RGB')\n sub_im.save(img_path + '_subim%d.jpg' % s)\n\n\ndef predict(east_detect, img_path, pixel_threshold, quiet=False):\n img = Image.open(img_path)\n d_wight, d_height = resize_image(img, cfg.max_predict_img_size)\n img = img.resize((d_wight, d_height), Image.NEAREST).convert('RGB')\n x = transforms.ToTensor()(img)\n x = torch.unsqueeze(x, 0)\n y = east_detect(x)\n y = torch.squeeze(y, 0)\n print(y.shape)\n y = y.detach().numpy()\n if y.shape[0] == 7:\n y = y.transpose((1, 2, 0))\n y[:, :, :3] = sigmoid(y[:, :, :3])\n cond = np.greater_equal(y[:, :, 0], pixel_threshold)\n activation_pixels = np.where(cond)\n quad_scores, quad_after_nms = nms(y, activation_pixels)\n with Image.open(img_path) as im:\n im_array = np.array(im.convert('RGB'))\n d_wight, d_height = resize_image(im, cfg.max_predict_img_size)\n scale_ratio_w = d_wight / im.width\n scale_ratio_h = d_height / im.height\n im = im.resize((d_wight, d_height), Image.NEAREST).convert('RGB')\n quad_im = im.copy()\n draw = ImageDraw.Draw(im)\n for i, j in zip(activation_pixels[0], activation_pixels[1]):\n px = (j + 0.5) * cfg.pixel_size\n py = (i + 0.5) * cfg.pixel_size\n line_width, line_color = 1, 'red'\n if y[i, j, 1] >= cfg.side_vertex_pixel_threshold:\n if y[i, j, 2] < cfg.trunc_threshold:\n line_width, line_color = 2, 'yellow'\n elif y[i, j, 2] >= 1 - cfg.trunc_threshold:\n line_width, line_color = 2, 'green'\n draw.line([(px - 0.5 * cfg.pixel_size, py - 0.5 * cfg.\n pixel_size), (px + 0.5 * cfg.pixel_size, py - 0.5 * cfg.\n pixel_size), (px + 0.5 * cfg.pixel_size, py + 0.5 * cfg.\n pixel_size), (px - 0.5 * cfg.pixel_size, py + 0.5 * cfg.\n pixel_size), (px - 0.5 * cfg.pixel_size, py - 0.5 * cfg.\n pixel_size)], width=line_width, fill=line_color)\n im.save(img_path + '_act.jpg')\n quad_draw = ImageDraw.Draw(quad_im)\n txt_items = []\n for score, geo, s in zip(quad_scores, quad_after_nms, range(len(\n quad_scores))):\n if np.amin(score) > 0:\n quad_draw.line([tuple(geo[0]), tuple(geo[1]), tuple(geo[2]),\n tuple(geo[3]), tuple(geo[0])], width=2, fill='red')\n if cfg.predict_cut_text_line:\n cut_text_line(geo, scale_ratio_w, scale_ratio_h,\n im_array, img_path, s)\n rescaled_geo = geo / [scale_ratio_w, scale_ratio_h]\n rescaled_geo_list = np.reshape(rescaled_geo, (8,)).tolist()\n txt_item = ','.join(map(str, rescaled_geo_list))\n txt_items.append(txt_item + '\\n')\n elif not quiet:\n print('quad invalid with vertex num less then 4.')\n quad_im.save(img_path + '_predict.jpg')\n if cfg.predict_write2txt and len(txt_items) > 0:\n with open(img_path[:-4] + '.txt', 'w') as f_txt:\n f_txt.writelines(txt_items)\n\n\ndef predict_txt(east_detect, img_path, txt_path, pixel_threshold, quiet=False):\n img = Image.open(img_path)\n d_wight, d_height = resize_image(img, cfg.max_predict_img_size)\n scale_ratio_w = d_wight / img.width\n scale_ratio_h = d_height / img.height\n transform = transforms.Compose([transforms.Resize((d_wight, d_height),\n interpolation=2), transforms.ToTensor()])\n x = transform(img)\n x = torch.unsqueeze(x, 0)\n y = east_detect(x)\n y = torch.squeeze(y, 0)\n print(y.shape)\n y = y.detach().numpy()\n if y.shape[0] == 7:\n y = y.transpose((1, 2, 0))\n y[:, :, :3] = sigmoid(y[:, :, :3])\n cond = np.greater_equal(y[:, :, 0], pixel_threshold)\n activation_pixels = np.where(cond)\n quad_scores, quad_after_nms = nms(y, activation_pixels)\n txt_items = []\n for score, geo in zip(quad_scores, quad_after_nms):\n if np.amin(score) > 0:\n rescaled_geo = geo / [scale_ratio_w, scale_ratio_h]\n rescaled_geo_list = np.reshape(rescaled_geo, (8,)).tolist()\n txt_item = ','.join(map(str, rescaled_geo_list))\n txt_items.append(txt_item + '\\n')\n elif not quiet:\n print('quad invalid with vertex num less then 4.')\n if cfg.predict_write2txt and len(txt_items) > 0:\n with open(txt_path, 'w') as f_txt:\n f_txt.writelines(txt_items)\n\n\nif __name__ == '__main__':\n if not os.path.exists('demo'):\n os.makedirs('./demo', exist_ok=True)\n img_path = cfg.img_path\n threshold = float(cfg.predict_threshold)\n pth_path = cfg.pth_path if cfg.pth_path else 'saved_model/3T736_latest.pth'\n print(img_path, threshold)\n east = advancedEAST()\n state_dict = {k.replace('module.', ''): v for k, v in torch.load(\n pth_path, map_location='cpu').items()}\n east.load_state_dict(state_dict)\n predict(east, img_path, threshold)\n", "step-5": "# Copyright 2021 Huawei Technologies Co., Ltd\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# http://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\nimport os\n\nimport numpy as np\nfrom PIL import Image, ImageDraw\nimport torch\nfrom torchvision import transforms\n\nimport cfg\nfrom label import point_inside_of_quad\nfrom model_VGG import advancedEAST\nfrom preprocess import resize_image\nfrom nms import nms\n\n\ndef sigmoid(x):\n \"\"\"`y = 1 / (1 + exp(-x))`\"\"\"\n return 1 / (1 + np.exp(-x))\n\n\ndef cut_text_line(geo, scale_ratio_w, scale_ratio_h, im_array, img_path, s):\n geo /= [scale_ratio_w, scale_ratio_h]\n p_min = np.amin(geo, axis=0)\n p_max = np.amax(geo, axis=0)\n min_xy = p_min.astype(int)\n max_xy = p_max.astype(int) + 2\n sub_im_arr = im_array[min_xy[1]:max_xy[1], min_xy[0]:max_xy[0], :].copy()\n for m in range(min_xy[1], max_xy[1]):\n for n in range(min_xy[0], max_xy[0]):\n if not point_inside_of_quad(n, m, geo, p_min, p_max):\n sub_im_arr[m - min_xy[1], n - min_xy[0], :] = 255\n sub_im = Image.fromarray(sub_im_arr.astype('uint8')).convert('RGB')\n sub_im.save(img_path + '_subim%d.jpg' % s)\n\n\ndef predict(east_detect, img_path, pixel_threshold, quiet=False):\n img = Image.open(img_path) # 为PIL图像对象,默认RGB\n d_wight, d_height = resize_image(img, cfg.max_predict_img_size)\n img = img.resize((d_wight, d_height), Image.NEAREST).convert('RGB')\n x = transforms.ToTensor()(img)\n x = torch.unsqueeze(x, 0) # 增加一个维度\n y = east_detect(x)\n y = torch.squeeze(y, 0) # 减少一个维度\n print(y.shape)\n y = y.detach().numpy() # 7*64*64\n if y.shape[0] == 7:\n y = y.transpose((1, 2, 0)) # CHW->HWC\n y[:, :, :3] = sigmoid(y[:, :, :3])\n cond = np.greater_equal(y[:, :, 0], pixel_threshold)\n activation_pixels = np.where(cond)\n quad_scores, quad_after_nms = nms(y, activation_pixels)\n with Image.open(img_path) as im:\n im_array = np.array(im.convert('RGB')) # 图片转为numpy数组\n d_wight, d_height = resize_image(im, cfg.max_predict_img_size)\n scale_ratio_w = d_wight / im.width\n scale_ratio_h = d_height / im.height\n im = im.resize((d_wight, d_height), Image.NEAREST).convert('RGB')\n quad_im = im.copy()\n draw = ImageDraw.Draw(im)\n for i, j in zip(activation_pixels[0], activation_pixels[1]):\n px = (j + 0.5) * cfg.pixel_size\n py = (i + 0.5) * cfg.pixel_size\n line_width, line_color = 1, 'red'\n if y[i, j, 1] >= cfg.side_vertex_pixel_threshold:\n if y[i, j, 2] < cfg.trunc_threshold:\n line_width, line_color = 2, 'yellow'\n elif y[i, j, 2] >= 1 - cfg.trunc_threshold:\n line_width, line_color = 2, 'green'\n draw.line([(px - 0.5 * cfg.pixel_size, py - 0.5 * cfg.pixel_size),\n (px + 0.5 * cfg.pixel_size, py - 0.5 * cfg.pixel_size),\n (px + 0.5 * cfg.pixel_size, py + 0.5 * cfg.pixel_size),\n (px - 0.5 * cfg.pixel_size, py + 0.5 * cfg.pixel_size),\n (px - 0.5 * cfg.pixel_size, py - 0.5 * cfg.pixel_size)],\n width=line_width, fill=line_color)\n im.save(img_path + '_act.jpg')\n quad_draw = ImageDraw.Draw(quad_im)\n txt_items = []\n for score, geo, s in zip(quad_scores, quad_after_nms,\n range(len(quad_scores))):\n if np.amin(score) > 0:\n quad_draw.line([tuple(geo[0]),\n tuple(geo[1]),\n tuple(geo[2]),\n tuple(geo[3]),\n tuple(geo[0])], width=2, fill='red')\n if cfg.predict_cut_text_line:\n cut_text_line(geo, scale_ratio_w, scale_ratio_h, im_array,\n img_path, s)\n rescaled_geo = geo / [scale_ratio_w, scale_ratio_h] # (N, 4, 2)标签坐标\n rescaled_geo_list = np.reshape(rescaled_geo, (8,)).tolist()\n txt_item = ','.join(map(str, rescaled_geo_list))\n txt_items.append(txt_item + '\\n')\n elif not quiet:\n print('quad invalid with vertex num less then 4.')\n quad_im.save(img_path + '_predict.jpg')\n if cfg.predict_write2txt and len(txt_items) > 0:\n with open(img_path[:-4] + '.txt', 'w') as f_txt:\n f_txt.writelines(txt_items)\n\n\ndef predict_txt(east_detect, img_path, txt_path, pixel_threshold, quiet=False):\n img = Image.open(img_path) # 为PIL图像对象,默认RGB\n d_wight, d_height = resize_image(img, cfg.max_predict_img_size)\n scale_ratio_w = d_wight / img.width\n scale_ratio_h = d_height / img.height\n transform = transforms.Compose([\n transforms.Resize((d_wight, d_height), interpolation=2),\n transforms.ToTensor()\n ])\n x = transform(img)\n x = torch.unsqueeze(x, 0) # 增加一个维度\n y = east_detect(x)\n y = torch.squeeze(y, 0) # 减少一个维度\n print(y.shape)\n y = y.detach().numpy() # 7*64*64\n if y.shape[0] == 7:\n y = y.transpose((1, 2, 0)) # CHW->HWC\n y[:, :, :3] = sigmoid(y[:, :, :3])\n cond = np.greater_equal(y[:, :, 0], pixel_threshold)\n activation_pixels = np.where(cond)\n quad_scores, quad_after_nms = nms(y, activation_pixels)\n\n txt_items = []\n for score, geo in zip(quad_scores, quad_after_nms):\n if np.amin(score) > 0:\n rescaled_geo = geo / [scale_ratio_w, scale_ratio_h]\n rescaled_geo_list = np.reshape(rescaled_geo, (8,)).tolist()\n txt_item = ','.join(map(str, rescaled_geo_list))\n txt_items.append(txt_item + '\\n')\n elif not quiet:\n print('quad invalid with vertex num less then 4.')\n if cfg.predict_write2txt and len(txt_items) > 0:\n with open(txt_path, 'w') as f_txt:\n f_txt.writelines(txt_items)\n\n\nif __name__ == '__main__':\n if not os.path.exists('demo'):\n os.makedirs('./demo', exist_ok=True)\n img_path = cfg.img_path\n threshold = float(cfg.predict_threshold)\n pth_path = cfg.pth_path if cfg.pth_path else 'saved_model/3T736_latest.pth'\n print(img_path, threshold)\n\n east = advancedEAST()\n state_dict = {k.replace('module.', ''): v for k, v in torch.load(pth_path, map_location='cpu').items()}\n east.load_state_dict(state_dict)\n predict(east, img_path, threshold)\n", "step-ids": [ 2, 4, 5, 6, 7 ] }
[ 2, 4, 5, 6, 7 ]
""" Convert file containing histograms into the response function """ import h5py import wx import numpy as np import matplotlib.pyplot as plt ############################################################################# # Select the file cantoning histograms, # which will be converted to response function app = wx.App () openFileDialog = wx.FileDialog (None, "Chose file containing histograms to get repose function", "", "", \ "HDF5 files (*.hdf5)|*.hdf5", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) # Check whether user canceled if openFileDialog.ShowModal() == wx.ID_CANCEL : raise ValueError("HDF5 file is not selected") hist_filename = openFileDialog.GetPath() del app ############################################################################# # Adding up all histograms with h5py.File(hist_filename, 'r') as F : for histogram in F["histograms"].values() : try : sum_histogram += histogram[...] except NameError : sum_histogram = histogram[...] # Loading resolution Resolution = F["parameters/Resolution"][...] ############################################################################# # Remove zeros cut_off = np.nonzero(sum_histogram)[0].max() sum_histogram = sum_histogram[:cut_off] ############################################################################# # Normalize to max 1 sum_histogram = sum_histogram.astype(np.float) sum_histogram /= sum_histogram.max() # Delete the background sum_histogram[ np.nonzero(sum_histogram < 0.03) ] = 0 ############################################################################# # plot plt.plot( 1e-3*Resolution*np.arange(sum_histogram.size), sum_histogram ) plt.title ("Total histogram with resolution %d ps" % Resolution ) plt.xlabel("time (ns)") plt.ylabel("counts") plt.show() # Save sum_histogram.tofile("response_function_%dps.dat" % Resolution)
normal
{ "blob_id": "c4898f3298c2febed476f99fe08bc5386527a47e", "index": 9344, "step-1": "<mask token>\n", "step-2": "<mask token>\nif openFileDialog.ShowModal() == wx.ID_CANCEL:\n raise ValueError('HDF5 file is not selected')\n<mask token>\ndel app\nwith h5py.File(hist_filename, 'r') as F:\n for histogram in F['histograms'].values():\n try:\n sum_histogram += histogram[...]\n except NameError:\n sum_histogram = histogram[...]\n Resolution = F['parameters/Resolution'][...]\n<mask token>\nsum_histogram /= sum_histogram.max()\n<mask token>\nplt.plot(0.001 * Resolution * np.arange(sum_histogram.size), sum_histogram)\nplt.title('Total histogram with resolution %d ps' % Resolution)\nplt.xlabel('time (ns)')\nplt.ylabel('counts')\nplt.show()\nsum_histogram.tofile('response_function_%dps.dat' % Resolution)\n", "step-3": "<mask token>\napp = wx.App()\nopenFileDialog = wx.FileDialog(None,\n 'Chose file containing histograms to get repose function', '', '',\n 'HDF5 files (*.hdf5)|*.hdf5', wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)\nif openFileDialog.ShowModal() == wx.ID_CANCEL:\n raise ValueError('HDF5 file is not selected')\nhist_filename = openFileDialog.GetPath()\ndel app\nwith h5py.File(hist_filename, 'r') as F:\n for histogram in F['histograms'].values():\n try:\n sum_histogram += histogram[...]\n except NameError:\n sum_histogram = histogram[...]\n Resolution = F['parameters/Resolution'][...]\ncut_off = np.nonzero(sum_histogram)[0].max()\nsum_histogram = sum_histogram[:cut_off]\nsum_histogram = sum_histogram.astype(np.float)\nsum_histogram /= sum_histogram.max()\nsum_histogram[np.nonzero(sum_histogram < 0.03)] = 0\nplt.plot(0.001 * Resolution * np.arange(sum_histogram.size), sum_histogram)\nplt.title('Total histogram with resolution %d ps' % Resolution)\nplt.xlabel('time (ns)')\nplt.ylabel('counts')\nplt.show()\nsum_histogram.tofile('response_function_%dps.dat' % Resolution)\n", "step-4": "<mask token>\nimport h5py\nimport wx\nimport numpy as np\nimport matplotlib.pyplot as plt\napp = wx.App()\nopenFileDialog = wx.FileDialog(None,\n 'Chose file containing histograms to get repose function', '', '',\n 'HDF5 files (*.hdf5)|*.hdf5', wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)\nif openFileDialog.ShowModal() == wx.ID_CANCEL:\n raise ValueError('HDF5 file is not selected')\nhist_filename = openFileDialog.GetPath()\ndel app\nwith h5py.File(hist_filename, 'r') as F:\n for histogram in F['histograms'].values():\n try:\n sum_histogram += histogram[...]\n except NameError:\n sum_histogram = histogram[...]\n Resolution = F['parameters/Resolution'][...]\ncut_off = np.nonzero(sum_histogram)[0].max()\nsum_histogram = sum_histogram[:cut_off]\nsum_histogram = sum_histogram.astype(np.float)\nsum_histogram /= sum_histogram.max()\nsum_histogram[np.nonzero(sum_histogram < 0.03)] = 0\nplt.plot(0.001 * Resolution * np.arange(sum_histogram.size), sum_histogram)\nplt.title('Total histogram with resolution %d ps' % Resolution)\nplt.xlabel('time (ns)')\nplt.ylabel('counts')\nplt.show()\nsum_histogram.tofile('response_function_%dps.dat' % Resolution)\n", "step-5": "\"\"\"\nConvert file containing histograms into the response function\n\"\"\"\nimport h5py\nimport wx\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#############################################################################\n# Select the file cantoning histograms, \n# which will be converted to response function\napp = wx.App ()\nopenFileDialog = wx.FileDialog (None, \"Chose file containing histograms to get repose function\", \"\", \"\", \\\n\t\t\"HDF5 files (*.hdf5)|*.hdf5\", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)\n\n# Check whether user canceled\nif openFileDialog.ShowModal() == wx.ID_CANCEL : \n\traise ValueError(\"HDF5 file is not selected\")\n\t\nhist_filename = openFileDialog.GetPath()\n\ndel app\n#############################################################################\n\n# Adding up all histograms\nwith h5py.File(hist_filename, 'r') as F :\n\tfor histogram in F[\"histograms\"].values() :\n\t\ttry :\n\t\t\tsum_histogram += histogram[...]\n\t\texcept NameError :\n\t\t\tsum_histogram = histogram[...]\n\n\t# Loading resolution\n\tResolution = F[\"parameters/Resolution\"][...]\n\t\n#############################################################################\n# Remove zeros \ncut_off = np.nonzero(sum_histogram)[0].max()\nsum_histogram = sum_histogram[:cut_off]\n\n#############################################################################\n# Normalize to max 1\nsum_histogram = sum_histogram.astype(np.float) \nsum_histogram /= sum_histogram.max()\n\n# Delete the background\nsum_histogram[ np.nonzero(sum_histogram < 0.03) ] = 0\n\n#############################################################################\n# plot\nplt.plot( 1e-3*Resolution*np.arange(sum_histogram.size), sum_histogram )\nplt.title (\"Total histogram with resolution %d ps\" % Resolution )\nplt.xlabel(\"time (ns)\")\nplt.ylabel(\"counts\")\nplt.show()\n\n# Save\nsum_histogram.tofile(\"response_function_%dps.dat\" % Resolution)\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import unittest ''' 시험 문제 2) 장식자 구현하기 - 다수의 인자를 받아, 2개의 인자로 변환하여 함수를 호출토록 구현 - 첫번째 인자 : 홀수의 합 - 두번째 인자 : 짝수의 합 모든 테스트가 통과하면, 다음과 같이 출력됩니다. 쉘> python final_2.py ... ---------------------------------------------------------------------- Ran 3 tests in 0.000s OK ''' def divider(fn): def wrap(*args): odd = sum(i for i in args if i%2!=0) even = sum(i for i in args if i%2==0) return fn(odd, even) return wrap ######################################## # # 아래는 수정하지마세요. # ######################################## @divider def mysum(x, y): return x + y @divider def mymultiply(x, y): return x * y @divider def mypow(x, y): return x ** y class TestFinalExam(unittest.TestCase): def k__test_mysum(self): self.assertEqual(mysum(1, 2), 3) self.assertEqual(mysum(1, 2, 3), 6) self.assertEqual(mysum(1, 2, 3, 4), 10) self.assertEqual(mysum(1, 2, 3, 4, 5), 15) self.assertEqual(mysum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 55) self.assertEqual(mysum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, 1001), 1156) def test_mymultiply(self): # self.assertEqual(mymultiply(1, 2), 2) # 1 * 2 # self.assertEqual(mymultiply(1, 2, 3), 8) # (1+3) * 2 # self.assertEqual(mymultiply(1, 2, 3, 4), 24) # (1+3) * (2+4) # self.assertEqual(mymultiply(1, 2, 3, 4, 5), 54) # (1+3+5) * (2+4) # self.assertEqual(mymultiply(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 750) self.assertEqual(mymultiply(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, 1001), 133380) # (1 + 3 + 5 + 7 + 8 + 9) * (2 + 4 + 6 + 8 + 10 + 100 + 1001) def test_mypow(self): # self.assertEqual(mypow(1, 2), 1) # 1 ** 2 # self.assertEqual(mypow(1, 2, 3), 16) # (1+3) ** 2 # self.assertEqual(mypow(1, 2, 3, 4), 4096) # (1+3) ** (2+4) # self.assertEqual(mypow(1, 2, 3, 4, 5), 531441) # (1+3+5) ** (2+4) # self.assertEqual(mypow(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 867361737988403547205962240695953369140625) pass if __name__ == '__main__': unittest.main()
normal
{ "blob_id": "253804644e366382a730775402768bc307944a19", "index": 6548, "step-1": "<mask token>\n\n\ndef divider(fn):\n\n def wrap(*args):\n odd = sum(i for i in args if i % 2 != 0)\n even = sum(i for i in args if i % 2 == 0)\n return fn(odd, even)\n return wrap\n\n\n@divider\ndef mysum(x, y):\n return x + y\n\n\n<mask token>\n\n\n@divider\ndef mypow(x, y):\n return x ** y\n\n\nclass TestFinalExam(unittest.TestCase):\n\n def k__test_mysum(self):\n self.assertEqual(mysum(1, 2), 3)\n self.assertEqual(mysum(1, 2, 3), 6)\n self.assertEqual(mysum(1, 2, 3, 4), 10)\n self.assertEqual(mysum(1, 2, 3, 4, 5), 15)\n self.assertEqual(mysum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 55)\n self.assertEqual(mysum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, 1001), 1156)\n\n def test_mymultiply(self):\n self.assertEqual(mymultiply(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, \n 1001), 133380)\n\n def test_mypow(self):\n pass\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef divider(fn):\n\n def wrap(*args):\n odd = sum(i for i in args if i % 2 != 0)\n even = sum(i for i in args if i % 2 == 0)\n return fn(odd, even)\n return wrap\n\n\n@divider\ndef mysum(x, y):\n return x + y\n\n\n@divider\ndef mymultiply(x, y):\n return x * y\n\n\n@divider\ndef mypow(x, y):\n return x ** y\n\n\nclass TestFinalExam(unittest.TestCase):\n\n def k__test_mysum(self):\n self.assertEqual(mysum(1, 2), 3)\n self.assertEqual(mysum(1, 2, 3), 6)\n self.assertEqual(mysum(1, 2, 3, 4), 10)\n self.assertEqual(mysum(1, 2, 3, 4, 5), 15)\n self.assertEqual(mysum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 55)\n self.assertEqual(mysum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, 1001), 1156)\n\n def test_mymultiply(self):\n self.assertEqual(mymultiply(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, \n 1001), 133380)\n\n def test_mypow(self):\n pass\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef divider(fn):\n\n def wrap(*args):\n odd = sum(i for i in args if i % 2 != 0)\n even = sum(i for i in args if i % 2 == 0)\n return fn(odd, even)\n return wrap\n\n\n@divider\ndef mysum(x, y):\n return x + y\n\n\n@divider\ndef mymultiply(x, y):\n return x * y\n\n\n@divider\ndef mypow(x, y):\n return x ** y\n\n\nclass TestFinalExam(unittest.TestCase):\n\n def k__test_mysum(self):\n self.assertEqual(mysum(1, 2), 3)\n self.assertEqual(mysum(1, 2, 3), 6)\n self.assertEqual(mysum(1, 2, 3, 4), 10)\n self.assertEqual(mysum(1, 2, 3, 4, 5), 15)\n self.assertEqual(mysum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 55)\n self.assertEqual(mysum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, 1001), 1156)\n\n def test_mymultiply(self):\n self.assertEqual(mymultiply(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, \n 1001), 133380)\n\n def test_mypow(self):\n pass\n\n\nif __name__ == '__main__':\n unittest.main()\n", "step-4": "import unittest\n<mask token>\n\n\ndef divider(fn):\n\n def wrap(*args):\n odd = sum(i for i in args if i % 2 != 0)\n even = sum(i for i in args if i % 2 == 0)\n return fn(odd, even)\n return wrap\n\n\n@divider\ndef mysum(x, y):\n return x + y\n\n\n@divider\ndef mymultiply(x, y):\n return x * y\n\n\n@divider\ndef mypow(x, y):\n return x ** y\n\n\nclass TestFinalExam(unittest.TestCase):\n\n def k__test_mysum(self):\n self.assertEqual(mysum(1, 2), 3)\n self.assertEqual(mysum(1, 2, 3), 6)\n self.assertEqual(mysum(1, 2, 3, 4), 10)\n self.assertEqual(mysum(1, 2, 3, 4, 5), 15)\n self.assertEqual(mysum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 55)\n self.assertEqual(mysum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, 1001), 1156)\n\n def test_mymultiply(self):\n self.assertEqual(mymultiply(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, \n 1001), 133380)\n\n def test_mypow(self):\n pass\n\n\nif __name__ == '__main__':\n unittest.main()\n", "step-5": "import unittest\n\n\n'''\n시험 문제 2) 장식자 구현하기\n\n- 다수의 인자를 받아, 2개의 인자로 변환하여 함수를 호출토록 구현\n- 첫번째 인자 : 홀수의 합\n- 두번째 인자 : 짝수의 합\n\n모든 테스트가 통과하면, 다음과 같이 출력됩니다.\n\n\n쉘> python final_2.py\n...\n----------------------------------------------------------------------\nRan 3 tests in 0.000s\n\nOK\n'''\n\n\ndef divider(fn):\n def wrap(*args):\n odd = sum(i for i in args if i%2!=0)\n even = sum(i for i in args if i%2==0)\n return fn(odd, even)\n return wrap\n\n\n########################################\n#\n# 아래는 수정하지마세요.\n#\n########################################\n\n@divider\ndef mysum(x, y):\n return x + y\n\n\n@divider\ndef mymultiply(x, y):\n return x * y\n\n\n@divider\ndef mypow(x, y):\n return x ** y\n\n\nclass TestFinalExam(unittest.TestCase):\n def k__test_mysum(self):\n self.assertEqual(mysum(1, 2), 3)\n self.assertEqual(mysum(1, 2, 3), 6)\n self.assertEqual(mysum(1, 2, 3, 4), 10)\n self.assertEqual(mysum(1, 2, 3, 4, 5), 15)\n self.assertEqual(mysum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 55)\n self.assertEqual(mysum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, 1001), 1156)\n\n def test_mymultiply(self):\n # self.assertEqual(mymultiply(1, 2), 2) # 1 * 2\n # self.assertEqual(mymultiply(1, 2, 3), 8) # (1+3) * 2\n # self.assertEqual(mymultiply(1, 2, 3, 4), 24) # (1+3) * (2+4)\n # self.assertEqual(mymultiply(1, 2, 3, 4, 5), 54) # (1+3+5) * (2+4)\n # self.assertEqual(mymultiply(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 750)\n self.assertEqual(mymultiply(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100, 1001), 133380)\n\n # (1 + 3 + 5 + 7 + 8 + 9) * (2 + 4 + 6 + 8 + 10 + 100 + 1001)\n\n def test_mypow(self):\n # self.assertEqual(mypow(1, 2), 1) # 1 ** 2\n # self.assertEqual(mypow(1, 2, 3), 16) # (1+3) ** 2\n # self.assertEqual(mypow(1, 2, 3, 4), 4096) # (1+3) ** (2+4)\n # self.assertEqual(mypow(1, 2, 3, 4, 5), 531441) # (1+3+5) ** (2+4)\n # self.assertEqual(mypow(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), 867361737988403547205962240695953369140625)\n pass\n\n\nif __name__ == '__main__':\n unittest.main()\n\n", "step-ids": [ 7, 8, 9, 10, 11 ] }
[ 7, 8, 9, 10, 11 ]
from flask_sqlalchemy import SQLAlchemy from sqlalchemy import func from extensions import bcrypt db = SQLAlchemy() class User(db.Model): id = db.Column(db.Integer(), primary_key=True) username = db.Column(db.String(255)) password = db.Column(db.String(255)) posts = db.relationship('Post', backref='user', lazy='dynamic') def __init__(self, username): self.username = username def set_password(self, password): self.password = bcrypt.generate_password_hash(password) def check_password(self, password): return bcrypt.check_password_hash(self.password, password) def __repr__(self): return '<User ' + self.username + '>' tags = db.Table('post_tags', db.Column('post_id', db.Integer(), db. ForeignKey('post.id')), db.Column('tag_id', db.Integer, db.ForeignKey( 'tag.id'))) class Post(db.Model): id = db.Column(db.Integer(), primary_key=True) title = db.Column(db.String(255)) text = db.Column(db.Text()) date = db.Column(db.DateTime()) user_id = db.Column(db.Integer(), db.ForeignKey('user.id')) comments = db.relationship('Comment', backref='post', lazy='dynamic') tags = db.relationship('Tag', secondary=tags, backref=db.backref( 'posts', lazy='dynamic')) def __init__(self, title): self.title = title def __repr__(self): return '<Post ' + self.title + '>' class Comment(db.Model): id = db.Column(db.Integer(), primary_key=True) title = db.Column(db.String(255)) text = db.Column(db.Text()) date = db.Column(db.DateTime()) post_id = db.Column(db.Integer(), db.ForeignKey('post.id')) def __init__(self, title): self.title = title def __repr__(self): return '<Comment ' + self.title + '>' class Tag(db.Model): id = db.Column(db.Integer(), primary_key=True) title = db.Column(db.String(255)) def __init__(self, title): self.title = title def __repr__(self): return '<Tag ' + self.title + '>' def sidebar_data(): recent = Post.query.order_by(Post.date.desc()).limit(5).all() top_tags = db.session.query(Tag, func.count(tags.c.post_id).label('total') ).join(tags).group_by(Tag).order_by('total DESC').limit(5).all() return recent, top_tags
normal
{ "blob_id": "dd0e96a1f93cbffedc11262a883dda285f5c224c", "index": 9703, "step-1": "<mask token>\n\n\nclass Post(db.Model):\n id = db.Column(db.Integer(), primary_key=True)\n title = db.Column(db.String(255))\n text = db.Column(db.Text())\n date = db.Column(db.DateTime())\n user_id = db.Column(db.Integer(), db.ForeignKey('user.id'))\n comments = db.relationship('Comment', backref='post', lazy='dynamic')\n tags = db.relationship('Tag', secondary=tags, backref=db.backref(\n 'posts', lazy='dynamic'))\n\n def __init__(self, title):\n self.title = title\n\n def __repr__(self):\n return '<Post ' + self.title + '>'\n\n\nclass Comment(db.Model):\n id = db.Column(db.Integer(), primary_key=True)\n title = db.Column(db.String(255))\n text = db.Column(db.Text())\n date = db.Column(db.DateTime())\n post_id = db.Column(db.Integer(), db.ForeignKey('post.id'))\n\n def __init__(self, title):\n self.title = title\n\n def __repr__(self):\n return '<Comment ' + self.title + '>'\n\n\nclass Tag(db.Model):\n id = db.Column(db.Integer(), primary_key=True)\n title = db.Column(db.String(255))\n\n def __init__(self, title):\n self.title = title\n\n def __repr__(self):\n return '<Tag ' + self.title + '>'\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass User(db.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, username):\n self.username = username\n\n def set_password(self, password):\n self.password = bcrypt.generate_password_hash(password)\n\n def check_password(self, password):\n return bcrypt.check_password_hash(self.password, password)\n\n def __repr__(self):\n return '<User ' + self.username + '>'\n\n\n<mask token>\n\n\nclass Post(db.Model):\n id = db.Column(db.Integer(), primary_key=True)\n title = db.Column(db.String(255))\n text = db.Column(db.Text())\n date = db.Column(db.DateTime())\n user_id = db.Column(db.Integer(), db.ForeignKey('user.id'))\n comments = db.relationship('Comment', backref='post', lazy='dynamic')\n tags = db.relationship('Tag', secondary=tags, backref=db.backref(\n 'posts', lazy='dynamic'))\n\n def __init__(self, title):\n self.title = title\n\n def __repr__(self):\n return '<Post ' + self.title + '>'\n\n\nclass Comment(db.Model):\n id = db.Column(db.Integer(), primary_key=True)\n title = db.Column(db.String(255))\n text = db.Column(db.Text())\n date = db.Column(db.DateTime())\n post_id = db.Column(db.Integer(), db.ForeignKey('post.id'))\n\n def __init__(self, title):\n self.title = title\n\n def __repr__(self):\n return '<Comment ' + self.title + '>'\n\n\nclass Tag(db.Model):\n id = db.Column(db.Integer(), primary_key=True)\n title = db.Column(db.String(255))\n\n def __init__(self, title):\n self.title = title\n\n def __repr__(self):\n return '<Tag ' + self.title + '>'\n\n\n<mask token>\n", "step-3": "<mask token>\ndb = SQLAlchemy()\n\n\nclass User(db.Model):\n id = db.Column(db.Integer(), primary_key=True)\n username = db.Column(db.String(255))\n password = db.Column(db.String(255))\n posts = db.relationship('Post', backref='user', lazy='dynamic')\n\n def __init__(self, username):\n self.username = username\n\n def set_password(self, password):\n self.password = bcrypt.generate_password_hash(password)\n\n def check_password(self, password):\n return bcrypt.check_password_hash(self.password, password)\n\n def __repr__(self):\n return '<User ' + self.username + '>'\n\n\ntags = db.Table('post_tags', db.Column('post_id', db.Integer(), db.\n ForeignKey('post.id')), db.Column('tag_id', db.Integer, db.ForeignKey(\n 'tag.id')))\n\n\nclass Post(db.Model):\n id = db.Column(db.Integer(), primary_key=True)\n title = db.Column(db.String(255))\n text = db.Column(db.Text())\n date = db.Column(db.DateTime())\n user_id = db.Column(db.Integer(), db.ForeignKey('user.id'))\n comments = db.relationship('Comment', backref='post', lazy='dynamic')\n tags = db.relationship('Tag', secondary=tags, backref=db.backref(\n 'posts', lazy='dynamic'))\n\n def __init__(self, title):\n self.title = title\n\n def __repr__(self):\n return '<Post ' + self.title + '>'\n\n\nclass Comment(db.Model):\n id = db.Column(db.Integer(), primary_key=True)\n title = db.Column(db.String(255))\n text = db.Column(db.Text())\n date = db.Column(db.DateTime())\n post_id = db.Column(db.Integer(), db.ForeignKey('post.id'))\n\n def __init__(self, title):\n self.title = title\n\n def __repr__(self):\n return '<Comment ' + self.title + '>'\n\n\nclass Tag(db.Model):\n id = db.Column(db.Integer(), primary_key=True)\n title = db.Column(db.String(255))\n\n def __init__(self, title):\n self.title = title\n\n def __repr__(self):\n return '<Tag ' + self.title + '>'\n\n\ndef sidebar_data():\n recent = Post.query.order_by(Post.date.desc()).limit(5).all()\n top_tags = db.session.query(Tag, func.count(tags.c.post_id).label('total')\n ).join(tags).group_by(Tag).order_by('total DESC').limit(5).all()\n return recent, top_tags\n", "step-4": "from flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import func\nfrom extensions import bcrypt\ndb = SQLAlchemy()\n\n\nclass User(db.Model):\n id = db.Column(db.Integer(), primary_key=True)\n username = db.Column(db.String(255))\n password = db.Column(db.String(255))\n posts = db.relationship('Post', backref='user', lazy='dynamic')\n\n def __init__(self, username):\n self.username = username\n\n def set_password(self, password):\n self.password = bcrypt.generate_password_hash(password)\n\n def check_password(self, password):\n return bcrypt.check_password_hash(self.password, password)\n\n def __repr__(self):\n return '<User ' + self.username + '>'\n\n\ntags = db.Table('post_tags', db.Column('post_id', db.Integer(), db.\n ForeignKey('post.id')), db.Column('tag_id', db.Integer, db.ForeignKey(\n 'tag.id')))\n\n\nclass Post(db.Model):\n id = db.Column(db.Integer(), primary_key=True)\n title = db.Column(db.String(255))\n text = db.Column(db.Text())\n date = db.Column(db.DateTime())\n user_id = db.Column(db.Integer(), db.ForeignKey('user.id'))\n comments = db.relationship('Comment', backref='post', lazy='dynamic')\n tags = db.relationship('Tag', secondary=tags, backref=db.backref(\n 'posts', lazy='dynamic'))\n\n def __init__(self, title):\n self.title = title\n\n def __repr__(self):\n return '<Post ' + self.title + '>'\n\n\nclass Comment(db.Model):\n id = db.Column(db.Integer(), primary_key=True)\n title = db.Column(db.String(255))\n text = db.Column(db.Text())\n date = db.Column(db.DateTime())\n post_id = db.Column(db.Integer(), db.ForeignKey('post.id'))\n\n def __init__(self, title):\n self.title = title\n\n def __repr__(self):\n return '<Comment ' + self.title + '>'\n\n\nclass Tag(db.Model):\n id = db.Column(db.Integer(), primary_key=True)\n title = db.Column(db.String(255))\n\n def __init__(self, title):\n self.title = title\n\n def __repr__(self):\n return '<Tag ' + self.title + '>'\n\n\ndef sidebar_data():\n recent = Post.query.order_by(Post.date.desc()).limit(5).all()\n top_tags = db.session.query(Tag, func.count(tags.c.post_id).label('total')\n ).join(tags).group_by(Tag).order_by('total DESC').limit(5).all()\n return recent, top_tags\n", "step-5": null, "step-ids": [ 12, 17, 20, 21 ] }
[ 12, 17, 20, 21 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def get_apriori_input(input_file, output_file, sample_col='Sample', gene_id_col='Gene_ID'): df = pd.read_csv(input_file, sep='\t') sample_names = df[sample_col].unique() with open(output_file, 'w') as out: csv_writer = csv.writer(out, delimiter='\t') for sample_name in sample_names: bool = df[sample_col] == sample_name df_sample = df[bool] gene_ids = df_sample[gene_id_col] gene_string = ','.join(gene_ids) csv_writer.writerow([sample_name, gene_string]) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def get_apriori_input(input_file, output_file, sample_col='Sample', gene_id_col='Gene_ID'): df = pd.read_csv(input_file, sep='\t') sample_names = df[sample_col].unique() with open(output_file, 'w') as out: csv_writer = csv.writer(out, delimiter='\t') for sample_name in sample_names: bool = df[sample_col] == sample_name df_sample = df[bool] gene_ids = df_sample[gene_id_col] gene_string = ','.join(gene_ids) csv_writer.writerow([sample_name, gene_string]) if __name__ == '__main__': import sys program, input_file, output_file, sample_col, gene_id_col = sys.argv get_apriori_input(input_file, output_file, sample_col, gene_id_col) <|reserved_special_token_1|> import pandas as pd import csv def get_apriori_input(input_file, output_file, sample_col='Sample', gene_id_col='Gene_ID'): df = pd.read_csv(input_file, sep='\t') sample_names = df[sample_col].unique() with open(output_file, 'w') as out: csv_writer = csv.writer(out, delimiter='\t') for sample_name in sample_names: bool = df[sample_col] == sample_name df_sample = df[bool] gene_ids = df_sample[gene_id_col] gene_string = ','.join(gene_ids) csv_writer.writerow([sample_name, gene_string]) if __name__ == '__main__': import sys program, input_file, output_file, sample_col, gene_id_col = sys.argv get_apriori_input(input_file, output_file, sample_col, gene_id_col) <|reserved_special_token_1|> #!/usr/bin/env python3 import pandas as pd import csv def get_apriori_input(input_file,output_file,sample_col="Sample",gene_id_col="Gene_ID"): df=pd.read_csv(input_file,sep="\t") sample_names=df[sample_col].unique() with open(output_file,"w") as out: csv_writer=csv.writer(out,delimiter="\t") for sample_name in sample_names: bool=df[sample_col]==sample_name df_sample=df[bool] gene_ids=df_sample[gene_id_col] gene_string=",".join(gene_ids) csv_writer.writerow([sample_name,gene_string]) if __name__ == "__main__": import sys program,input_file,output_file,sample_col,gene_id_col=sys.argv get_apriori_input(input_file,output_file,sample_col,gene_id_col)
flexible
{ "blob_id": "e14bea6376c8649bf9c9c5759d530af773664cd4", "index": 891, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef get_apriori_input(input_file, output_file, sample_col='Sample',\n gene_id_col='Gene_ID'):\n df = pd.read_csv(input_file, sep='\\t')\n sample_names = df[sample_col].unique()\n with open(output_file, 'w') as out:\n csv_writer = csv.writer(out, delimiter='\\t')\n for sample_name in sample_names:\n bool = df[sample_col] == sample_name\n df_sample = df[bool]\n gene_ids = df_sample[gene_id_col]\n gene_string = ','.join(gene_ids)\n csv_writer.writerow([sample_name, gene_string])\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef get_apriori_input(input_file, output_file, sample_col='Sample',\n gene_id_col='Gene_ID'):\n df = pd.read_csv(input_file, sep='\\t')\n sample_names = df[sample_col].unique()\n with open(output_file, 'w') as out:\n csv_writer = csv.writer(out, delimiter='\\t')\n for sample_name in sample_names:\n bool = df[sample_col] == sample_name\n df_sample = df[bool]\n gene_ids = df_sample[gene_id_col]\n gene_string = ','.join(gene_ids)\n csv_writer.writerow([sample_name, gene_string])\n\n\nif __name__ == '__main__':\n import sys\n program, input_file, output_file, sample_col, gene_id_col = sys.argv\n get_apriori_input(input_file, output_file, sample_col, gene_id_col)\n", "step-4": "import pandas as pd\nimport csv\n\n\ndef get_apriori_input(input_file, output_file, sample_col='Sample',\n gene_id_col='Gene_ID'):\n df = pd.read_csv(input_file, sep='\\t')\n sample_names = df[sample_col].unique()\n with open(output_file, 'w') as out:\n csv_writer = csv.writer(out, delimiter='\\t')\n for sample_name in sample_names:\n bool = df[sample_col] == sample_name\n df_sample = df[bool]\n gene_ids = df_sample[gene_id_col]\n gene_string = ','.join(gene_ids)\n csv_writer.writerow([sample_name, gene_string])\n\n\nif __name__ == '__main__':\n import sys\n program, input_file, output_file, sample_col, gene_id_col = sys.argv\n get_apriori_input(input_file, output_file, sample_col, gene_id_col)\n", "step-5": "#!/usr/bin/env python3\nimport pandas as pd\nimport csv\ndef get_apriori_input(input_file,output_file,sample_col=\"Sample\",gene_id_col=\"Gene_ID\"):\n df=pd.read_csv(input_file,sep=\"\\t\")\n sample_names=df[sample_col].unique()\n with open(output_file,\"w\") as out:\n csv_writer=csv.writer(out,delimiter=\"\\t\")\n for sample_name in sample_names:\n bool=df[sample_col]==sample_name\n df_sample=df[bool]\n gene_ids=df_sample[gene_id_col]\n gene_string=\",\".join(gene_ids)\n csv_writer.writerow([sample_name,gene_string])\n\n\nif __name__ == \"__main__\":\n import sys\n program,input_file,output_file,sample_col,gene_id_col=sys.argv\n get_apriori_input(input_file,output_file,sample_col,gene_id_col)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python # -*- coding: utf-8 -*- from trest.utils import utime from trest.logger import SysLogger from trest.config import settings from trest.exception import JsonError from applications.common.models.user import User class UserService(object): @staticmethod def page_list(where, page, per_page): """列表记录 Arguments: where dict -- 查询条件 page int -- 当前页 per_page int -- 每页记录数 return: Paginate 对象 | None """ query = User.Q if 'status' in where.keys(): query = query.filter(User.status == where['status']) else: query = query.filter(User.status != -1) pagelist_obj = query.paginate(page=page, per_page=per_page) return pagelist_obj @staticmethod def get(id): """获取单条记录 [description] Arguments: id int -- 主键 return: User Model 实例 | None """ if not id: raise JsonError('ID不能为空') obj = User.Q.filter(User.id == id).first() return obj @staticmethod def update(id, param): """更新记录 [description] Arguments: id int -- 主键 param dict -- [description] return: True | JsonError """ columns = [i for (i, _) in User.__table__.columns.items()] param = {k:v for k,v in param.items() if k in columns} if 'updated_at' in columns: param['updated_at'] = utime.timestamp(3) if not id: raise JsonError('ID 不能为空') try: User.Update.filter(User.id == id).update(param) User.session.commit() return True except Exception as e: User.session.rollback() SysLogger.error(e) raise JsonError('update error') @staticmethod def insert(param): """插入 [description] Arguments: id int -- 主键 param dict -- [description] return: True | JsonError """ columns = [i for (i, _) in User.__table__.columns.items()] param = {k:v for k,v in param.items() if k in columns} if 'created_at' in columns: param['created_at'] = utime.timestamp(3) try: obj = User(**param) User.session.add(obj) User.session.commit() return True except Exception as e: User.session.rollback() SysLogger.error(e) raise JsonError('insert error')
normal
{ "blob_id": "d1ed43bab6171c876b2ad9ef9db834ab8f9026d5", "index": 8411, "step-1": "<mask token>\n\n\nclass UserService(object):\n <mask token>\n\n @staticmethod\n def get(id):\n \"\"\"获取单条记录\n\n [description]\n\n Arguments:\n id int -- 主键\n\n return:\n User Model 实例 | None\n \"\"\"\n if not id:\n raise JsonError('ID不能为空')\n obj = User.Q.filter(User.id == id).first()\n return obj\n <mask token>\n\n @staticmethod\n def insert(param):\n \"\"\"插入\n\n [description]\n\n Arguments:\n id int -- 主键\n param dict -- [description]\n\n return:\n True | JsonError\n \"\"\"\n columns = [i for i, _ in User.__table__.columns.items()]\n param = {k: v for k, v in param.items() if k in columns}\n if 'created_at' in columns:\n param['created_at'] = utime.timestamp(3)\n try:\n obj = User(**param)\n User.session.add(obj)\n User.session.commit()\n return True\n except Exception as e:\n User.session.rollback()\n SysLogger.error(e)\n raise JsonError('insert error')\n", "step-2": "<mask token>\n\n\nclass UserService(object):\n <mask token>\n\n @staticmethod\n def get(id):\n \"\"\"获取单条记录\n\n [description]\n\n Arguments:\n id int -- 主键\n\n return:\n User Model 实例 | None\n \"\"\"\n if not id:\n raise JsonError('ID不能为空')\n obj = User.Q.filter(User.id == id).first()\n return obj\n\n @staticmethod\n def update(id, param):\n \"\"\"更新记录\n\n [description]\n\n Arguments:\n id int -- 主键\n param dict -- [description]\n\n return:\n True | JsonError\n \"\"\"\n columns = [i for i, _ in User.__table__.columns.items()]\n param = {k: v for k, v in param.items() if k in columns}\n if 'updated_at' in columns:\n param['updated_at'] = utime.timestamp(3)\n if not id:\n raise JsonError('ID 不能为空')\n try:\n User.Update.filter(User.id == id).update(param)\n User.session.commit()\n return True\n except Exception as e:\n User.session.rollback()\n SysLogger.error(e)\n raise JsonError('update error')\n\n @staticmethod\n def insert(param):\n \"\"\"插入\n\n [description]\n\n Arguments:\n id int -- 主键\n param dict -- [description]\n\n return:\n True | JsonError\n \"\"\"\n columns = [i for i, _ in User.__table__.columns.items()]\n param = {k: v for k, v in param.items() if k in columns}\n if 'created_at' in columns:\n param['created_at'] = utime.timestamp(3)\n try:\n obj = User(**param)\n User.session.add(obj)\n User.session.commit()\n return True\n except Exception as e:\n User.session.rollback()\n SysLogger.error(e)\n raise JsonError('insert error')\n", "step-3": "<mask token>\n\n\nclass UserService(object):\n\n @staticmethod\n def page_list(where, page, per_page):\n \"\"\"列表记录\n Arguments:\n where dict -- 查询条件\n page int -- 当前页\n per_page int -- 每页记录数\n\n return:\n Paginate 对象 | None\n \"\"\"\n query = User.Q\n if 'status' in where.keys():\n query = query.filter(User.status == where['status'])\n else:\n query = query.filter(User.status != -1)\n pagelist_obj = query.paginate(page=page, per_page=per_page)\n return pagelist_obj\n\n @staticmethod\n def get(id):\n \"\"\"获取单条记录\n\n [description]\n\n Arguments:\n id int -- 主键\n\n return:\n User Model 实例 | None\n \"\"\"\n if not id:\n raise JsonError('ID不能为空')\n obj = User.Q.filter(User.id == id).first()\n return obj\n\n @staticmethod\n def update(id, param):\n \"\"\"更新记录\n\n [description]\n\n Arguments:\n id int -- 主键\n param dict -- [description]\n\n return:\n True | JsonError\n \"\"\"\n columns = [i for i, _ in User.__table__.columns.items()]\n param = {k: v for k, v in param.items() if k in columns}\n if 'updated_at' in columns:\n param['updated_at'] = utime.timestamp(3)\n if not id:\n raise JsonError('ID 不能为空')\n try:\n User.Update.filter(User.id == id).update(param)\n User.session.commit()\n return True\n except Exception as e:\n User.session.rollback()\n SysLogger.error(e)\n raise JsonError('update error')\n\n @staticmethod\n def insert(param):\n \"\"\"插入\n\n [description]\n\n Arguments:\n id int -- 主键\n param dict -- [description]\n\n return:\n True | JsonError\n \"\"\"\n columns = [i for i, _ in User.__table__.columns.items()]\n param = {k: v for k, v in param.items() if k in columns}\n if 'created_at' in columns:\n param['created_at'] = utime.timestamp(3)\n try:\n obj = User(**param)\n User.session.add(obj)\n User.session.commit()\n return True\n except Exception as e:\n User.session.rollback()\n SysLogger.error(e)\n raise JsonError('insert error')\n", "step-4": "from trest.utils import utime\nfrom trest.logger import SysLogger\nfrom trest.config import settings\nfrom trest.exception import JsonError\nfrom applications.common.models.user import User\n\n\nclass UserService(object):\n\n @staticmethod\n def page_list(where, page, per_page):\n \"\"\"列表记录\n Arguments:\n where dict -- 查询条件\n page int -- 当前页\n per_page int -- 每页记录数\n\n return:\n Paginate 对象 | None\n \"\"\"\n query = User.Q\n if 'status' in where.keys():\n query = query.filter(User.status == where['status'])\n else:\n query = query.filter(User.status != -1)\n pagelist_obj = query.paginate(page=page, per_page=per_page)\n return pagelist_obj\n\n @staticmethod\n def get(id):\n \"\"\"获取单条记录\n\n [description]\n\n Arguments:\n id int -- 主键\n\n return:\n User Model 实例 | None\n \"\"\"\n if not id:\n raise JsonError('ID不能为空')\n obj = User.Q.filter(User.id == id).first()\n return obj\n\n @staticmethod\n def update(id, param):\n \"\"\"更新记录\n\n [description]\n\n Arguments:\n id int -- 主键\n param dict -- [description]\n\n return:\n True | JsonError\n \"\"\"\n columns = [i for i, _ in User.__table__.columns.items()]\n param = {k: v for k, v in param.items() if k in columns}\n if 'updated_at' in columns:\n param['updated_at'] = utime.timestamp(3)\n if not id:\n raise JsonError('ID 不能为空')\n try:\n User.Update.filter(User.id == id).update(param)\n User.session.commit()\n return True\n except Exception as e:\n User.session.rollback()\n SysLogger.error(e)\n raise JsonError('update error')\n\n @staticmethod\n def insert(param):\n \"\"\"插入\n\n [description]\n\n Arguments:\n id int -- 主键\n param dict -- [description]\n\n return:\n True | JsonError\n \"\"\"\n columns = [i for i, _ in User.__table__.columns.items()]\n param = {k: v for k, v in param.items() if k in columns}\n if 'created_at' in columns:\n param['created_at'] = utime.timestamp(3)\n try:\n obj = User(**param)\n User.session.add(obj)\n User.session.commit()\n return True\n except Exception as e:\n User.session.rollback()\n SysLogger.error(e)\n raise JsonError('insert error')\n", "step-5": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom trest.utils import utime\nfrom trest.logger import SysLogger\nfrom trest.config import settings\nfrom trest.exception import JsonError\nfrom applications.common.models.user import User\n\n\nclass UserService(object):\n @staticmethod\n def page_list(where, page, per_page):\n \"\"\"列表记录\n Arguments:\n where dict -- 查询条件\n page int -- 当前页\n per_page int -- 每页记录数\n\n return:\n Paginate 对象 | None\n \"\"\"\n query = User.Q\n\n if 'status' in where.keys():\n query = query.filter(User.status == where['status'])\n else:\n query = query.filter(User.status != -1)\n\n pagelist_obj = query.paginate(page=page, per_page=per_page)\n return pagelist_obj\n\n @staticmethod\n def get(id):\n \"\"\"获取单条记录\n\n [description]\n\n Arguments:\n id int -- 主键\n\n return:\n User Model 实例 | None\n \"\"\"\n if not id:\n raise JsonError('ID不能为空')\n obj = User.Q.filter(User.id == id).first()\n return obj\n\n @staticmethod\n def update(id, param):\n \"\"\"更新记录\n\n [description]\n\n Arguments:\n id int -- 主键\n param dict -- [description]\n\n return:\n True | JsonError\n \"\"\"\n columns = [i for (i, _) in User.__table__.columns.items()]\n param = {k:v for k,v in param.items() if k in columns}\n if 'updated_at' in columns:\n param['updated_at'] = utime.timestamp(3)\n\n if not id:\n raise JsonError('ID 不能为空')\n\n try:\n User.Update.filter(User.id == id).update(param)\n User.session.commit()\n return True\n except Exception as e:\n User.session.rollback()\n SysLogger.error(e)\n raise JsonError('update error')\n\n @staticmethod\n def insert(param):\n \"\"\"插入\n\n [description]\n\n Arguments:\n id int -- 主键\n param dict -- [description]\n\n return:\n True | JsonError\n \"\"\"\n columns = [i for (i, _) in User.__table__.columns.items()]\n param = {k:v for k,v in param.items() if k in columns}\n if 'created_at' in columns:\n param['created_at'] = utime.timestamp(3)\n try:\n obj = User(**param)\n User.session.add(obj)\n User.session.commit()\n return True\n except Exception as e:\n User.session.rollback()\n SysLogger.error(e)\n raise JsonError('insert error')\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
import pytest from dymopy.client import Dymo from dymopy.client import make_xml, make_params def test_url(): dymo = Dymo() assert dymo.uri == "https://127.0.0.1:41951/DYMO/DLS/Printing" def test_status(): dymo = Dymo() status = dymo.get_status() assert isinstance(status, dict) assert status['status_code'] == 200 def test_printer_name(): dymo = Dymo() printer = dymo.get_printer() assert isinstance(printer, dict) assert printer['status_code'] == 200 def test_xml(): label_params = make_params() label_xml = make_xml("This is working?") def test_printer_job(): dymo = Dymo() label_params = make_params() label_xml = make_xml('Hello', 'World!') # print_resp = dymo.print(label_xml=label_xml, label_params=label_params) # assert print_resp.status_code == 200
normal
{ "blob_id": "766098753ec579e2d63893fcbd94e8819b46bc0b", "index": 6867, "step-1": "<mask token>\n\n\ndef test_url():\n dymo = Dymo()\n assert dymo.uri == 'https://127.0.0.1:41951/DYMO/DLS/Printing'\n\n\ndef test_status():\n dymo = Dymo()\n status = dymo.get_status()\n assert isinstance(status, dict)\n assert status['status_code'] == 200\n\n\n<mask token>\n\n\ndef test_printer_job():\n dymo = Dymo()\n label_params = make_params()\n label_xml = make_xml('Hello', 'World!')\n", "step-2": "<mask token>\n\n\ndef test_url():\n dymo = Dymo()\n assert dymo.uri == 'https://127.0.0.1:41951/DYMO/DLS/Printing'\n\n\ndef test_status():\n dymo = Dymo()\n status = dymo.get_status()\n assert isinstance(status, dict)\n assert status['status_code'] == 200\n\n\ndef test_printer_name():\n dymo = Dymo()\n printer = dymo.get_printer()\n assert isinstance(printer, dict)\n assert printer['status_code'] == 200\n\n\n<mask token>\n\n\ndef test_printer_job():\n dymo = Dymo()\n label_params = make_params()\n label_xml = make_xml('Hello', 'World!')\n", "step-3": "<mask token>\n\n\ndef test_url():\n dymo = Dymo()\n assert dymo.uri == 'https://127.0.0.1:41951/DYMO/DLS/Printing'\n\n\ndef test_status():\n dymo = Dymo()\n status = dymo.get_status()\n assert isinstance(status, dict)\n assert status['status_code'] == 200\n\n\ndef test_printer_name():\n dymo = Dymo()\n printer = dymo.get_printer()\n assert isinstance(printer, dict)\n assert printer['status_code'] == 200\n\n\ndef test_xml():\n label_params = make_params()\n label_xml = make_xml('This is working?')\n\n\ndef test_printer_job():\n dymo = Dymo()\n label_params = make_params()\n label_xml = make_xml('Hello', 'World!')\n", "step-4": "import pytest\nfrom dymopy.client import Dymo\nfrom dymopy.client import make_xml, make_params\n\n\ndef test_url():\n dymo = Dymo()\n assert dymo.uri == 'https://127.0.0.1:41951/DYMO/DLS/Printing'\n\n\ndef test_status():\n dymo = Dymo()\n status = dymo.get_status()\n assert isinstance(status, dict)\n assert status['status_code'] == 200\n\n\ndef test_printer_name():\n dymo = Dymo()\n printer = dymo.get_printer()\n assert isinstance(printer, dict)\n assert printer['status_code'] == 200\n\n\ndef test_xml():\n label_params = make_params()\n label_xml = make_xml('This is working?')\n\n\ndef test_printer_job():\n dymo = Dymo()\n label_params = make_params()\n label_xml = make_xml('Hello', 'World!')\n", "step-5": "import pytest \nfrom dymopy.client import Dymo\nfrom dymopy.client import make_xml, make_params \n\ndef test_url(): \n dymo = Dymo()\n assert dymo.uri == \"https://127.0.0.1:41951/DYMO/DLS/Printing\"\n\ndef test_status(): \n dymo = Dymo()\n status = dymo.get_status()\n assert isinstance(status, dict)\n assert status['status_code'] == 200\n\ndef test_printer_name(): \n dymo = Dymo()\n printer = dymo.get_printer()\n assert isinstance(printer, dict)\n assert printer['status_code'] == 200\n\ndef test_xml(): \n label_params = make_params()\n label_xml = make_xml(\"This is working?\")\n \n\ndef test_printer_job(): \n dymo = Dymo()\n label_params = make_params()\n label_xml = make_xml('Hello', 'World!')\n \n # print_resp = dymo.print(label_xml=label_xml, label_params=label_params)\n # assert print_resp.status_code == 200\n \n ", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
# -*- coding:utf-8 -*- # Author: 李泽军 # Date: 2020/1/27 3:31 PM # Project: flask-demo from flask import abort from flask_login import current_user from functools import wraps from simpledu.modes import User def role_required(role): ''' 带参数的装饰器,可以用它来保护一个路由处理函数智能被特定的用户访问 :param role: :return: ''' def decorator(func): @wraps(func) def wrapper(*args,**kwargs): if not current_user.is_authenticated or current_user.role < role: abort(404) return func(*args,**kwargs) return wrapper return decorator # 特定角色的装饰器 staff_required = role_required(User.ROLE_STAFF) admin_required = role_required(User.ROLE_ADMIN)
normal
{ "blob_id": "b3f6d255830bdb2b0afc99aab6e3715616ac4dec", "index": 4298, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef role_required(role):\n \"\"\"\n 带参数的装饰器,可以用它来保护一个路由处理函数智能被特定的用户访问\n :param role:\n :return:\n \"\"\"\n\n def decorator(func):\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n if not current_user.is_authenticated or current_user.role < role:\n abort(404)\n return func(*args, **kwargs)\n return wrapper\n return decorator\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef role_required(role):\n \"\"\"\n 带参数的装饰器,可以用它来保护一个路由处理函数智能被特定的用户访问\n :param role:\n :return:\n \"\"\"\n\n def decorator(func):\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n if not current_user.is_authenticated or current_user.role < role:\n abort(404)\n return func(*args, **kwargs)\n return wrapper\n return decorator\n\n\nstaff_required = role_required(User.ROLE_STAFF)\nadmin_required = role_required(User.ROLE_ADMIN)\n", "step-4": "from flask import abort\nfrom flask_login import current_user\nfrom functools import wraps\nfrom simpledu.modes import User\n\n\ndef role_required(role):\n \"\"\"\n 带参数的装饰器,可以用它来保护一个路由处理函数智能被特定的用户访问\n :param role:\n :return:\n \"\"\"\n\n def decorator(func):\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n if not current_user.is_authenticated or current_user.role < role:\n abort(404)\n return func(*args, **kwargs)\n return wrapper\n return decorator\n\n\nstaff_required = role_required(User.ROLE_STAFF)\nadmin_required = role_required(User.ROLE_ADMIN)\n", "step-5": "# -*- coding:utf-8 -*-\n# Author: 李泽军\n# Date: 2020/1/27 3:31 PM\n# Project: flask-demo\n\nfrom flask import abort\nfrom flask_login import current_user\nfrom functools import wraps\nfrom simpledu.modes import User\n\n\ndef role_required(role):\n '''\n 带参数的装饰器,可以用它来保护一个路由处理函数智能被特定的用户访问\n :param role:\n :return:\n '''\n\n def decorator(func):\n @wraps(func)\n def wrapper(*args,**kwargs):\n if not current_user.is_authenticated or current_user.role < role:\n abort(404)\n return func(*args,**kwargs)\n\n return wrapper\n return decorator\n\n# 特定角色的装饰器\nstaff_required = role_required(User.ROLE_STAFF)\nadmin_required = role_required(User.ROLE_ADMIN)\n\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Test(models.Model): <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Test(models.Model): word1 = models.CharField(max_length=50) word2 = models.CharField(max_length=50) word3 = models.CharField(max_length=50) answer = models.CharField(max_length=50) <|reserved_special_token_1|> from django.db import models from django.utils import timezone class Test(models.Model): word1 = models.CharField(max_length=50) word2 = models.CharField(max_length=50) word3 = models.CharField(max_length=50) answer = models.CharField(max_length=50) <|reserved_special_token_1|> from django.db import models from django.utils import timezone class Test(models.Model): word1 = models.CharField(max_length=50) word2 = models.CharField(max_length=50) word3 = models.CharField(max_length=50) answer = models.CharField(max_length=50) #def __str__(self): # return self.word1, self.word2, self.word3, self.answer
flexible
{ "blob_id": "2a1d31b2123c11af3fce571287d3dad00a9b0086", "index": 2820, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Test(models.Model):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Test(models.Model):\n word1 = models.CharField(max_length=50)\n word2 = models.CharField(max_length=50)\n word3 = models.CharField(max_length=50)\n answer = models.CharField(max_length=50)\n", "step-4": "from django.db import models\nfrom django.utils import timezone\n\n\nclass Test(models.Model):\n word1 = models.CharField(max_length=50)\n word2 = models.CharField(max_length=50)\n word3 = models.CharField(max_length=50)\n answer = models.CharField(max_length=50)\n", "step-5": "from django.db import models\nfrom django.utils import timezone\n\nclass Test(models.Model):\n word1 = models.CharField(max_length=50)\n word2 = models.CharField(max_length=50)\n word3 = models.CharField(max_length=50)\n answer = models.CharField(max_length=50)\n\n #def __str__(self):\n # return self.word1, self.word2, self.word3, self.answer", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import weakref from Qt import QtCore from Qt import QtGui from Qt.QtWidgets import QDoubleSpinBox from Qt.QtWidgets import QSpinBox from Qt.QtWidgets import QWidget from Qt.QtWidgets import QSpacerItem from Qt.QtWidgets import QPushButton from Qt.QtWidgets import QComboBox from Qt.QtWidgets import QLineEdit from Qt.QtWidgets import QCheckBox from Qt.QtWidgets import QGraphicsProxyWidget from Qt.QtWidgets import QGridLayout from Qt.QtWidgets import QHBoxLayout from Qt.QtWidgets import QSizePolicy from AGraphCommon import * from AbstractGraph import PinBase from ..Ui import FloatVector3InputWidget_ui from ..Ui import FloatVector4InputWidget_ui from ..Ui import Matrix33InputWidget_ui from ..Ui import Matrix44InputWidget_ui import pyrr def _configDoubleSpinBox(sb): sb.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX) sb.setSingleStep(FLOAT_SINGLE_STEP) sb.setDecimals(FLOAT_DECIMALS) def _configIntSpinBox(sb): sb.setRange(INT_RANGE_MIN, INT_RANGE_MAX) class InputWidgetRaw(QWidget): """ This type of widget can be used as a base class for complex ui generated by designer """ def __init__(self, parent=None, dataSetCallback=None, defaultValue=None, userStructClass=None, **kwds): super(InputWidgetRaw, self).__init__(parent=parent, **kwds) self._defaultValue = defaultValue # fuction with signature void(object) # this will set data to pin self.dataSetCallback = dataSetCallback def onResetValue(self): self.setWidgetValue(self._defaultValue) def setWidgetValue(self, value): '''to widget''' pass def widgetValueUpdated(self, value): '''from widget''' pass class InputWidgetSingle(InputWidgetRaw): """ This type of widget is used for a simple widgets like buttons, checkboxes etc. It consists of horizontal layout widget itself and reset button. """ def __init__(self, parent=None, dataSetCallback=None, defaultValue=None, userStructClass=None, **kwds): super(InputWidgetSingle, self).__init__(parent=parent, dataSetCallback=dataSetCallback, defaultValue=defaultValue, userStructClass=userStructClass, **kwds) # from widget self.bWidgetSet = False self.gridLayout = QGridLayout(self) self.gridLayout.setSpacing(1) self.gridLayout.setContentsMargins(0, 0, 0, 0) self.gridLayout.setObjectName("gridLayout") self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.pbReset = QPushButton(self) self.pbReset.setMaximumSize(QtCore.QSize(25, 25)) self.pbReset.setText("") self.pbReset.setObjectName("pbReset") self.pbReset.setIcon(QtGui.QIcon(":/icons/resources/reset.png")) self.horizontalLayout.addWidget(self.pbReset) self.pbReset.clicked.connect(self.onResetValue) self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1) self._index = 0 def setWidget(self, widget): self.horizontalLayout.insertWidget(self._index, widget) class ExecInputWidget(InputWidgetSingle): """docstring for ExecInputWidget""" def __init__(self, parent=None, **kwds): super(ExecInputWidget, self).__init__(parent=parent, **kwds) self.pb = QPushButton('execute', self) self.setWidget(self.pb) self.pb.clicked.connect(self.dataSetCallback) self.pbReset.deleteLater() def setObjectName(self,name): super(ExecInputWidget, self).setObjectName(name) self.pb.setText(name.split(".")[-1]) class EnumInputWidget(InputWidgetSingle): """ Enum input widget """ def __init__(self, parent=None, **kwds): super(EnumInputWidget, self).__init__(parent=parent, **kwds) # self._userStruct = kwds['userStructClass'] self.cb = QComboBox(self) self.setWidget(self.cb) for i in list(kwds['userStructClass']): self.cb.addItem(i.name, i.value) self.cb.currentIndexChanged[int].connect(self.dataSetCallback) def setWidgetValue(self, val): self.cb.setCurrentIndex(val) class FloatInputWidget(InputWidgetSingle): """ Floating point data input widget """ def __init__(self, parent=None, **kwds): super(FloatInputWidget, self).__init__(parent=parent, **kwds) self.sb = QDoubleSpinBox(self) _configDoubleSpinBox(self.sb) self.setWidget(self.sb) # when spin box updated call setter function self.sb.valueChanged.connect(lambda val: self.dataSetCallback(val)) def setWidgetValue(self, val): self.sb.setValue(float(val)) class IntInputWidget(InputWidgetSingle): """ Decimal number input widget """ def __init__(self, parent=None, **kwds): super(IntInputWidget, self).__init__(parent=parent, **kwds) self.sb = QSpinBox(self) _configIntSpinBox(self.sb) self.setWidget(self.sb) self.sb.valueChanged.connect(lambda val: self.dataSetCallback(val)) def setWidgetValue(self, val): self.sb.setValue(int(val)) class NoneInputWidget(InputWidgetSingle): """ String data input widget """ def __init__(self, parent=None, **kwds): super(NoneInputWidget, self).__init__(parent=parent, **kwds) self.le = QLineEdit(self) self.le.setContextMenuPolicy(QtCore.Qt.NoContextMenu) self.setWidget(self.le) self.le.textChanged.connect(lambda val: self.dataSetCallback(val)) self.le.setEnabled(False) def setWidgetValue(self, val): self.le.setText(str(val)) class StringInputWidget(InputWidgetSingle): """ String data input widget """ def __init__(self, parent=None, **kwds): super(StringInputWidget, self).__init__(parent=parent, **kwds) self.le = QLineEdit(self) self.le.setContextMenuPolicy(QtCore.Qt.NoContextMenu) self.setWidget(self.le) self.le.textChanged.connect(lambda val: self.dataSetCallback(val)) def setWidgetValue(self, val): self.le.setText(str(val)) class BoolInputWidget(InputWidgetSingle): """Boolean data input widget""" def __init__(self, parent=None, **kwds): super(BoolInputWidget, self).__init__(parent=parent, **kwds) self.cb = QCheckBox(self) self.setWidget(self.cb) self.cb.stateChanged.connect(lambda val: self.dataSetCallback(bool(val))) def setWidgetValue(self, val): if bool(val): self.cb.setCheckState(QtCore.Qt.Checked) else: self.cb.setCheckState(QtCore.Qt.Unchecked) class FloatVector3InputWidget(InputWidgetRaw, FloatVector3InputWidget_ui.Ui_Form): """Vector3 data input widget""" def __init__(self, **kwds): super(FloatVector3InputWidget, self).__init__(**kwds) self.setupUi(self) self._configSpinBoxes() self.dsbX.valueChanged.connect(self._onDataChangedX) self.dsbY.valueChanged.connect(self._onDataChangedY) self.dsbZ.valueChanged.connect(self._onDataChangedZ) self.pbReset.clicked.connect(self.onResetValue) def asDataTypeClass(self): return pyrr.Vector3([self.dsbX.value(), self.dsbY.value(), self.dsbZ.value()]) def _configSpinBoxes(self): self.dsbX.setDecimals(FLOAT_DECIMALS) self.dsbY.setDecimals(FLOAT_DECIMALS) self.dsbZ.setDecimals(FLOAT_DECIMALS) self.dsbX.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX) self.dsbY.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX) self.dsbZ.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX) self.dsbX.setSingleStep(FLOAT_SINGLE_STEP) self.dsbY.setSingleStep(FLOAT_SINGLE_STEP) self.dsbZ.setSingleStep(FLOAT_SINGLE_STEP) def _onDataChangedX(self, val): v = self.asDataTypeClass() v.x = val self.dataSetCallback(v) def _onDataChangedY(self, val): v = self.asDataTypeClass() v.y = val self.dataSetCallback(v) def _onDataChangedZ(self, val): v = self.asDataTypeClass() v.z = val self.dataSetCallback(v) def setWidgetValue(self, val): self.dsbX.setValue(val.x) self.dsbY.setValue(val.y) self.dsbZ.setValue(val.z) class FloatVector4InputWidget(InputWidgetRaw, FloatVector4InputWidget_ui.Ui_Form): """Vector4 data input widget""" def __init__(self, **kwds): super(FloatVector4InputWidget, self).__init__(**kwds) self.setupUi(self) self._configSpinBoxes() self.dsbX.valueChanged.connect(self._onDataChangedX) self.dsbY.valueChanged.connect(self._onDataChangedY) self.dsbZ.valueChanged.connect(self._onDataChangedZ) self.dsbW.valueChanged.connect(self._onDataChangedW) self.pbReset.clicked.connect(self.onResetValue) def asDataTypeClass(self): return pyrr.Vector4([self.dsbX.value(), self.dsbY.value(), self.dsbZ.value(), self.dsbW.value()]) def _configSpinBoxes(self): self.dsbX.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX) self.dsbY.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX) self.dsbZ.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX) self.dsbW.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX) self.dsbX.setSingleStep(FLOAT_SINGLE_STEP) self.dsbY.setSingleStep(FLOAT_SINGLE_STEP) self.dsbZ.setSingleStep(FLOAT_SINGLE_STEP) self.dsbW.setSingleStep(FLOAT_SINGLE_STEP) self.dsbX.setDecimals(FLOAT_DECIMALS) self.dsbY.setDecimals(FLOAT_DECIMALS) self.dsbZ.setDecimals(FLOAT_DECIMALS) self.dsbW.setDecimals(FLOAT_DECIMALS) def _onDataChangedX(self, val): v = self.asDataTypeClass() v.x = val self.dataSetCallback(v) def _onDataChangedY(self, val): v = self.asDataTypeClass() v.y = val self.dataSetCallback(v) def _onDataChangedZ(self, val): v = self.asDataTypeClass() v.z = val self.dataSetCallback(v) def _onDataChangedW(self, val): v = self.asDataTypeClass() v.w = val self.dataSetCallback(v) def setWidgetValue(self, val): self.dsbX.setValue(val.x) self.dsbY.setValue(val.y) self.dsbZ.setValue(val.z) self.dsbW.setValue(val.w) class QuatInputWidget(FloatVector4InputWidget): """Quaternion data input widget""" def __init__(self, **kwds): super(QuatInputWidget, self).__init__(**kwds) def asDataTypeClass(self): return pyrr.Quaternion([self.dsbX.value(), self.dsbY.value(), self.dsbZ.value(), self.dsbW.value()]) class Matrix33InputWidget(InputWidgetRaw, Matrix33InputWidget_ui.Ui_Form): """Matrix33 data input widget""" def __init__(self, parent=None, **kwds): super(Matrix33InputWidget, self).__init__(parent=parent, **kwds) self.setupUi(self) self._configSpinBoxes() self.dsbm11.valueChanged.connect(self.m11Changed) self.dsbm12.valueChanged.connect(self.m12Changed) self.dsbm13.valueChanged.connect(self.m13Changed) self.dsbm21.valueChanged.connect(self.m21Changed) self.dsbm22.valueChanged.connect(self.m22Changed) self.dsbm23.valueChanged.connect(self.m23Changed) self.dsbm31.valueChanged.connect(self.m31Changed) self.dsbm32.valueChanged.connect(self.m32Changed) self.dsbm33.valueChanged.connect(self.m33Changed) self.pbReset.clicked.connect(self.onResetValue) def asDataTypeClass(self): return pyrr.Matrix33([ [self.dsbm11.value(), self.dsbm12.value(), self.dsbm13.value()], [self.dsbm21.value(), self.dsbm22.value(), self.dsbm23.value()], [self.dsbm31.value(), self.dsbm32.value(), self.dsbm33.value()] ]) def _configSpinBoxes(self): ls = [self.dsbm11, self.dsbm12, self.dsbm13, self.dsbm21, self.dsbm22, self.dsbm23, self.dsbm31, self.dsbm32, self.dsbm33] for sb in ls: sb.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX) sb.setSingleStep(FLOAT_SINGLE_STEP) sb.setDecimals(FLOAT_DECIMALS) def m11Changed(self, val): m = self.asDataTypeClass() m.m11 = val self.dataSetCallback(m) def m12Changed(self, val): m = self.asDataTypeClass() m.m12 = val self.dataSetCallback(m) def m13Changed(self, val): m = self.asDataTypeClass() m.m13 = val self.dataSetCallback(m) def m21Changed(self, val): m = self.asDataTypeClass() m.m21 = val self.dataSetCallback(m) def m22Changed(self, val): m = self.asDataTypeClass() m.m22 = val self.dataSetCallback(m) def m23Changed(self, val): m = self.asDataTypeClass() m.m23 = val self.dataSetCallback(m) def m31Changed(self, val): m = self.asDataTypeClass() m.m31 = val self.dataSetCallback(m) def m32Changed(self, val): m = self.asDataTypeClass() m.m32 = val self.dataSetCallback(m) def m33Changed(self, val): m = self.asDataTypeClass() m.m33 = val self.dataSetCallback(m) def setWidgetValue(self, val): self.dsbm11.setValue(val.m11) self.dsbm12.setValue(val.m12) self.dsbm13.setValue(val.m13) self.dsbm21.setValue(val.m21) self.dsbm22.setValue(val.m22) self.dsbm23.setValue(val.m23) self.dsbm31.setValue(val.m31) self.dsbm32.setValue(val.m32) self.dsbm33.setValue(val.m33) class Matrix44InputWidget(InputWidgetRaw, Matrix44InputWidget_ui.Ui_Form): """Matrix44 data input widget""" def __init__(self, parent=None, **kwds): super(Matrix44InputWidget, self).__init__(parent=parent, **kwds) self.setupUi(self) self._configSpinBoxes() self.dsbm11.valueChanged.connect(self.m11Changed) self.dsbm12.valueChanged.connect(self.m12Changed) self.dsbm13.valueChanged.connect(self.m13Changed) self.dsbm14.valueChanged.connect(self.m14Changed) self.dsbm21.valueChanged.connect(self.m21Changed) self.dsbm22.valueChanged.connect(self.m22Changed) self.dsbm23.valueChanged.connect(self.m23Changed) self.dsbm24.valueChanged.connect(self.m24Changed) self.dsbm31.valueChanged.connect(self.m31Changed) self.dsbm32.valueChanged.connect(self.m32Changed) self.dsbm33.valueChanged.connect(self.m33Changed) self.dsbm34.valueChanged.connect(self.m34Changed) self.dsbm41.valueChanged.connect(self.m41Changed) self.dsbm42.valueChanged.connect(self.m42Changed) self.dsbm43.valueChanged.connect(self.m43Changed) self.dsbm44.valueChanged.connect(self.m44Changed) self.pbReset.clicked.connect(self.onResetValue) def asDataTypeClass(self): return pyrr.Matrix44([ [self.dsbm11.value(), self.dsbm12.value(), self.dsbm13.value(), self.dsbm14.value()], [self.dsbm21.value(), self.dsbm22.value(), self.dsbm23.value(), self.dsbm24.value()], [self.dsbm31.value(), self.dsbm32.value(), self.dsbm33.value(), self.dsbm34.value()], [self.dsbm41.value(), self.dsbm42.value(), self.dsbm43.value(), self.dsbm44.value()] ]) def _configSpinBoxes(self): ls = [self.dsbm11, self.dsbm12, self.dsbm13, self.dsbm14, self.dsbm21, self.dsbm22, self.dsbm23, self.dsbm24, self.dsbm31, self.dsbm32, self.dsbm33, self.dsbm34, self.dsbm41, self.dsbm42, self.dsbm43, self.dsbm44] for sb in ls: sb.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX) sb.setSingleStep(FLOAT_SINGLE_STEP) sb.setDecimals(FLOAT_DECIMALS) def m11Changed(self, val): m = self.asDataTypeClass() m.m11 = val self.dataSetCallback(m) def m12Changed(self, val): m = self.asDataTypeClass() m.m12 = val self.dataSetCallback(m) def m13Changed(self, val): m = self.asDataTypeClass() m.m13 = val self.dataSetCallback(m) def m14Changed(self, val): m = self.asDataTypeClass() m.m14 = val self.dataSetCallback(m) def m21Changed(self, val): m = self.asDataTypeClass() m.m21 = val self.dataSetCallback(m) def m22Changed(self, val): m = self.asDataTypeClass() m.m22 = val self.dataSetCallback(m) def m23Changed(self, val): m = self.asDataTypeClass() m.m23 = val self.dataSetCallback(m) def m24Changed(self, val): m = self.asDataTypeClass() m.m24 = val self.dataSetCallback(m) def m31Changed(self, val): m = self.asDataTypeClass() m.m31 = val self.dataSetCallback(m) def m32Changed(self, val): m = self.asDataTypeClass() m.m32 = val self.dataSetCallback(m) def m33Changed(self, val): m = self.asDataTypeClass() m.m33 = val self.dataSetCallback(m) def m34Changed(self, val): m = self.asDataTypeClass() m.m34 = val self.dataSetCallback(m) def m41Changed(self, val): m = self.asDataTypeClass() m.m41 = val self.dataSetCallback(m) def m42Changed(self, val): m = self.asDataTypeClass() m.m42 = val self.dataSetCallback(m) def m43Changed(self, val): m = self.asDataTypeClass() m.m43 = val self.dataSetCallback(m) def m44Changed(self, val): m = self.asDataTypeClass() m.m44 = val self.dataSetCallback(m) def setWidgetValue(self, val): self.dsbm11.setValue(val.m11) self.dsbm12.setValue(val.m12) self.dsbm13.setValue(val.m13) self.dsbm14.setValue(val.m14) self.dsbm21.setValue(val.m21) self.dsbm22.setValue(val.m22) self.dsbm23.setValue(val.m23) self.dsbm24.setValue(val.m24) self.dsbm31.setValue(val.m31) self.dsbm32.setValue(val.m32) self.dsbm33.setValue(val.m33) self.dsbm34.setValue(val.m34) self.dsbm41.setValue(val.m41) self.dsbm42.setValue(val.m42) self.dsbm43.setValue(val.m43) self.dsbm44.setValue(val.m44) def getInputWidget(dataType, dataSetter, defaultValue, userStructClass): ''' factory method ''' if dataType == DataTypes.Float: return FloatInputWidget(dataSetCallback=dataSetter, defaultValue=defaultValue) if dataType == DataTypes.Int: return IntInputWidget(dataSetCallback=dataSetter, defaultValue=defaultValue) if dataType == DataTypes.String: return StringInputWidget(dataSetCallback=dataSetter, defaultValue=defaultValue) if dataType == DataTypes.Bool: return BoolInputWidget(dataSetCallback=dataSetter, defaultValue=defaultValue) if dataType == DataTypes.FloatVector3: return FloatVector3InputWidget(dataSetCallback=dataSetter, defaultValue=defaultValue) if dataType == DataTypes.FloatVector4: return FloatVector4InputWidget(dataSetCallback=dataSetter, defaultValue=defaultValue) if dataType == DataTypes.Quaternion: return QuatInputWidget(dataSetCallback=dataSetter, defaultValue=defaultValue) if dataType == DataTypes.Matrix33: return Matrix33InputWidget(dataSetCallback=dataSetter, defaultValue=defaultValue) if dataType == DataTypes.Matrix44: return Matrix44InputWidget(dataSetCallback=dataSetter, defaultValue=defaultValue) if dataType == DataTypes.Exec: return ExecInputWidget(dataSetCallback=dataSetter, defaultValue=None) if dataType == DataTypes.Enum: return EnumInputWidget(dataSetCallback=dataSetter, defaultValue=defaultValue, userStructClass=userStructClass) return NoneInputWidget(dataSetCallback=dataSetter, defaultValue=defaultValue)
normal
{ "blob_id": "023dc23a5e649c2fbbb45ff577dffa3b5d2aac64", "index": 7904, "step-1": "<mask token>\n\n\nclass FloatVector3InputWidget(InputWidgetRaw, FloatVector3InputWidget_ui.\n Ui_Form):\n <mask token>\n\n def __init__(self, **kwds):\n super(FloatVector3InputWidget, self).__init__(**kwds)\n self.setupUi(self)\n self._configSpinBoxes()\n self.dsbX.valueChanged.connect(self._onDataChangedX)\n self.dsbY.valueChanged.connect(self._onDataChangedY)\n self.dsbZ.valueChanged.connect(self._onDataChangedZ)\n self.pbReset.clicked.connect(self.onResetValue)\n\n def asDataTypeClass(self):\n return pyrr.Vector3([self.dsbX.value(), self.dsbY.value(), self.\n dsbZ.value()])\n\n def _configSpinBoxes(self):\n self.dsbX.setDecimals(FLOAT_DECIMALS)\n self.dsbY.setDecimals(FLOAT_DECIMALS)\n self.dsbZ.setDecimals(FLOAT_DECIMALS)\n self.dsbX.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbY.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbZ.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbX.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbY.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbZ.setSingleStep(FLOAT_SINGLE_STEP)\n\n def _onDataChangedX(self, val):\n v = self.asDataTypeClass()\n v.x = val\n self.dataSetCallback(v)\n\n def _onDataChangedY(self, val):\n v = self.asDataTypeClass()\n v.y = val\n self.dataSetCallback(v)\n\n def _onDataChangedZ(self, val):\n v = self.asDataTypeClass()\n v.z = val\n self.dataSetCallback(v)\n\n def setWidgetValue(self, val):\n self.dsbX.setValue(val.x)\n self.dsbY.setValue(val.y)\n self.dsbZ.setValue(val.z)\n\n\nclass FloatVector4InputWidget(InputWidgetRaw, FloatVector4InputWidget_ui.\n Ui_Form):\n \"\"\"Vector4 data input widget\"\"\"\n\n def __init__(self, **kwds):\n super(FloatVector4InputWidget, self).__init__(**kwds)\n self.setupUi(self)\n self._configSpinBoxes()\n self.dsbX.valueChanged.connect(self._onDataChangedX)\n self.dsbY.valueChanged.connect(self._onDataChangedY)\n self.dsbZ.valueChanged.connect(self._onDataChangedZ)\n self.dsbW.valueChanged.connect(self._onDataChangedW)\n self.pbReset.clicked.connect(self.onResetValue)\n\n def asDataTypeClass(self):\n return pyrr.Vector4([self.dsbX.value(), self.dsbY.value(), self.\n dsbZ.value(), self.dsbW.value()])\n\n def _configSpinBoxes(self):\n self.dsbX.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbY.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbZ.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbW.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbX.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbY.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbZ.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbW.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbX.setDecimals(FLOAT_DECIMALS)\n self.dsbY.setDecimals(FLOAT_DECIMALS)\n self.dsbZ.setDecimals(FLOAT_DECIMALS)\n self.dsbW.setDecimals(FLOAT_DECIMALS)\n\n def _onDataChangedX(self, val):\n v = self.asDataTypeClass()\n v.x = val\n self.dataSetCallback(v)\n\n def _onDataChangedY(self, val):\n v = self.asDataTypeClass()\n v.y = val\n self.dataSetCallback(v)\n\n def _onDataChangedZ(self, val):\n v = self.asDataTypeClass()\n v.z = val\n self.dataSetCallback(v)\n\n def _onDataChangedW(self, val):\n v = self.asDataTypeClass()\n v.w = val\n self.dataSetCallback(v)\n\n def setWidgetValue(self, val):\n self.dsbX.setValue(val.x)\n self.dsbY.setValue(val.y)\n self.dsbZ.setValue(val.z)\n self.dsbW.setValue(val.w)\n\n\nclass QuatInputWidget(FloatVector4InputWidget):\n \"\"\"Quaternion data input widget\"\"\"\n\n def __init__(self, **kwds):\n super(QuatInputWidget, self).__init__(**kwds)\n\n def asDataTypeClass(self):\n return pyrr.Quaternion([self.dsbX.value(), self.dsbY.value(), self.\n dsbZ.value(), self.dsbW.value()])\n\n\nclass Matrix33InputWidget(InputWidgetRaw, Matrix33InputWidget_ui.Ui_Form):\n \"\"\"Matrix33 data input widget\"\"\"\n\n def __init__(self, parent=None, **kwds):\n super(Matrix33InputWidget, self).__init__(parent=parent, **kwds)\n self.setupUi(self)\n self._configSpinBoxes()\n self.dsbm11.valueChanged.connect(self.m11Changed)\n self.dsbm12.valueChanged.connect(self.m12Changed)\n self.dsbm13.valueChanged.connect(self.m13Changed)\n self.dsbm21.valueChanged.connect(self.m21Changed)\n self.dsbm22.valueChanged.connect(self.m22Changed)\n self.dsbm23.valueChanged.connect(self.m23Changed)\n self.dsbm31.valueChanged.connect(self.m31Changed)\n self.dsbm32.valueChanged.connect(self.m32Changed)\n self.dsbm33.valueChanged.connect(self.m33Changed)\n self.pbReset.clicked.connect(self.onResetValue)\n\n def asDataTypeClass(self):\n return pyrr.Matrix33([[self.dsbm11.value(), self.dsbm12.value(),\n self.dsbm13.value()], [self.dsbm21.value(), self.dsbm22.value(),\n self.dsbm23.value()], [self.dsbm31.value(), self.dsbm32.value(),\n self.dsbm33.value()]])\n\n def _configSpinBoxes(self):\n ls = [self.dsbm11, self.dsbm12, self.dsbm13, self.dsbm21, self.\n dsbm22, self.dsbm23, self.dsbm31, self.dsbm32, self.dsbm33]\n for sb in ls:\n sb.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n sb.setSingleStep(FLOAT_SINGLE_STEP)\n sb.setDecimals(FLOAT_DECIMALS)\n\n def m11Changed(self, val):\n m = self.asDataTypeClass()\n m.m11 = val\n self.dataSetCallback(m)\n\n def m12Changed(self, val):\n m = self.asDataTypeClass()\n m.m12 = val\n self.dataSetCallback(m)\n\n def m13Changed(self, val):\n m = self.asDataTypeClass()\n m.m13 = val\n self.dataSetCallback(m)\n\n def m21Changed(self, val):\n m = self.asDataTypeClass()\n m.m21 = val\n self.dataSetCallback(m)\n\n def m22Changed(self, val):\n m = self.asDataTypeClass()\n m.m22 = val\n self.dataSetCallback(m)\n\n def m23Changed(self, val):\n m = self.asDataTypeClass()\n m.m23 = val\n self.dataSetCallback(m)\n\n def m31Changed(self, val):\n m = self.asDataTypeClass()\n m.m31 = val\n self.dataSetCallback(m)\n\n def m32Changed(self, val):\n m = self.asDataTypeClass()\n m.m32 = val\n self.dataSetCallback(m)\n\n def m33Changed(self, val):\n m = self.asDataTypeClass()\n m.m33 = val\n self.dataSetCallback(m)\n\n def setWidgetValue(self, val):\n self.dsbm11.setValue(val.m11)\n self.dsbm12.setValue(val.m12)\n self.dsbm13.setValue(val.m13)\n self.dsbm21.setValue(val.m21)\n self.dsbm22.setValue(val.m22)\n self.dsbm23.setValue(val.m23)\n self.dsbm31.setValue(val.m31)\n self.dsbm32.setValue(val.m32)\n self.dsbm33.setValue(val.m33)\n\n\nclass Matrix44InputWidget(InputWidgetRaw, Matrix44InputWidget_ui.Ui_Form):\n \"\"\"Matrix44 data input widget\"\"\"\n\n def __init__(self, parent=None, **kwds):\n super(Matrix44InputWidget, self).__init__(parent=parent, **kwds)\n self.setupUi(self)\n self._configSpinBoxes()\n self.dsbm11.valueChanged.connect(self.m11Changed)\n self.dsbm12.valueChanged.connect(self.m12Changed)\n self.dsbm13.valueChanged.connect(self.m13Changed)\n self.dsbm14.valueChanged.connect(self.m14Changed)\n self.dsbm21.valueChanged.connect(self.m21Changed)\n self.dsbm22.valueChanged.connect(self.m22Changed)\n self.dsbm23.valueChanged.connect(self.m23Changed)\n self.dsbm24.valueChanged.connect(self.m24Changed)\n self.dsbm31.valueChanged.connect(self.m31Changed)\n self.dsbm32.valueChanged.connect(self.m32Changed)\n self.dsbm33.valueChanged.connect(self.m33Changed)\n self.dsbm34.valueChanged.connect(self.m34Changed)\n self.dsbm41.valueChanged.connect(self.m41Changed)\n self.dsbm42.valueChanged.connect(self.m42Changed)\n self.dsbm43.valueChanged.connect(self.m43Changed)\n self.dsbm44.valueChanged.connect(self.m44Changed)\n self.pbReset.clicked.connect(self.onResetValue)\n\n def asDataTypeClass(self):\n return pyrr.Matrix44([[self.dsbm11.value(), self.dsbm12.value(),\n self.dsbm13.value(), self.dsbm14.value()], [self.dsbm21.value(),\n self.dsbm22.value(), self.dsbm23.value(), self.dsbm24.value()],\n [self.dsbm31.value(), self.dsbm32.value(), self.dsbm33.value(),\n self.dsbm34.value()], [self.dsbm41.value(), self.dsbm42.value(),\n self.dsbm43.value(), self.dsbm44.value()]])\n\n def _configSpinBoxes(self):\n ls = [self.dsbm11, self.dsbm12, self.dsbm13, self.dsbm14, self.\n dsbm21, self.dsbm22, self.dsbm23, self.dsbm24, self.dsbm31,\n self.dsbm32, self.dsbm33, self.dsbm34, self.dsbm41, self.dsbm42,\n self.dsbm43, self.dsbm44]\n for sb in ls:\n sb.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n sb.setSingleStep(FLOAT_SINGLE_STEP)\n sb.setDecimals(FLOAT_DECIMALS)\n\n def m11Changed(self, val):\n m = self.asDataTypeClass()\n m.m11 = val\n self.dataSetCallback(m)\n\n def m12Changed(self, val):\n m = self.asDataTypeClass()\n m.m12 = val\n self.dataSetCallback(m)\n\n def m13Changed(self, val):\n m = self.asDataTypeClass()\n m.m13 = val\n self.dataSetCallback(m)\n\n def m14Changed(self, val):\n m = self.asDataTypeClass()\n m.m14 = val\n self.dataSetCallback(m)\n\n def m21Changed(self, val):\n m = self.asDataTypeClass()\n m.m21 = val\n self.dataSetCallback(m)\n\n def m22Changed(self, val):\n m = self.asDataTypeClass()\n m.m22 = val\n self.dataSetCallback(m)\n\n def m23Changed(self, val):\n m = self.asDataTypeClass()\n m.m23 = val\n self.dataSetCallback(m)\n\n def m24Changed(self, val):\n m = self.asDataTypeClass()\n m.m24 = val\n self.dataSetCallback(m)\n\n def m31Changed(self, val):\n m = self.asDataTypeClass()\n m.m31 = val\n self.dataSetCallback(m)\n\n def m32Changed(self, val):\n m = self.asDataTypeClass()\n m.m32 = val\n self.dataSetCallback(m)\n\n def m33Changed(self, val):\n m = self.asDataTypeClass()\n m.m33 = val\n self.dataSetCallback(m)\n\n def m34Changed(self, val):\n m = self.asDataTypeClass()\n m.m34 = val\n self.dataSetCallback(m)\n\n def m41Changed(self, val):\n m = self.asDataTypeClass()\n m.m41 = val\n self.dataSetCallback(m)\n\n def m42Changed(self, val):\n m = self.asDataTypeClass()\n m.m42 = val\n self.dataSetCallback(m)\n\n def m43Changed(self, val):\n m = self.asDataTypeClass()\n m.m43 = val\n self.dataSetCallback(m)\n\n def m44Changed(self, val):\n m = self.asDataTypeClass()\n m.m44 = val\n self.dataSetCallback(m)\n\n def setWidgetValue(self, val):\n self.dsbm11.setValue(val.m11)\n self.dsbm12.setValue(val.m12)\n self.dsbm13.setValue(val.m13)\n self.dsbm14.setValue(val.m14)\n self.dsbm21.setValue(val.m21)\n self.dsbm22.setValue(val.m22)\n self.dsbm23.setValue(val.m23)\n self.dsbm24.setValue(val.m24)\n self.dsbm31.setValue(val.m31)\n self.dsbm32.setValue(val.m32)\n self.dsbm33.setValue(val.m33)\n self.dsbm34.setValue(val.m34)\n self.dsbm41.setValue(val.m41)\n self.dsbm42.setValue(val.m42)\n self.dsbm43.setValue(val.m43)\n self.dsbm44.setValue(val.m44)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass FloatVector3InputWidget(InputWidgetRaw, FloatVector3InputWidget_ui.\n Ui_Form):\n \"\"\"Vector3 data input widget\"\"\"\n\n def __init__(self, **kwds):\n super(FloatVector3InputWidget, self).__init__(**kwds)\n self.setupUi(self)\n self._configSpinBoxes()\n self.dsbX.valueChanged.connect(self._onDataChangedX)\n self.dsbY.valueChanged.connect(self._onDataChangedY)\n self.dsbZ.valueChanged.connect(self._onDataChangedZ)\n self.pbReset.clicked.connect(self.onResetValue)\n\n def asDataTypeClass(self):\n return pyrr.Vector3([self.dsbX.value(), self.dsbY.value(), self.\n dsbZ.value()])\n\n def _configSpinBoxes(self):\n self.dsbX.setDecimals(FLOAT_DECIMALS)\n self.dsbY.setDecimals(FLOAT_DECIMALS)\n self.dsbZ.setDecimals(FLOAT_DECIMALS)\n self.dsbX.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbY.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbZ.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbX.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbY.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbZ.setSingleStep(FLOAT_SINGLE_STEP)\n\n def _onDataChangedX(self, val):\n v = self.asDataTypeClass()\n v.x = val\n self.dataSetCallback(v)\n\n def _onDataChangedY(self, val):\n v = self.asDataTypeClass()\n v.y = val\n self.dataSetCallback(v)\n\n def _onDataChangedZ(self, val):\n v = self.asDataTypeClass()\n v.z = val\n self.dataSetCallback(v)\n\n def setWidgetValue(self, val):\n self.dsbX.setValue(val.x)\n self.dsbY.setValue(val.y)\n self.dsbZ.setValue(val.z)\n\n\nclass FloatVector4InputWidget(InputWidgetRaw, FloatVector4InputWidget_ui.\n Ui_Form):\n \"\"\"Vector4 data input widget\"\"\"\n\n def __init__(self, **kwds):\n super(FloatVector4InputWidget, self).__init__(**kwds)\n self.setupUi(self)\n self._configSpinBoxes()\n self.dsbX.valueChanged.connect(self._onDataChangedX)\n self.dsbY.valueChanged.connect(self._onDataChangedY)\n self.dsbZ.valueChanged.connect(self._onDataChangedZ)\n self.dsbW.valueChanged.connect(self._onDataChangedW)\n self.pbReset.clicked.connect(self.onResetValue)\n\n def asDataTypeClass(self):\n return pyrr.Vector4([self.dsbX.value(), self.dsbY.value(), self.\n dsbZ.value(), self.dsbW.value()])\n\n def _configSpinBoxes(self):\n self.dsbX.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbY.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbZ.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbW.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbX.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbY.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbZ.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbW.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbX.setDecimals(FLOAT_DECIMALS)\n self.dsbY.setDecimals(FLOAT_DECIMALS)\n self.dsbZ.setDecimals(FLOAT_DECIMALS)\n self.dsbW.setDecimals(FLOAT_DECIMALS)\n\n def _onDataChangedX(self, val):\n v = self.asDataTypeClass()\n v.x = val\n self.dataSetCallback(v)\n\n def _onDataChangedY(self, val):\n v = self.asDataTypeClass()\n v.y = val\n self.dataSetCallback(v)\n\n def _onDataChangedZ(self, val):\n v = self.asDataTypeClass()\n v.z = val\n self.dataSetCallback(v)\n\n def _onDataChangedW(self, val):\n v = self.asDataTypeClass()\n v.w = val\n self.dataSetCallback(v)\n\n def setWidgetValue(self, val):\n self.dsbX.setValue(val.x)\n self.dsbY.setValue(val.y)\n self.dsbZ.setValue(val.z)\n self.dsbW.setValue(val.w)\n\n\nclass QuatInputWidget(FloatVector4InputWidget):\n \"\"\"Quaternion data input widget\"\"\"\n\n def __init__(self, **kwds):\n super(QuatInputWidget, self).__init__(**kwds)\n\n def asDataTypeClass(self):\n return pyrr.Quaternion([self.dsbX.value(), self.dsbY.value(), self.\n dsbZ.value(), self.dsbW.value()])\n\n\nclass Matrix33InputWidget(InputWidgetRaw, Matrix33InputWidget_ui.Ui_Form):\n \"\"\"Matrix33 data input widget\"\"\"\n\n def __init__(self, parent=None, **kwds):\n super(Matrix33InputWidget, self).__init__(parent=parent, **kwds)\n self.setupUi(self)\n self._configSpinBoxes()\n self.dsbm11.valueChanged.connect(self.m11Changed)\n self.dsbm12.valueChanged.connect(self.m12Changed)\n self.dsbm13.valueChanged.connect(self.m13Changed)\n self.dsbm21.valueChanged.connect(self.m21Changed)\n self.dsbm22.valueChanged.connect(self.m22Changed)\n self.dsbm23.valueChanged.connect(self.m23Changed)\n self.dsbm31.valueChanged.connect(self.m31Changed)\n self.dsbm32.valueChanged.connect(self.m32Changed)\n self.dsbm33.valueChanged.connect(self.m33Changed)\n self.pbReset.clicked.connect(self.onResetValue)\n\n def asDataTypeClass(self):\n return pyrr.Matrix33([[self.dsbm11.value(), self.dsbm12.value(),\n self.dsbm13.value()], [self.dsbm21.value(), self.dsbm22.value(),\n self.dsbm23.value()], [self.dsbm31.value(), self.dsbm32.value(),\n self.dsbm33.value()]])\n\n def _configSpinBoxes(self):\n ls = [self.dsbm11, self.dsbm12, self.dsbm13, self.dsbm21, self.\n dsbm22, self.dsbm23, self.dsbm31, self.dsbm32, self.dsbm33]\n for sb in ls:\n sb.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n sb.setSingleStep(FLOAT_SINGLE_STEP)\n sb.setDecimals(FLOAT_DECIMALS)\n\n def m11Changed(self, val):\n m = self.asDataTypeClass()\n m.m11 = val\n self.dataSetCallback(m)\n\n def m12Changed(self, val):\n m = self.asDataTypeClass()\n m.m12 = val\n self.dataSetCallback(m)\n\n def m13Changed(self, val):\n m = self.asDataTypeClass()\n m.m13 = val\n self.dataSetCallback(m)\n\n def m21Changed(self, val):\n m = self.asDataTypeClass()\n m.m21 = val\n self.dataSetCallback(m)\n\n def m22Changed(self, val):\n m = self.asDataTypeClass()\n m.m22 = val\n self.dataSetCallback(m)\n\n def m23Changed(self, val):\n m = self.asDataTypeClass()\n m.m23 = val\n self.dataSetCallback(m)\n\n def m31Changed(self, val):\n m = self.asDataTypeClass()\n m.m31 = val\n self.dataSetCallback(m)\n\n def m32Changed(self, val):\n m = self.asDataTypeClass()\n m.m32 = val\n self.dataSetCallback(m)\n\n def m33Changed(self, val):\n m = self.asDataTypeClass()\n m.m33 = val\n self.dataSetCallback(m)\n\n def setWidgetValue(self, val):\n self.dsbm11.setValue(val.m11)\n self.dsbm12.setValue(val.m12)\n self.dsbm13.setValue(val.m13)\n self.dsbm21.setValue(val.m21)\n self.dsbm22.setValue(val.m22)\n self.dsbm23.setValue(val.m23)\n self.dsbm31.setValue(val.m31)\n self.dsbm32.setValue(val.m32)\n self.dsbm33.setValue(val.m33)\n\n\nclass Matrix44InputWidget(InputWidgetRaw, Matrix44InputWidget_ui.Ui_Form):\n \"\"\"Matrix44 data input widget\"\"\"\n\n def __init__(self, parent=None, **kwds):\n super(Matrix44InputWidget, self).__init__(parent=parent, **kwds)\n self.setupUi(self)\n self._configSpinBoxes()\n self.dsbm11.valueChanged.connect(self.m11Changed)\n self.dsbm12.valueChanged.connect(self.m12Changed)\n self.dsbm13.valueChanged.connect(self.m13Changed)\n self.dsbm14.valueChanged.connect(self.m14Changed)\n self.dsbm21.valueChanged.connect(self.m21Changed)\n self.dsbm22.valueChanged.connect(self.m22Changed)\n self.dsbm23.valueChanged.connect(self.m23Changed)\n self.dsbm24.valueChanged.connect(self.m24Changed)\n self.dsbm31.valueChanged.connect(self.m31Changed)\n self.dsbm32.valueChanged.connect(self.m32Changed)\n self.dsbm33.valueChanged.connect(self.m33Changed)\n self.dsbm34.valueChanged.connect(self.m34Changed)\n self.dsbm41.valueChanged.connect(self.m41Changed)\n self.dsbm42.valueChanged.connect(self.m42Changed)\n self.dsbm43.valueChanged.connect(self.m43Changed)\n self.dsbm44.valueChanged.connect(self.m44Changed)\n self.pbReset.clicked.connect(self.onResetValue)\n\n def asDataTypeClass(self):\n return pyrr.Matrix44([[self.dsbm11.value(), self.dsbm12.value(),\n self.dsbm13.value(), self.dsbm14.value()], [self.dsbm21.value(),\n self.dsbm22.value(), self.dsbm23.value(), self.dsbm24.value()],\n [self.dsbm31.value(), self.dsbm32.value(), self.dsbm33.value(),\n self.dsbm34.value()], [self.dsbm41.value(), self.dsbm42.value(),\n self.dsbm43.value(), self.dsbm44.value()]])\n\n def _configSpinBoxes(self):\n ls = [self.dsbm11, self.dsbm12, self.dsbm13, self.dsbm14, self.\n dsbm21, self.dsbm22, self.dsbm23, self.dsbm24, self.dsbm31,\n self.dsbm32, self.dsbm33, self.dsbm34, self.dsbm41, self.dsbm42,\n self.dsbm43, self.dsbm44]\n for sb in ls:\n sb.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n sb.setSingleStep(FLOAT_SINGLE_STEP)\n sb.setDecimals(FLOAT_DECIMALS)\n\n def m11Changed(self, val):\n m = self.asDataTypeClass()\n m.m11 = val\n self.dataSetCallback(m)\n\n def m12Changed(self, val):\n m = self.asDataTypeClass()\n m.m12 = val\n self.dataSetCallback(m)\n\n def m13Changed(self, val):\n m = self.asDataTypeClass()\n m.m13 = val\n self.dataSetCallback(m)\n\n def m14Changed(self, val):\n m = self.asDataTypeClass()\n m.m14 = val\n self.dataSetCallback(m)\n\n def m21Changed(self, val):\n m = self.asDataTypeClass()\n m.m21 = val\n self.dataSetCallback(m)\n\n def m22Changed(self, val):\n m = self.asDataTypeClass()\n m.m22 = val\n self.dataSetCallback(m)\n\n def m23Changed(self, val):\n m = self.asDataTypeClass()\n m.m23 = val\n self.dataSetCallback(m)\n\n def m24Changed(self, val):\n m = self.asDataTypeClass()\n m.m24 = val\n self.dataSetCallback(m)\n\n def m31Changed(self, val):\n m = self.asDataTypeClass()\n m.m31 = val\n self.dataSetCallback(m)\n\n def m32Changed(self, val):\n m = self.asDataTypeClass()\n m.m32 = val\n self.dataSetCallback(m)\n\n def m33Changed(self, val):\n m = self.asDataTypeClass()\n m.m33 = val\n self.dataSetCallback(m)\n\n def m34Changed(self, val):\n m = self.asDataTypeClass()\n m.m34 = val\n self.dataSetCallback(m)\n\n def m41Changed(self, val):\n m = self.asDataTypeClass()\n m.m41 = val\n self.dataSetCallback(m)\n\n def m42Changed(self, val):\n m = self.asDataTypeClass()\n m.m42 = val\n self.dataSetCallback(m)\n\n def m43Changed(self, val):\n m = self.asDataTypeClass()\n m.m43 = val\n self.dataSetCallback(m)\n\n def m44Changed(self, val):\n m = self.asDataTypeClass()\n m.m44 = val\n self.dataSetCallback(m)\n\n def setWidgetValue(self, val):\n self.dsbm11.setValue(val.m11)\n self.dsbm12.setValue(val.m12)\n self.dsbm13.setValue(val.m13)\n self.dsbm14.setValue(val.m14)\n self.dsbm21.setValue(val.m21)\n self.dsbm22.setValue(val.m22)\n self.dsbm23.setValue(val.m23)\n self.dsbm24.setValue(val.m24)\n self.dsbm31.setValue(val.m31)\n self.dsbm32.setValue(val.m32)\n self.dsbm33.setValue(val.m33)\n self.dsbm34.setValue(val.m34)\n self.dsbm41.setValue(val.m41)\n self.dsbm42.setValue(val.m42)\n self.dsbm43.setValue(val.m43)\n self.dsbm44.setValue(val.m44)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass BoolInputWidget(InputWidgetSingle):\n <mask token>\n\n def __init__(self, parent=None, **kwds):\n super(BoolInputWidget, self).__init__(parent=parent, **kwds)\n self.cb = QCheckBox(self)\n self.setWidget(self.cb)\n self.cb.stateChanged.connect(lambda val: self.dataSetCallback(bool(\n val)))\n <mask token>\n\n\nclass FloatVector3InputWidget(InputWidgetRaw, FloatVector3InputWidget_ui.\n Ui_Form):\n \"\"\"Vector3 data input widget\"\"\"\n\n def __init__(self, **kwds):\n super(FloatVector3InputWidget, self).__init__(**kwds)\n self.setupUi(self)\n self._configSpinBoxes()\n self.dsbX.valueChanged.connect(self._onDataChangedX)\n self.dsbY.valueChanged.connect(self._onDataChangedY)\n self.dsbZ.valueChanged.connect(self._onDataChangedZ)\n self.pbReset.clicked.connect(self.onResetValue)\n\n def asDataTypeClass(self):\n return pyrr.Vector3([self.dsbX.value(), self.dsbY.value(), self.\n dsbZ.value()])\n\n def _configSpinBoxes(self):\n self.dsbX.setDecimals(FLOAT_DECIMALS)\n self.dsbY.setDecimals(FLOAT_DECIMALS)\n self.dsbZ.setDecimals(FLOAT_DECIMALS)\n self.dsbX.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbY.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbZ.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbX.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbY.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbZ.setSingleStep(FLOAT_SINGLE_STEP)\n\n def _onDataChangedX(self, val):\n v = self.asDataTypeClass()\n v.x = val\n self.dataSetCallback(v)\n\n def _onDataChangedY(self, val):\n v = self.asDataTypeClass()\n v.y = val\n self.dataSetCallback(v)\n\n def _onDataChangedZ(self, val):\n v = self.asDataTypeClass()\n v.z = val\n self.dataSetCallback(v)\n\n def setWidgetValue(self, val):\n self.dsbX.setValue(val.x)\n self.dsbY.setValue(val.y)\n self.dsbZ.setValue(val.z)\n\n\nclass FloatVector4InputWidget(InputWidgetRaw, FloatVector4InputWidget_ui.\n Ui_Form):\n \"\"\"Vector4 data input widget\"\"\"\n\n def __init__(self, **kwds):\n super(FloatVector4InputWidget, self).__init__(**kwds)\n self.setupUi(self)\n self._configSpinBoxes()\n self.dsbX.valueChanged.connect(self._onDataChangedX)\n self.dsbY.valueChanged.connect(self._onDataChangedY)\n self.dsbZ.valueChanged.connect(self._onDataChangedZ)\n self.dsbW.valueChanged.connect(self._onDataChangedW)\n self.pbReset.clicked.connect(self.onResetValue)\n\n def asDataTypeClass(self):\n return pyrr.Vector4([self.dsbX.value(), self.dsbY.value(), self.\n dsbZ.value(), self.dsbW.value()])\n\n def _configSpinBoxes(self):\n self.dsbX.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbY.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbZ.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbW.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbX.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbY.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbZ.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbW.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbX.setDecimals(FLOAT_DECIMALS)\n self.dsbY.setDecimals(FLOAT_DECIMALS)\n self.dsbZ.setDecimals(FLOAT_DECIMALS)\n self.dsbW.setDecimals(FLOAT_DECIMALS)\n\n def _onDataChangedX(self, val):\n v = self.asDataTypeClass()\n v.x = val\n self.dataSetCallback(v)\n\n def _onDataChangedY(self, val):\n v = self.asDataTypeClass()\n v.y = val\n self.dataSetCallback(v)\n\n def _onDataChangedZ(self, val):\n v = self.asDataTypeClass()\n v.z = val\n self.dataSetCallback(v)\n\n def _onDataChangedW(self, val):\n v = self.asDataTypeClass()\n v.w = val\n self.dataSetCallback(v)\n\n def setWidgetValue(self, val):\n self.dsbX.setValue(val.x)\n self.dsbY.setValue(val.y)\n self.dsbZ.setValue(val.z)\n self.dsbW.setValue(val.w)\n\n\nclass QuatInputWidget(FloatVector4InputWidget):\n \"\"\"Quaternion data input widget\"\"\"\n\n def __init__(self, **kwds):\n super(QuatInputWidget, self).__init__(**kwds)\n\n def asDataTypeClass(self):\n return pyrr.Quaternion([self.dsbX.value(), self.dsbY.value(), self.\n dsbZ.value(), self.dsbW.value()])\n\n\nclass Matrix33InputWidget(InputWidgetRaw, Matrix33InputWidget_ui.Ui_Form):\n \"\"\"Matrix33 data input widget\"\"\"\n\n def __init__(self, parent=None, **kwds):\n super(Matrix33InputWidget, self).__init__(parent=parent, **kwds)\n self.setupUi(self)\n self._configSpinBoxes()\n self.dsbm11.valueChanged.connect(self.m11Changed)\n self.dsbm12.valueChanged.connect(self.m12Changed)\n self.dsbm13.valueChanged.connect(self.m13Changed)\n self.dsbm21.valueChanged.connect(self.m21Changed)\n self.dsbm22.valueChanged.connect(self.m22Changed)\n self.dsbm23.valueChanged.connect(self.m23Changed)\n self.dsbm31.valueChanged.connect(self.m31Changed)\n self.dsbm32.valueChanged.connect(self.m32Changed)\n self.dsbm33.valueChanged.connect(self.m33Changed)\n self.pbReset.clicked.connect(self.onResetValue)\n\n def asDataTypeClass(self):\n return pyrr.Matrix33([[self.dsbm11.value(), self.dsbm12.value(),\n self.dsbm13.value()], [self.dsbm21.value(), self.dsbm22.value(),\n self.dsbm23.value()], [self.dsbm31.value(), self.dsbm32.value(),\n self.dsbm33.value()]])\n\n def _configSpinBoxes(self):\n ls = [self.dsbm11, self.dsbm12, self.dsbm13, self.dsbm21, self.\n dsbm22, self.dsbm23, self.dsbm31, self.dsbm32, self.dsbm33]\n for sb in ls:\n sb.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n sb.setSingleStep(FLOAT_SINGLE_STEP)\n sb.setDecimals(FLOAT_DECIMALS)\n\n def m11Changed(self, val):\n m = self.asDataTypeClass()\n m.m11 = val\n self.dataSetCallback(m)\n\n def m12Changed(self, val):\n m = self.asDataTypeClass()\n m.m12 = val\n self.dataSetCallback(m)\n\n def m13Changed(self, val):\n m = self.asDataTypeClass()\n m.m13 = val\n self.dataSetCallback(m)\n\n def m21Changed(self, val):\n m = self.asDataTypeClass()\n m.m21 = val\n self.dataSetCallback(m)\n\n def m22Changed(self, val):\n m = self.asDataTypeClass()\n m.m22 = val\n self.dataSetCallback(m)\n\n def m23Changed(self, val):\n m = self.asDataTypeClass()\n m.m23 = val\n self.dataSetCallback(m)\n\n def m31Changed(self, val):\n m = self.asDataTypeClass()\n m.m31 = val\n self.dataSetCallback(m)\n\n def m32Changed(self, val):\n m = self.asDataTypeClass()\n m.m32 = val\n self.dataSetCallback(m)\n\n def m33Changed(self, val):\n m = self.asDataTypeClass()\n m.m33 = val\n self.dataSetCallback(m)\n\n def setWidgetValue(self, val):\n self.dsbm11.setValue(val.m11)\n self.dsbm12.setValue(val.m12)\n self.dsbm13.setValue(val.m13)\n self.dsbm21.setValue(val.m21)\n self.dsbm22.setValue(val.m22)\n self.dsbm23.setValue(val.m23)\n self.dsbm31.setValue(val.m31)\n self.dsbm32.setValue(val.m32)\n self.dsbm33.setValue(val.m33)\n\n\nclass Matrix44InputWidget(InputWidgetRaw, Matrix44InputWidget_ui.Ui_Form):\n \"\"\"Matrix44 data input widget\"\"\"\n\n def __init__(self, parent=None, **kwds):\n super(Matrix44InputWidget, self).__init__(parent=parent, **kwds)\n self.setupUi(self)\n self._configSpinBoxes()\n self.dsbm11.valueChanged.connect(self.m11Changed)\n self.dsbm12.valueChanged.connect(self.m12Changed)\n self.dsbm13.valueChanged.connect(self.m13Changed)\n self.dsbm14.valueChanged.connect(self.m14Changed)\n self.dsbm21.valueChanged.connect(self.m21Changed)\n self.dsbm22.valueChanged.connect(self.m22Changed)\n self.dsbm23.valueChanged.connect(self.m23Changed)\n self.dsbm24.valueChanged.connect(self.m24Changed)\n self.dsbm31.valueChanged.connect(self.m31Changed)\n self.dsbm32.valueChanged.connect(self.m32Changed)\n self.dsbm33.valueChanged.connect(self.m33Changed)\n self.dsbm34.valueChanged.connect(self.m34Changed)\n self.dsbm41.valueChanged.connect(self.m41Changed)\n self.dsbm42.valueChanged.connect(self.m42Changed)\n self.dsbm43.valueChanged.connect(self.m43Changed)\n self.dsbm44.valueChanged.connect(self.m44Changed)\n self.pbReset.clicked.connect(self.onResetValue)\n\n def asDataTypeClass(self):\n return pyrr.Matrix44([[self.dsbm11.value(), self.dsbm12.value(),\n self.dsbm13.value(), self.dsbm14.value()], [self.dsbm21.value(),\n self.dsbm22.value(), self.dsbm23.value(), self.dsbm24.value()],\n [self.dsbm31.value(), self.dsbm32.value(), self.dsbm33.value(),\n self.dsbm34.value()], [self.dsbm41.value(), self.dsbm42.value(),\n self.dsbm43.value(), self.dsbm44.value()]])\n\n def _configSpinBoxes(self):\n ls = [self.dsbm11, self.dsbm12, self.dsbm13, self.dsbm14, self.\n dsbm21, self.dsbm22, self.dsbm23, self.dsbm24, self.dsbm31,\n self.dsbm32, self.dsbm33, self.dsbm34, self.dsbm41, self.dsbm42,\n self.dsbm43, self.dsbm44]\n for sb in ls:\n sb.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n sb.setSingleStep(FLOAT_SINGLE_STEP)\n sb.setDecimals(FLOAT_DECIMALS)\n\n def m11Changed(self, val):\n m = self.asDataTypeClass()\n m.m11 = val\n self.dataSetCallback(m)\n\n def m12Changed(self, val):\n m = self.asDataTypeClass()\n m.m12 = val\n self.dataSetCallback(m)\n\n def m13Changed(self, val):\n m = self.asDataTypeClass()\n m.m13 = val\n self.dataSetCallback(m)\n\n def m14Changed(self, val):\n m = self.asDataTypeClass()\n m.m14 = val\n self.dataSetCallback(m)\n\n def m21Changed(self, val):\n m = self.asDataTypeClass()\n m.m21 = val\n self.dataSetCallback(m)\n\n def m22Changed(self, val):\n m = self.asDataTypeClass()\n m.m22 = val\n self.dataSetCallback(m)\n\n def m23Changed(self, val):\n m = self.asDataTypeClass()\n m.m23 = val\n self.dataSetCallback(m)\n\n def m24Changed(self, val):\n m = self.asDataTypeClass()\n m.m24 = val\n self.dataSetCallback(m)\n\n def m31Changed(self, val):\n m = self.asDataTypeClass()\n m.m31 = val\n self.dataSetCallback(m)\n\n def m32Changed(self, val):\n m = self.asDataTypeClass()\n m.m32 = val\n self.dataSetCallback(m)\n\n def m33Changed(self, val):\n m = self.asDataTypeClass()\n m.m33 = val\n self.dataSetCallback(m)\n\n def m34Changed(self, val):\n m = self.asDataTypeClass()\n m.m34 = val\n self.dataSetCallback(m)\n\n def m41Changed(self, val):\n m = self.asDataTypeClass()\n m.m41 = val\n self.dataSetCallback(m)\n\n def m42Changed(self, val):\n m = self.asDataTypeClass()\n m.m42 = val\n self.dataSetCallback(m)\n\n def m43Changed(self, val):\n m = self.asDataTypeClass()\n m.m43 = val\n self.dataSetCallback(m)\n\n def m44Changed(self, val):\n m = self.asDataTypeClass()\n m.m44 = val\n self.dataSetCallback(m)\n\n def setWidgetValue(self, val):\n self.dsbm11.setValue(val.m11)\n self.dsbm12.setValue(val.m12)\n self.dsbm13.setValue(val.m13)\n self.dsbm14.setValue(val.m14)\n self.dsbm21.setValue(val.m21)\n self.dsbm22.setValue(val.m22)\n self.dsbm23.setValue(val.m23)\n self.dsbm24.setValue(val.m24)\n self.dsbm31.setValue(val.m31)\n self.dsbm32.setValue(val.m32)\n self.dsbm33.setValue(val.m33)\n self.dsbm34.setValue(val.m34)\n self.dsbm41.setValue(val.m41)\n self.dsbm42.setValue(val.m42)\n self.dsbm43.setValue(val.m43)\n self.dsbm44.setValue(val.m44)\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass EnumInputWidget(InputWidgetSingle):\n <mask token>\n <mask token>\n <mask token>\n\n\nclass FloatInputWidget(InputWidgetSingle):\n \"\"\"\n Floating point data input widget\n \"\"\"\n\n def __init__(self, parent=None, **kwds):\n super(FloatInputWidget, self).__init__(parent=parent, **kwds)\n self.sb = QDoubleSpinBox(self)\n _configDoubleSpinBox(self.sb)\n self.setWidget(self.sb)\n self.sb.valueChanged.connect(lambda val: self.dataSetCallback(val))\n\n def setWidgetValue(self, val):\n self.sb.setValue(float(val))\n\n\nclass IntInputWidget(InputWidgetSingle):\n \"\"\"\n Decimal number input widget\n \"\"\"\n\n def __init__(self, parent=None, **kwds):\n super(IntInputWidget, self).__init__(parent=parent, **kwds)\n self.sb = QSpinBox(self)\n _configIntSpinBox(self.sb)\n self.setWidget(self.sb)\n self.sb.valueChanged.connect(lambda val: self.dataSetCallback(val))\n\n def setWidgetValue(self, val):\n self.sb.setValue(int(val))\n\n\nclass NoneInputWidget(InputWidgetSingle):\n \"\"\"\n String data input widget\n \"\"\"\n\n def __init__(self, parent=None, **kwds):\n super(NoneInputWidget, self).__init__(parent=parent, **kwds)\n self.le = QLineEdit(self)\n self.le.setContextMenuPolicy(QtCore.Qt.NoContextMenu)\n self.setWidget(self.le)\n self.le.textChanged.connect(lambda val: self.dataSetCallback(val))\n self.le.setEnabled(False)\n\n def setWidgetValue(self, val):\n self.le.setText(str(val))\n\n\nclass StringInputWidget(InputWidgetSingle):\n \"\"\"\n String data input widget\n \"\"\"\n\n def __init__(self, parent=None, **kwds):\n super(StringInputWidget, self).__init__(parent=parent, **kwds)\n self.le = QLineEdit(self)\n self.le.setContextMenuPolicy(QtCore.Qt.NoContextMenu)\n self.setWidget(self.le)\n self.le.textChanged.connect(lambda val: self.dataSetCallback(val))\n\n def setWidgetValue(self, val):\n self.le.setText(str(val))\n\n\nclass BoolInputWidget(InputWidgetSingle):\n \"\"\"Boolean data input widget\"\"\"\n\n def __init__(self, parent=None, **kwds):\n super(BoolInputWidget, self).__init__(parent=parent, **kwds)\n self.cb = QCheckBox(self)\n self.setWidget(self.cb)\n self.cb.stateChanged.connect(lambda val: self.dataSetCallback(bool(\n val)))\n\n def setWidgetValue(self, val):\n if bool(val):\n self.cb.setCheckState(QtCore.Qt.Checked)\n else:\n self.cb.setCheckState(QtCore.Qt.Unchecked)\n\n\nclass FloatVector3InputWidget(InputWidgetRaw, FloatVector3InputWidget_ui.\n Ui_Form):\n \"\"\"Vector3 data input widget\"\"\"\n\n def __init__(self, **kwds):\n super(FloatVector3InputWidget, self).__init__(**kwds)\n self.setupUi(self)\n self._configSpinBoxes()\n self.dsbX.valueChanged.connect(self._onDataChangedX)\n self.dsbY.valueChanged.connect(self._onDataChangedY)\n self.dsbZ.valueChanged.connect(self._onDataChangedZ)\n self.pbReset.clicked.connect(self.onResetValue)\n\n def asDataTypeClass(self):\n return pyrr.Vector3([self.dsbX.value(), self.dsbY.value(), self.\n dsbZ.value()])\n\n def _configSpinBoxes(self):\n self.dsbX.setDecimals(FLOAT_DECIMALS)\n self.dsbY.setDecimals(FLOAT_DECIMALS)\n self.dsbZ.setDecimals(FLOAT_DECIMALS)\n self.dsbX.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbY.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbZ.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbX.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbY.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbZ.setSingleStep(FLOAT_SINGLE_STEP)\n\n def _onDataChangedX(self, val):\n v = self.asDataTypeClass()\n v.x = val\n self.dataSetCallback(v)\n\n def _onDataChangedY(self, val):\n v = self.asDataTypeClass()\n v.y = val\n self.dataSetCallback(v)\n\n def _onDataChangedZ(self, val):\n v = self.asDataTypeClass()\n v.z = val\n self.dataSetCallback(v)\n\n def setWidgetValue(self, val):\n self.dsbX.setValue(val.x)\n self.dsbY.setValue(val.y)\n self.dsbZ.setValue(val.z)\n\n\nclass FloatVector4InputWidget(InputWidgetRaw, FloatVector4InputWidget_ui.\n Ui_Form):\n \"\"\"Vector4 data input widget\"\"\"\n\n def __init__(self, **kwds):\n super(FloatVector4InputWidget, self).__init__(**kwds)\n self.setupUi(self)\n self._configSpinBoxes()\n self.dsbX.valueChanged.connect(self._onDataChangedX)\n self.dsbY.valueChanged.connect(self._onDataChangedY)\n self.dsbZ.valueChanged.connect(self._onDataChangedZ)\n self.dsbW.valueChanged.connect(self._onDataChangedW)\n self.pbReset.clicked.connect(self.onResetValue)\n\n def asDataTypeClass(self):\n return pyrr.Vector4([self.dsbX.value(), self.dsbY.value(), self.\n dsbZ.value(), self.dsbW.value()])\n\n def _configSpinBoxes(self):\n self.dsbX.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbY.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbZ.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbW.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbX.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbY.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbZ.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbW.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbX.setDecimals(FLOAT_DECIMALS)\n self.dsbY.setDecimals(FLOAT_DECIMALS)\n self.dsbZ.setDecimals(FLOAT_DECIMALS)\n self.dsbW.setDecimals(FLOAT_DECIMALS)\n\n def _onDataChangedX(self, val):\n v = self.asDataTypeClass()\n v.x = val\n self.dataSetCallback(v)\n\n def _onDataChangedY(self, val):\n v = self.asDataTypeClass()\n v.y = val\n self.dataSetCallback(v)\n\n def _onDataChangedZ(self, val):\n v = self.asDataTypeClass()\n v.z = val\n self.dataSetCallback(v)\n\n def _onDataChangedW(self, val):\n v = self.asDataTypeClass()\n v.w = val\n self.dataSetCallback(v)\n\n def setWidgetValue(self, val):\n self.dsbX.setValue(val.x)\n self.dsbY.setValue(val.y)\n self.dsbZ.setValue(val.z)\n self.dsbW.setValue(val.w)\n\n\nclass QuatInputWidget(FloatVector4InputWidget):\n \"\"\"Quaternion data input widget\"\"\"\n\n def __init__(self, **kwds):\n super(QuatInputWidget, self).__init__(**kwds)\n\n def asDataTypeClass(self):\n return pyrr.Quaternion([self.dsbX.value(), self.dsbY.value(), self.\n dsbZ.value(), self.dsbW.value()])\n\n\nclass Matrix33InputWidget(InputWidgetRaw, Matrix33InputWidget_ui.Ui_Form):\n \"\"\"Matrix33 data input widget\"\"\"\n\n def __init__(self, parent=None, **kwds):\n super(Matrix33InputWidget, self).__init__(parent=parent, **kwds)\n self.setupUi(self)\n self._configSpinBoxes()\n self.dsbm11.valueChanged.connect(self.m11Changed)\n self.dsbm12.valueChanged.connect(self.m12Changed)\n self.dsbm13.valueChanged.connect(self.m13Changed)\n self.dsbm21.valueChanged.connect(self.m21Changed)\n self.dsbm22.valueChanged.connect(self.m22Changed)\n self.dsbm23.valueChanged.connect(self.m23Changed)\n self.dsbm31.valueChanged.connect(self.m31Changed)\n self.dsbm32.valueChanged.connect(self.m32Changed)\n self.dsbm33.valueChanged.connect(self.m33Changed)\n self.pbReset.clicked.connect(self.onResetValue)\n\n def asDataTypeClass(self):\n return pyrr.Matrix33([[self.dsbm11.value(), self.dsbm12.value(),\n self.dsbm13.value()], [self.dsbm21.value(), self.dsbm22.value(),\n self.dsbm23.value()], [self.dsbm31.value(), self.dsbm32.value(),\n self.dsbm33.value()]])\n\n def _configSpinBoxes(self):\n ls = [self.dsbm11, self.dsbm12, self.dsbm13, self.dsbm21, self.\n dsbm22, self.dsbm23, self.dsbm31, self.dsbm32, self.dsbm33]\n for sb in ls:\n sb.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n sb.setSingleStep(FLOAT_SINGLE_STEP)\n sb.setDecimals(FLOAT_DECIMALS)\n\n def m11Changed(self, val):\n m = self.asDataTypeClass()\n m.m11 = val\n self.dataSetCallback(m)\n\n def m12Changed(self, val):\n m = self.asDataTypeClass()\n m.m12 = val\n self.dataSetCallback(m)\n\n def m13Changed(self, val):\n m = self.asDataTypeClass()\n m.m13 = val\n self.dataSetCallback(m)\n\n def m21Changed(self, val):\n m = self.asDataTypeClass()\n m.m21 = val\n self.dataSetCallback(m)\n\n def m22Changed(self, val):\n m = self.asDataTypeClass()\n m.m22 = val\n self.dataSetCallback(m)\n\n def m23Changed(self, val):\n m = self.asDataTypeClass()\n m.m23 = val\n self.dataSetCallback(m)\n\n def m31Changed(self, val):\n m = self.asDataTypeClass()\n m.m31 = val\n self.dataSetCallback(m)\n\n def m32Changed(self, val):\n m = self.asDataTypeClass()\n m.m32 = val\n self.dataSetCallback(m)\n\n def m33Changed(self, val):\n m = self.asDataTypeClass()\n m.m33 = val\n self.dataSetCallback(m)\n\n def setWidgetValue(self, val):\n self.dsbm11.setValue(val.m11)\n self.dsbm12.setValue(val.m12)\n self.dsbm13.setValue(val.m13)\n self.dsbm21.setValue(val.m21)\n self.dsbm22.setValue(val.m22)\n self.dsbm23.setValue(val.m23)\n self.dsbm31.setValue(val.m31)\n self.dsbm32.setValue(val.m32)\n self.dsbm33.setValue(val.m33)\n\n\nclass Matrix44InputWidget(InputWidgetRaw, Matrix44InputWidget_ui.Ui_Form):\n \"\"\"Matrix44 data input widget\"\"\"\n\n def __init__(self, parent=None, **kwds):\n super(Matrix44InputWidget, self).__init__(parent=parent, **kwds)\n self.setupUi(self)\n self._configSpinBoxes()\n self.dsbm11.valueChanged.connect(self.m11Changed)\n self.dsbm12.valueChanged.connect(self.m12Changed)\n self.dsbm13.valueChanged.connect(self.m13Changed)\n self.dsbm14.valueChanged.connect(self.m14Changed)\n self.dsbm21.valueChanged.connect(self.m21Changed)\n self.dsbm22.valueChanged.connect(self.m22Changed)\n self.dsbm23.valueChanged.connect(self.m23Changed)\n self.dsbm24.valueChanged.connect(self.m24Changed)\n self.dsbm31.valueChanged.connect(self.m31Changed)\n self.dsbm32.valueChanged.connect(self.m32Changed)\n self.dsbm33.valueChanged.connect(self.m33Changed)\n self.dsbm34.valueChanged.connect(self.m34Changed)\n self.dsbm41.valueChanged.connect(self.m41Changed)\n self.dsbm42.valueChanged.connect(self.m42Changed)\n self.dsbm43.valueChanged.connect(self.m43Changed)\n self.dsbm44.valueChanged.connect(self.m44Changed)\n self.pbReset.clicked.connect(self.onResetValue)\n\n def asDataTypeClass(self):\n return pyrr.Matrix44([[self.dsbm11.value(), self.dsbm12.value(),\n self.dsbm13.value(), self.dsbm14.value()], [self.dsbm21.value(),\n self.dsbm22.value(), self.dsbm23.value(), self.dsbm24.value()],\n [self.dsbm31.value(), self.dsbm32.value(), self.dsbm33.value(),\n self.dsbm34.value()], [self.dsbm41.value(), self.dsbm42.value(),\n self.dsbm43.value(), self.dsbm44.value()]])\n\n def _configSpinBoxes(self):\n ls = [self.dsbm11, self.dsbm12, self.dsbm13, self.dsbm14, self.\n dsbm21, self.dsbm22, self.dsbm23, self.dsbm24, self.dsbm31,\n self.dsbm32, self.dsbm33, self.dsbm34, self.dsbm41, self.dsbm42,\n self.dsbm43, self.dsbm44]\n for sb in ls:\n sb.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n sb.setSingleStep(FLOAT_SINGLE_STEP)\n sb.setDecimals(FLOAT_DECIMALS)\n\n def m11Changed(self, val):\n m = self.asDataTypeClass()\n m.m11 = val\n self.dataSetCallback(m)\n\n def m12Changed(self, val):\n m = self.asDataTypeClass()\n m.m12 = val\n self.dataSetCallback(m)\n\n def m13Changed(self, val):\n m = self.asDataTypeClass()\n m.m13 = val\n self.dataSetCallback(m)\n\n def m14Changed(self, val):\n m = self.asDataTypeClass()\n m.m14 = val\n self.dataSetCallback(m)\n\n def m21Changed(self, val):\n m = self.asDataTypeClass()\n m.m21 = val\n self.dataSetCallback(m)\n\n def m22Changed(self, val):\n m = self.asDataTypeClass()\n m.m22 = val\n self.dataSetCallback(m)\n\n def m23Changed(self, val):\n m = self.asDataTypeClass()\n m.m23 = val\n self.dataSetCallback(m)\n\n def m24Changed(self, val):\n m = self.asDataTypeClass()\n m.m24 = val\n self.dataSetCallback(m)\n\n def m31Changed(self, val):\n m = self.asDataTypeClass()\n m.m31 = val\n self.dataSetCallback(m)\n\n def m32Changed(self, val):\n m = self.asDataTypeClass()\n m.m32 = val\n self.dataSetCallback(m)\n\n def m33Changed(self, val):\n m = self.asDataTypeClass()\n m.m33 = val\n self.dataSetCallback(m)\n\n def m34Changed(self, val):\n m = self.asDataTypeClass()\n m.m34 = val\n self.dataSetCallback(m)\n\n def m41Changed(self, val):\n m = self.asDataTypeClass()\n m.m41 = val\n self.dataSetCallback(m)\n\n def m42Changed(self, val):\n m = self.asDataTypeClass()\n m.m42 = val\n self.dataSetCallback(m)\n\n def m43Changed(self, val):\n m = self.asDataTypeClass()\n m.m43 = val\n self.dataSetCallback(m)\n\n def m44Changed(self, val):\n m = self.asDataTypeClass()\n m.m44 = val\n self.dataSetCallback(m)\n\n def setWidgetValue(self, val):\n self.dsbm11.setValue(val.m11)\n self.dsbm12.setValue(val.m12)\n self.dsbm13.setValue(val.m13)\n self.dsbm14.setValue(val.m14)\n self.dsbm21.setValue(val.m21)\n self.dsbm22.setValue(val.m22)\n self.dsbm23.setValue(val.m23)\n self.dsbm24.setValue(val.m24)\n self.dsbm31.setValue(val.m31)\n self.dsbm32.setValue(val.m32)\n self.dsbm33.setValue(val.m33)\n self.dsbm34.setValue(val.m34)\n self.dsbm41.setValue(val.m41)\n self.dsbm42.setValue(val.m42)\n self.dsbm43.setValue(val.m43)\n self.dsbm44.setValue(val.m44)\n\n\n<mask token>\n", "step-5": "import weakref\nfrom Qt import QtCore\nfrom Qt import QtGui\nfrom Qt.QtWidgets import QDoubleSpinBox\nfrom Qt.QtWidgets import QSpinBox\nfrom Qt.QtWidgets import QWidget\nfrom Qt.QtWidgets import QSpacerItem\nfrom Qt.QtWidgets import QPushButton\nfrom Qt.QtWidgets import QComboBox\nfrom Qt.QtWidgets import QLineEdit\nfrom Qt.QtWidgets import QCheckBox\nfrom Qt.QtWidgets import QGraphicsProxyWidget\nfrom Qt.QtWidgets import QGridLayout\nfrom Qt.QtWidgets import QHBoxLayout\nfrom Qt.QtWidgets import QSizePolicy\nfrom AGraphCommon import *\nfrom AbstractGraph import PinBase\nfrom ..Ui import FloatVector3InputWidget_ui\nfrom ..Ui import FloatVector4InputWidget_ui\nfrom ..Ui import Matrix33InputWidget_ui\nfrom ..Ui import Matrix44InputWidget_ui\nimport pyrr\n\n\ndef _configDoubleSpinBox(sb):\n sb.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n sb.setSingleStep(FLOAT_SINGLE_STEP)\n sb.setDecimals(FLOAT_DECIMALS)\n\n\ndef _configIntSpinBox(sb):\n sb.setRange(INT_RANGE_MIN, INT_RANGE_MAX)\n\n\nclass InputWidgetRaw(QWidget):\n \"\"\"\n This type of widget can be used as a base class for complex ui generated by designer\n \"\"\"\n def __init__(self, parent=None, dataSetCallback=None, defaultValue=None, userStructClass=None, **kwds):\n super(InputWidgetRaw, self).__init__(parent=parent, **kwds)\n self._defaultValue = defaultValue\n # fuction with signature void(object)\n # this will set data to pin\n self.dataSetCallback = dataSetCallback\n\n def onResetValue(self):\n self.setWidgetValue(self._defaultValue)\n\n def setWidgetValue(self, value):\n '''to widget'''\n pass\n\n def widgetValueUpdated(self, value):\n '''from widget'''\n pass\n\n\nclass InputWidgetSingle(InputWidgetRaw):\n \"\"\"\n This type of widget is used for a simple widgets like buttons, checkboxes etc.\n It consists of horizontal layout widget itself and reset button.\n \"\"\"\n\n def __init__(self, parent=None, dataSetCallback=None, defaultValue=None, userStructClass=None, **kwds):\n super(InputWidgetSingle, self).__init__(parent=parent, dataSetCallback=dataSetCallback, defaultValue=defaultValue, userStructClass=userStructClass, **kwds)\n # from widget\n self.bWidgetSet = False\n self.gridLayout = QGridLayout(self)\n self.gridLayout.setSpacing(1)\n self.gridLayout.setContentsMargins(0, 0, 0, 0)\n self.gridLayout.setObjectName(\"gridLayout\")\n self.horizontalLayout = QHBoxLayout()\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n\n spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)\n self.horizontalLayout.addItem(spacerItem)\n self.pbReset = QPushButton(self)\n self.pbReset.setMaximumSize(QtCore.QSize(25, 25))\n self.pbReset.setText(\"\")\n self.pbReset.setObjectName(\"pbReset\")\n self.pbReset.setIcon(QtGui.QIcon(\":/icons/resources/reset.png\"))\n self.horizontalLayout.addWidget(self.pbReset)\n self.pbReset.clicked.connect(self.onResetValue)\n\n self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1)\n self._index = 0\n\n def setWidget(self, widget):\n self.horizontalLayout.insertWidget(self._index, widget)\n\n\nclass ExecInputWidget(InputWidgetSingle):\n \"\"\"docstring for ExecInputWidget\"\"\"\n def __init__(self, parent=None, **kwds):\n super(ExecInputWidget, self).__init__(parent=parent, **kwds)\n self.pb = QPushButton('execute', self)\n self.setWidget(self.pb)\n self.pb.clicked.connect(self.dataSetCallback)\n self.pbReset.deleteLater()\n def setObjectName(self,name):\n super(ExecInputWidget, self).setObjectName(name)\n self.pb.setText(name.split(\".\")[-1])\n\nclass EnumInputWidget(InputWidgetSingle):\n \"\"\"\n Enum input widget\n \"\"\"\n def __init__(self, parent=None, **kwds):\n super(EnumInputWidget, self).__init__(parent=parent, **kwds)\n # self._userStruct = kwds['userStructClass']\n self.cb = QComboBox(self)\n self.setWidget(self.cb)\n for i in list(kwds['userStructClass']):\n self.cb.addItem(i.name, i.value)\n self.cb.currentIndexChanged[int].connect(self.dataSetCallback)\n\n def setWidgetValue(self, val):\n self.cb.setCurrentIndex(val)\n\n\nclass FloatInputWidget(InputWidgetSingle):\n \"\"\"\n Floating point data input widget\n \"\"\"\n\n def __init__(self, parent=None, **kwds):\n super(FloatInputWidget, self).__init__(parent=parent, **kwds)\n self.sb = QDoubleSpinBox(self)\n _configDoubleSpinBox(self.sb)\n self.setWidget(self.sb)\n # when spin box updated call setter function\n self.sb.valueChanged.connect(lambda val: self.dataSetCallback(val))\n\n def setWidgetValue(self, val):\n self.sb.setValue(float(val))\n\n\nclass IntInputWidget(InputWidgetSingle):\n \"\"\"\n Decimal number input widget\n \"\"\"\n def __init__(self, parent=None, **kwds):\n super(IntInputWidget, self).__init__(parent=parent, **kwds)\n self.sb = QSpinBox(self)\n _configIntSpinBox(self.sb)\n self.setWidget(self.sb)\n self.sb.valueChanged.connect(lambda val: self.dataSetCallback(val))\n\n def setWidgetValue(self, val):\n self.sb.setValue(int(val))\n\n\nclass NoneInputWidget(InputWidgetSingle):\n \"\"\"\n String data input widget\n \"\"\"\n def __init__(self, parent=None, **kwds):\n super(NoneInputWidget, self).__init__(parent=parent, **kwds)\n self.le = QLineEdit(self)\n self.le.setContextMenuPolicy(QtCore.Qt.NoContextMenu)\n self.setWidget(self.le)\n self.le.textChanged.connect(lambda val: self.dataSetCallback(val))\n self.le.setEnabled(False)\n\n def setWidgetValue(self, val):\n self.le.setText(str(val))\n\nclass StringInputWidget(InputWidgetSingle):\n \"\"\"\n String data input widget\n \"\"\"\n def __init__(self, parent=None, **kwds):\n super(StringInputWidget, self).__init__(parent=parent, **kwds)\n self.le = QLineEdit(self)\n self.le.setContextMenuPolicy(QtCore.Qt.NoContextMenu)\n self.setWidget(self.le)\n self.le.textChanged.connect(lambda val: self.dataSetCallback(val))\n\n def setWidgetValue(self, val):\n self.le.setText(str(val))\n\n\nclass BoolInputWidget(InputWidgetSingle):\n \"\"\"Boolean data input widget\"\"\"\n def __init__(self, parent=None, **kwds):\n super(BoolInputWidget, self).__init__(parent=parent, **kwds)\n self.cb = QCheckBox(self)\n self.setWidget(self.cb)\n self.cb.stateChanged.connect(lambda val: self.dataSetCallback(bool(val)))\n\n def setWidgetValue(self, val):\n if bool(val):\n self.cb.setCheckState(QtCore.Qt.Checked)\n else:\n self.cb.setCheckState(QtCore.Qt.Unchecked)\n\n\nclass FloatVector3InputWidget(InputWidgetRaw, FloatVector3InputWidget_ui.Ui_Form):\n \"\"\"Vector3 data input widget\"\"\"\n def __init__(self, **kwds):\n super(FloatVector3InputWidget, self).__init__(**kwds)\n self.setupUi(self)\n self._configSpinBoxes()\n self.dsbX.valueChanged.connect(self._onDataChangedX)\n self.dsbY.valueChanged.connect(self._onDataChangedY)\n self.dsbZ.valueChanged.connect(self._onDataChangedZ)\n self.pbReset.clicked.connect(self.onResetValue)\n\n def asDataTypeClass(self):\n return pyrr.Vector3([self.dsbX.value(), self.dsbY.value(), self.dsbZ.value()])\n\n def _configSpinBoxes(self):\n self.dsbX.setDecimals(FLOAT_DECIMALS)\n self.dsbY.setDecimals(FLOAT_DECIMALS)\n self.dsbZ.setDecimals(FLOAT_DECIMALS)\n\n self.dsbX.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbY.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbZ.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n\n self.dsbX.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbY.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbZ.setSingleStep(FLOAT_SINGLE_STEP)\n\n def _onDataChangedX(self, val):\n v = self.asDataTypeClass()\n v.x = val\n self.dataSetCallback(v)\n\n def _onDataChangedY(self, val):\n v = self.asDataTypeClass()\n v.y = val\n self.dataSetCallback(v)\n\n def _onDataChangedZ(self, val):\n v = self.asDataTypeClass()\n v.z = val\n self.dataSetCallback(v)\n\n def setWidgetValue(self, val):\n self.dsbX.setValue(val.x)\n self.dsbY.setValue(val.y)\n self.dsbZ.setValue(val.z)\n\n\nclass FloatVector4InputWidget(InputWidgetRaw, FloatVector4InputWidget_ui.Ui_Form):\n \"\"\"Vector4 data input widget\"\"\"\n def __init__(self, **kwds):\n super(FloatVector4InputWidget, self).__init__(**kwds)\n self.setupUi(self)\n self._configSpinBoxes()\n self.dsbX.valueChanged.connect(self._onDataChangedX)\n self.dsbY.valueChanged.connect(self._onDataChangedY)\n self.dsbZ.valueChanged.connect(self._onDataChangedZ)\n self.dsbW.valueChanged.connect(self._onDataChangedW)\n self.pbReset.clicked.connect(self.onResetValue)\n\n def asDataTypeClass(self):\n return pyrr.Vector4([self.dsbX.value(), self.dsbY.value(), self.dsbZ.value(), self.dsbW.value()])\n\n def _configSpinBoxes(self):\n self.dsbX.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbY.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbZ.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbW.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n self.dsbX.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbY.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbZ.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbW.setSingleStep(FLOAT_SINGLE_STEP)\n self.dsbX.setDecimals(FLOAT_DECIMALS)\n self.dsbY.setDecimals(FLOAT_DECIMALS)\n self.dsbZ.setDecimals(FLOAT_DECIMALS)\n self.dsbW.setDecimals(FLOAT_DECIMALS)\n\n def _onDataChangedX(self, val):\n v = self.asDataTypeClass()\n v.x = val\n self.dataSetCallback(v)\n\n def _onDataChangedY(self, val):\n v = self.asDataTypeClass()\n v.y = val\n self.dataSetCallback(v)\n\n def _onDataChangedZ(self, val):\n v = self.asDataTypeClass()\n v.z = val\n self.dataSetCallback(v)\n\n def _onDataChangedW(self, val):\n v = self.asDataTypeClass()\n v.w = val\n self.dataSetCallback(v)\n\n def setWidgetValue(self, val):\n self.dsbX.setValue(val.x)\n self.dsbY.setValue(val.y)\n self.dsbZ.setValue(val.z)\n self.dsbW.setValue(val.w)\n\n\nclass QuatInputWidget(FloatVector4InputWidget):\n \"\"\"Quaternion data input widget\"\"\"\n def __init__(self, **kwds):\n super(QuatInputWidget, self).__init__(**kwds)\n\n def asDataTypeClass(self):\n return pyrr.Quaternion([self.dsbX.value(), self.dsbY.value(), self.dsbZ.value(), self.dsbW.value()])\n\n\nclass Matrix33InputWidget(InputWidgetRaw, Matrix33InputWidget_ui.Ui_Form):\n \"\"\"Matrix33 data input widget\"\"\"\n def __init__(self, parent=None, **kwds):\n super(Matrix33InputWidget, self).__init__(parent=parent, **kwds)\n self.setupUi(self)\n self._configSpinBoxes()\n\n self.dsbm11.valueChanged.connect(self.m11Changed)\n self.dsbm12.valueChanged.connect(self.m12Changed)\n self.dsbm13.valueChanged.connect(self.m13Changed)\n\n self.dsbm21.valueChanged.connect(self.m21Changed)\n self.dsbm22.valueChanged.connect(self.m22Changed)\n self.dsbm23.valueChanged.connect(self.m23Changed)\n\n self.dsbm31.valueChanged.connect(self.m31Changed)\n self.dsbm32.valueChanged.connect(self.m32Changed)\n self.dsbm33.valueChanged.connect(self.m33Changed)\n\n self.pbReset.clicked.connect(self.onResetValue)\n\n def asDataTypeClass(self):\n return pyrr.Matrix33([\n [self.dsbm11.value(), self.dsbm12.value(), self.dsbm13.value()],\n [self.dsbm21.value(), self.dsbm22.value(), self.dsbm23.value()],\n [self.dsbm31.value(), self.dsbm32.value(), self.dsbm33.value()]\n ])\n\n def _configSpinBoxes(self):\n ls = [self.dsbm11, self.dsbm12, self.dsbm13,\n self.dsbm21, self.dsbm22, self.dsbm23,\n self.dsbm31, self.dsbm32, self.dsbm33]\n for sb in ls:\n sb.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n sb.setSingleStep(FLOAT_SINGLE_STEP)\n sb.setDecimals(FLOAT_DECIMALS)\n\n def m11Changed(self, val):\n m = self.asDataTypeClass()\n m.m11 = val\n self.dataSetCallback(m)\n\n def m12Changed(self, val):\n m = self.asDataTypeClass()\n m.m12 = val\n self.dataSetCallback(m)\n\n def m13Changed(self, val):\n m = self.asDataTypeClass()\n m.m13 = val\n self.dataSetCallback(m)\n\n def m21Changed(self, val):\n m = self.asDataTypeClass()\n m.m21 = val\n self.dataSetCallback(m)\n\n def m22Changed(self, val):\n m = self.asDataTypeClass()\n m.m22 = val\n self.dataSetCallback(m)\n\n def m23Changed(self, val):\n m = self.asDataTypeClass()\n m.m23 = val\n self.dataSetCallback(m)\n\n def m31Changed(self, val):\n m = self.asDataTypeClass()\n m.m31 = val\n self.dataSetCallback(m)\n\n def m32Changed(self, val):\n m = self.asDataTypeClass()\n m.m32 = val\n self.dataSetCallback(m)\n\n def m33Changed(self, val):\n m = self.asDataTypeClass()\n m.m33 = val\n self.dataSetCallback(m)\n\n def setWidgetValue(self, val):\n self.dsbm11.setValue(val.m11)\n self.dsbm12.setValue(val.m12)\n self.dsbm13.setValue(val.m13)\n\n self.dsbm21.setValue(val.m21)\n self.dsbm22.setValue(val.m22)\n self.dsbm23.setValue(val.m23)\n\n self.dsbm31.setValue(val.m31)\n self.dsbm32.setValue(val.m32)\n self.dsbm33.setValue(val.m33)\n\n\nclass Matrix44InputWidget(InputWidgetRaw, Matrix44InputWidget_ui.Ui_Form):\n \"\"\"Matrix44 data input widget\"\"\"\n def __init__(self, parent=None, **kwds):\n super(Matrix44InputWidget, self).__init__(parent=parent, **kwds)\n self.setupUi(self)\n self._configSpinBoxes()\n\n self.dsbm11.valueChanged.connect(self.m11Changed)\n self.dsbm12.valueChanged.connect(self.m12Changed)\n self.dsbm13.valueChanged.connect(self.m13Changed)\n self.dsbm14.valueChanged.connect(self.m14Changed)\n\n self.dsbm21.valueChanged.connect(self.m21Changed)\n self.dsbm22.valueChanged.connect(self.m22Changed)\n self.dsbm23.valueChanged.connect(self.m23Changed)\n self.dsbm24.valueChanged.connect(self.m24Changed)\n\n self.dsbm31.valueChanged.connect(self.m31Changed)\n self.dsbm32.valueChanged.connect(self.m32Changed)\n self.dsbm33.valueChanged.connect(self.m33Changed)\n self.dsbm34.valueChanged.connect(self.m34Changed)\n\n self.dsbm41.valueChanged.connect(self.m41Changed)\n self.dsbm42.valueChanged.connect(self.m42Changed)\n self.dsbm43.valueChanged.connect(self.m43Changed)\n self.dsbm44.valueChanged.connect(self.m44Changed)\n\n self.pbReset.clicked.connect(self.onResetValue)\n\n def asDataTypeClass(self):\n return pyrr.Matrix44([\n [self.dsbm11.value(), self.dsbm12.value(), self.dsbm13.value(), self.dsbm14.value()],\n [self.dsbm21.value(), self.dsbm22.value(), self.dsbm23.value(), self.dsbm24.value()],\n [self.dsbm31.value(), self.dsbm32.value(), self.dsbm33.value(), self.dsbm34.value()],\n [self.dsbm41.value(), self.dsbm42.value(), self.dsbm43.value(), self.dsbm44.value()]\n ])\n\n def _configSpinBoxes(self):\n ls = [self.dsbm11, self.dsbm12, self.dsbm13, self.dsbm14,\n self.dsbm21, self.dsbm22, self.dsbm23, self.dsbm24,\n self.dsbm31, self.dsbm32, self.dsbm33, self.dsbm34,\n self.dsbm41, self.dsbm42, self.dsbm43, self.dsbm44]\n for sb in ls:\n sb.setRange(FLOAT_RANGE_MIN, FLOAT_RANGE_MAX)\n sb.setSingleStep(FLOAT_SINGLE_STEP)\n sb.setDecimals(FLOAT_DECIMALS)\n\n def m11Changed(self, val):\n m = self.asDataTypeClass()\n m.m11 = val\n self.dataSetCallback(m)\n\n def m12Changed(self, val):\n m = self.asDataTypeClass()\n m.m12 = val\n self.dataSetCallback(m)\n\n def m13Changed(self, val):\n m = self.asDataTypeClass()\n m.m13 = val\n self.dataSetCallback(m)\n\n def m14Changed(self, val):\n m = self.asDataTypeClass()\n m.m14 = val\n self.dataSetCallback(m)\n\n def m21Changed(self, val):\n m = self.asDataTypeClass()\n m.m21 = val\n self.dataSetCallback(m)\n\n def m22Changed(self, val):\n m = self.asDataTypeClass()\n m.m22 = val\n self.dataSetCallback(m)\n\n def m23Changed(self, val):\n m = self.asDataTypeClass()\n m.m23 = val\n self.dataSetCallback(m)\n\n def m24Changed(self, val):\n m = self.asDataTypeClass()\n m.m24 = val\n self.dataSetCallback(m)\n\n def m31Changed(self, val):\n m = self.asDataTypeClass()\n m.m31 = val\n self.dataSetCallback(m)\n\n def m32Changed(self, val):\n m = self.asDataTypeClass()\n m.m32 = val\n self.dataSetCallback(m)\n\n def m33Changed(self, val):\n m = self.asDataTypeClass()\n m.m33 = val\n self.dataSetCallback(m)\n\n def m34Changed(self, val):\n m = self.asDataTypeClass()\n m.m34 = val\n self.dataSetCallback(m)\n\n def m41Changed(self, val):\n m = self.asDataTypeClass()\n m.m41 = val\n self.dataSetCallback(m)\n\n def m42Changed(self, val):\n m = self.asDataTypeClass()\n m.m42 = val\n self.dataSetCallback(m)\n\n def m43Changed(self, val):\n m = self.asDataTypeClass()\n m.m43 = val\n self.dataSetCallback(m)\n\n def m44Changed(self, val):\n m = self.asDataTypeClass()\n m.m44 = val\n self.dataSetCallback(m)\n\n def setWidgetValue(self, val):\n self.dsbm11.setValue(val.m11)\n self.dsbm12.setValue(val.m12)\n self.dsbm13.setValue(val.m13)\n self.dsbm14.setValue(val.m14)\n\n self.dsbm21.setValue(val.m21)\n self.dsbm22.setValue(val.m22)\n self.dsbm23.setValue(val.m23)\n self.dsbm24.setValue(val.m24)\n\n self.dsbm31.setValue(val.m31)\n self.dsbm32.setValue(val.m32)\n self.dsbm33.setValue(val.m33)\n self.dsbm34.setValue(val.m34)\n\n self.dsbm41.setValue(val.m41)\n self.dsbm42.setValue(val.m42)\n self.dsbm43.setValue(val.m43)\n self.dsbm44.setValue(val.m44)\n\n\ndef getInputWidget(dataType, dataSetter, defaultValue, userStructClass):\n '''\n factory method\n '''\n if dataType == DataTypes.Float:\n return FloatInputWidget(dataSetCallback=dataSetter, defaultValue=defaultValue)\n if dataType == DataTypes.Int:\n return IntInputWidget(dataSetCallback=dataSetter, defaultValue=defaultValue)\n if dataType == DataTypes.String:\n return StringInputWidget(dataSetCallback=dataSetter, defaultValue=defaultValue)\n if dataType == DataTypes.Bool:\n return BoolInputWidget(dataSetCallback=dataSetter, defaultValue=defaultValue)\n if dataType == DataTypes.FloatVector3:\n return FloatVector3InputWidget(dataSetCallback=dataSetter, defaultValue=defaultValue)\n if dataType == DataTypes.FloatVector4:\n return FloatVector4InputWidget(dataSetCallback=dataSetter, defaultValue=defaultValue)\n if dataType == DataTypes.Quaternion:\n return QuatInputWidget(dataSetCallback=dataSetter, defaultValue=defaultValue)\n if dataType == DataTypes.Matrix33:\n return Matrix33InputWidget(dataSetCallback=dataSetter, defaultValue=defaultValue)\n if dataType == DataTypes.Matrix44:\n return Matrix44InputWidget(dataSetCallback=dataSetter, defaultValue=defaultValue)\n if dataType == DataTypes.Exec:\n return ExecInputWidget(dataSetCallback=dataSetter, defaultValue=None)\n if dataType == DataTypes.Enum:\n return EnumInputWidget(dataSetCallback=dataSetter, defaultValue=defaultValue, userStructClass=userStructClass)\n \n return NoneInputWidget(dataSetCallback=dataSetter, defaultValue=defaultValue)\n", "step-ids": [ 59, 60, 62, 81, 103 ] }
[ 59, 60, 62, 81, 103 ]
from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtWidgets import QLineEdit, QRadioButton, QPushButton, QTableWidgetItem, QTableWidget, QApplication, QMainWindow, QDateEdit, QLabel, QDialog, QTextEdit, QCheckBox from PyQt5.QtCore import QDate, QTime, QDateTime, Qt from OOPCourseWorkTwo.GUI.SingleAnswerQuestionDialog import Ui_SingleAnswerQuestionDialog from OOPCourseWorkTwo.GUI.MultipleAnswersQuestionDialog import Ui_MultipleAnswersQuestionDialog from OOPCourseWorkTwo.GUI.EssayQuestionDialog import Ui_EssayQuestionDialog from OOPCourseWorkTwo.GUI.MarkingEssayQuestionDialog import Ui_MarkingEssayQuestionDialog class TeacherGUI(): def __init__(self): pass @classmethod def setup(cls, ui_mainwindow): cls.__ui_mainwindow = ui_mainwindow @classmethod def display_all_active_school_classes(cls, school_classes): cls.__ui_mainwindow.tableWidget_14.clear() row = 0 col = 0 for (school_class_id, ) in school_classes: school_class_text = "Class " + str(school_class_id) school_class_item = QTableWidgetItem(school_class_text) cls.__ui_mainwindow.tableWidget_14.setItem(row, col, school_class_item) if (col >= 4): col = 0 row += 1 else: col += 1 @classmethod def display_all_exams(cls, all_exams): cls.__ui_mainwindow.tableWidget_5.clear() row = 0 col = 0 for (exam_id, ) in all_exams: exam_text = "Exam " + str(exam_id) exam_item = QTableWidgetItem(exam_text) cls.__ui_mainwindow.tableWidget_5.setItem(row, col, exam_item) if (col >= 9): col = 0 row += 1 else: col += 1 @classmethod def display_not_completed_exams(cls, not_completed_exams): cls.__ui_mainwindow.tableWidget_16.clear() row = 0 col = 0 for (exam_id, ) in not_completed_exams: exam_text = "Exam " + str(exam_id) exam_item = QTableWidgetItem(exam_text) cls.__ui_mainwindow.tableWidget_16.setItem(row, col, exam_item) if (col >= 6): col = 0 row += 1 else: col += 1 @classmethod def display_ready_to_be_marked_exams(cls, ready_to_be_marked_exams): cls.__ui_mainwindow.tableWidget_17.clear() row = 0 col = 0 for (exam_id, ) in ready_to_be_marked_exams: exam_text = "Exam " + str(exam_id) exam_item = QTableWidgetItem(exam_text) cls.__ui_mainwindow.tableWidget_17.setItem(row, col, exam_item) if (col >= 3): col = 0 row += 1 else: col += 1 @classmethod def display_single_answer_question_dialog_preview(cls): question_body = cls.__ui_mainwindow.textEdit.toPlainText() option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText() option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText() option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText() option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText() option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText() cls.__dialog = QtWidgets.QDialog() cls.__ui_dialog = Ui_SingleAnswerQuestionDialog() cls.__ui_dialog.setupUi(cls.__dialog) cls.__ui_dialog.label.setText(question_body) cls.__ui_dialog.label_3.setText("A " + option_A_text) cls.__ui_dialog.label_4.setText("B " + option_B_text) cls.__ui_dialog.label_5.setText("C " + option_C_text) cls.__ui_dialog.label_6.setText("D " + option_D_text) cls.__ui_dialog.label_7.setText("E " + option_E_text) cls.__dialog.show() cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog) @classmethod def display_multiple_answers_question_dialog_preview(cls): question_body = cls.__ui_mainwindow.textEdit_14.toPlainText() option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText() option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText() option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText() option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText() option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText() cls.__dialog = QtWidgets.QDialog() cls.__ui_dialog = Ui_MultipleAnswersQuestionDialog() cls.__ui_dialog.setupUi(cls.__dialog) cls.__ui_dialog.label.setText(question_body) cls.__ui_dialog.label_3.setText(option_A_text) cls.__ui_dialog.label_4.setText(option_B_text) cls.__ui_dialog.label_5.setText(option_C_text) cls.__ui_dialog.label_6.setText(option_D_text) cls.__ui_dialog.label_7.setText(option_E_text) cls.__dialog.show() cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog) @classmethod def display_essay_question_dialog_preview(cls): question_body = cls.__ui_mainwindow.textEdit_19.toPlainText() cls.__dialog = QtWidgets.QDialog() cls.__ui_dialog = Ui_EssayQuestionDialog() cls.__ui_dialog.setupUi(cls.__dialog) if (question_body == ""): cls.__ui_dialog.label.setText("Question Body") else: cls.__ui_dialog.label.setText(question_body) cls.__dialog.show() cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog) @classmethod def close_dialog(cls): cls.__dialog.close() @classmethod def get_single_answer_question_details(cls): question_body = cls.__ui_mainwindow.textEdit.toPlainText() if (question_body == ""): return None option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText() if (option_A_text == ""): return None option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText() if (option_B_text == ""): return None option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText() if (option_C_text == ""): return None option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText() if (option_D_text == ""): return None option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText() if (option_E_text == ""): return None year_level_text = cls.__ui_mainwindow.lineEdit_3.text() if (year_level_text == ""): return None try: year_level = int(year_level_text) except: return None phrase_tag_text = cls.__ui_mainwindow.lineEdit_4.text() if (phrase_tag_text == ""): return None correct_answers_list = [] if (cls.__ui_mainwindow.radioButton.isChecked()): correct_answers_list.append("A") if (cls.__ui_mainwindow.radioButton_2.isChecked()): correct_answers_list.append("B") if (cls.__ui_mainwindow.radioButton_5.isChecked()): correct_answers_list.append("C") if (cls.__ui_mainwindow.radioButton_3.isChecked()): correct_answers_list.append("D") if (cls.__ui_mainwindow.radioButton_4.isChecked()): correct_answers_list.append("E") if (correct_answers_list == []): return None if (len(correct_answers_list) > 1): return None return (question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, year_level, phrase_tag_text, correct_answers_list) @classmethod def get_multiple_answers_question_details(cls): question_body = cls.__ui_mainwindow.textEdit_14.toPlainText() if (question_body == ""): return None option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText() if (option_A_text == ""): return None option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText() if (option_B_text == ""): return None option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText() if (option_C_text == ""): return None option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText() if (option_D_text == ""): return None option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText() if (option_E_text == ""): return None year_level_text = cls.__ui_mainwindow.lineEdit_25.text() if (year_level_text == ""): return None try: year_level = int(year_level_text) except: return None phrase_tag_text = cls.__ui_mainwindow.lineEdit_7.text() if (phrase_tag_text == ""): return None correct_answers_list = [] if (cls.__ui_mainwindow.checkBox.isChecked()): correct_answers_list.append("A") if (cls.__ui_mainwindow.checkBox_2.isChecked()): correct_answers_list.append("B") if (cls.__ui_mainwindow.checkBox_3.isChecked()): correct_answers_list.append("C") if (cls.__ui_mainwindow.checkBox_4.isChecked()): correct_answers_list.append("D") if (cls.__ui_mainwindow.checkBox_5.isChecked()): correct_answers_list.append("E") if (correct_answers_list == []): return None if (len(correct_answers_list) > 4): return None return (question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, year_level, phrase_tag_text, correct_answers_list) @classmethod def get_essay_question_details(cls): question_body = cls.__ui_mainwindow.textEdit_19.toPlainText() if (question_body == ""): return None year_level_text = cls.__ui_mainwindow.lineEdit_26.text() if (year_level_text == ""): return None try: year_level = int(year_level_text) except: return None phrase_tag_text = cls.__ui_mainwindow.lineEdit_27.text() if (phrase_tag_text == ""): return None return (question_body, year_level, phrase_tag_text) @classmethod def display_all_active_questions(cls, active_questions_tuple): row = 0 col = 0 for question_pk_tuple in active_questions_tuple: question_pk = question_pk_tuple[0] question_text = "Question " + str(question_pk) question_item = QTableWidgetItem(question_text) cls.__ui_mainwindow.tableWidget.setItem(row, col, question_item) if (col >= 7): col = 0 row += 1 else: col += 1 @classmethod def display_create_single_answer_question_success(cls): cls.__ui_mainwindow.label_4.setText("Create Single Answer Question Success") @classmethod def display_invalid_single_answer_question_creation_message(cls): cls.__ui_mainwindow.label_4.setText("Invalid Single Answer Question Creation") @classmethod def display_create_multiple_answers_question_success(cls): cls.__ui_mainwindow.label_11.setText("Create Multiple Answers Question Success") @classmethod def display_invalid_multiple_answers_question_creation_message(cls): cls.__ui_mainwindow.label_11.setText("Invalid Multiple Answers Question Creation") @classmethod def display_invalid_essay_question_creation_message(cls): cls.__ui_mainwindow.label_42.setText("Invalid Essay Question Creation") @classmethod def display_create_essay_question_success(cls): cls.__ui_mainwindow.label_42.setText("Create Essay Question Success") @classmethod def display_invalid_modification_message(cls): cls.__ui_mainwindow.label_57.setText("Invalid Modification") @classmethod def refresh_create_single_answer_question_page(cls): cls.__ui_mainwindow.textEdit.clear() cls.__ui_mainwindow.textEdit_2.clear() cls.__ui_mainwindow.textEdit_3.clear() cls.__ui_mainwindow.textEdit_4.clear() cls.__ui_mainwindow.textEdit_5.clear() cls.__ui_mainwindow.textEdit_6.clear() cls.__ui_mainwindow.lineEdit_3.clear() cls.__ui_mainwindow.lineEdit_4.clear() cls.__ui_mainwindow.radioButton.setChecked(False) cls.__ui_mainwindow.radioButton_2.setChecked(False) cls.__ui_mainwindow.radioButton_3.setChecked(False) cls.__ui_mainwindow.radioButton_4.setChecked(False) cls.__ui_mainwindow.radioButton_5.setChecked(False) @classmethod def refresh_create_multiple_answers_question_page(cls): cls.__ui_mainwindow.textEdit_14.clear() cls.__ui_mainwindow.textEdit_13.clear() cls.__ui_mainwindow.textEdit_15.clear() cls.__ui_mainwindow.textEdit_16.clear() cls.__ui_mainwindow.textEdit_17.clear() cls.__ui_mainwindow.textEdit_18.clear() cls.__ui_mainwindow.lineEdit_25.clear() cls.__ui_mainwindow.lineEdit_7.clear() cls.__ui_mainwindow.checkBox.setChecked(False) cls.__ui_mainwindow.checkBox_2.setChecked(False) cls.__ui_mainwindow.checkBox_3.setChecked(False) cls.__ui_mainwindow.checkBox_4.setChecked(False) cls.__ui_mainwindow.checkBox_5.setChecked(False) @classmethod def refresh_view_or_modify_question_page(cls): cls.__ui_mainwindow.lineEdit_5.clear() cls.__ui_mainwindow.label_45.setText("Question ID: ") cls.__ui_mainwindow.label_47.setText("Question Type: ") cls.__ui_mainwindow.label_57.clear() cls.__ui_mainwindow.label_12.clear() cls.__ui_mainwindow.textEdit_7.clear() cls.__ui_mainwindow.textEdit_8.clear() cls.__ui_mainwindow.textEdit_9.clear() cls.__ui_mainwindow.textEdit_10.clear() cls.__ui_mainwindow.textEdit_11.clear() cls.__ui_mainwindow.textEdit_20.clear() cls.__ui_mainwindow.lineEdit_6.clear() cls.__ui_mainwindow.lineEdit_8.clear() cls.__ui_mainwindow.lineEdit_28.clear() cls.__ui_mainwindow.radioButton_6.setDisabled(False) cls.__ui_mainwindow.radioButton_7.setDisabled(False) cls.__ui_mainwindow.radioButton_8.setDisabled(False) cls.__ui_mainwindow.radioButton_9.setDisabled(False) cls.__ui_mainwindow.radioButton_10.setDisabled(False) cls.__ui_mainwindow.textEdit_8.setDisabled(False) cls.__ui_mainwindow.textEdit_9.setDisabled(False) cls.__ui_mainwindow.textEdit_10.setDisabled(False) cls.__ui_mainwindow.textEdit_11.setDisabled(False) cls.__ui_mainwindow.textEdit_20.setDisabled(False) cls.__ui_mainwindow.radioButton_6.setAutoExclusive(False) cls.__ui_mainwindow.radioButton_6.setChecked(False) cls.__ui_mainwindow.radioButton_7.setAutoExclusive(False) cls.__ui_mainwindow.radioButton_7.setChecked(False) cls.__ui_mainwindow.radioButton_8.setAutoExclusive(False) cls.__ui_mainwindow.radioButton_8.setChecked(False) cls.__ui_mainwindow.radioButton_9.setAutoExclusive(False) cls.__ui_mainwindow.radioButton_9.setChecked(False) cls.__ui_mainwindow.radioButton_10.setAutoExclusive(False) cls.__ui_mainwindow.radioButton_10.setChecked(False) @classmethod def refresh_create_essay_question_page(cls): cls.__ui_mainwindow.textEdit_19.clear() cls.__ui_mainwindow.lineEdit_26.clear() cls.__ui_mainwindow.lineEdit_27.clear() @classmethod def refresh_create_exam_page(cls): cls.__ui_mainwindow.tableWidget_3.clear() cls.__ui_mainwindow.tableWidget_4.clear() cls.__ui_mainwindow.lineEdit_10.clear() cls.__ui_mainwindow.lineEdit_11.clear() cls.__ui_mainwindow.lineEdit_12.clear() cls.__ui_mainwindow.lineEdit_13.clear() @classmethod def get_question_id_to_load(cls): question_id_text = cls.__ui_mainwindow.lineEdit_5.text() try: question_id = int(question_id_text) return question_id except: return None @classmethod def load_single_answer_question_details(cls, question_details): question_id = question_details[0] question_type = question_details[1] points = question_details[2] year_level = question_details[3] question_tag = question_details[4] question_body = question_details[5] option_A_text = question_details[6] option_B_text = question_details[7] option_C_text = question_details[8] option_D_text = question_details[9] option_E_text = question_details[10] correct_answer = question_details[11] cls.__ui_mainwindow.label_45.setText("Question ID: " + str(question_id)) cls.__ui_mainwindow.label_47.setText("Question Type: " + str(question_type)) cls.__ui_mainwindow.textEdit_7.setText(question_body) cls.__ui_mainwindow.textEdit_8.setText(option_A_text) cls.__ui_mainwindow.textEdit_9.setText(option_B_text) cls.__ui_mainwindow.textEdit_10.setText(option_C_text) cls.__ui_mainwindow.textEdit_11.setText(option_D_text) cls.__ui_mainwindow.textEdit_20.setText(option_E_text) cls.__ui_mainwindow.lineEdit_6.setText(str(year_level)) cls.__ui_mainwindow.lineEdit_8.setText(question_tag) cls.__ui_mainwindow.lineEdit_28.setText(str(points)) if (correct_answer == "A"): cls.__ui_mainwindow.radioButton_6.setChecked(True) elif (correct_answer == "B"): cls.__ui_mainwindow.radioButton_7.setChecked(True) elif (correct_answer == "C"): cls.__ui_mainwindow.radioButton_8.setChecked(True) elif (correct_answer == "D"): cls.__ui_mainwindow.radioButton_9.setChecked(True) elif (correct_answer == "E"): cls.__ui_mainwindow.radioButton_10.setChecked(True) @classmethod def load_multiple_answers_question_details(cls, question_details): question_id = question_details[0] question_type = question_details[1] points = question_details[2] year_level = question_details[3] question_tag = question_details[4] question_body = question_details[5] option_A_text = question_details[6] option_B_text = question_details[7] option_C_text = question_details[8] option_D_text = question_details[9] option_E_text = question_details[10] correct_answers = question_details[11] cls.__ui_mainwindow.label_45.setText("Question ID: " + str(question_id)) cls.__ui_mainwindow.label_47.setText("Question Type: " + str(question_type)) cls.__ui_mainwindow.textEdit_7.setText(question_body) cls.__ui_mainwindow.textEdit_8.setText(option_A_text) cls.__ui_mainwindow.textEdit_9.setText(option_B_text) cls.__ui_mainwindow.textEdit_10.setText(option_C_text) cls.__ui_mainwindow.textEdit_11.setText(option_D_text) cls.__ui_mainwindow.textEdit_20.setText(option_E_text) cls.__ui_mainwindow.lineEdit_6.setText(str(year_level)) cls.__ui_mainwindow.lineEdit_8.setText(question_tag) cls.__ui_mainwindow.lineEdit_28.setText(str(points)) if (correct_answers.count("A") == 1): cls.__ui_mainwindow.radioButton_6.setChecked(True) if (correct_answers.count("B") == 1): cls.__ui_mainwindow.radioButton_7.setChecked(True) if (correct_answers.count("C") == 1): cls.__ui_mainwindow.radioButton_8.setChecked(True) if (correct_answers.count("D") == 1): cls.__ui_mainwindow.radioButton_9.setChecked(True) if (correct_answers.count("E") == 1): cls.__ui_mainwindow.radioButton_10.setChecked(True) @classmethod def load_essay_question_details(cls, question_details): question_id = question_details[0] question_type = question_details[1] points = question_details[2] year_level = question_details[3] question_tag = question_details[4] question_body = question_details[5] cls.__ui_mainwindow.label_45.setText("Question ID: " + str(question_id)) cls.__ui_mainwindow.label_47.setText("Question Type: " + str(question_type)) cls.__ui_mainwindow.textEdit_7.setText(question_body) cls.__ui_mainwindow.radioButton_6.setDisabled(True) cls.__ui_mainwindow.radioButton_7.setDisabled(True) cls.__ui_mainwindow.radioButton_8.setDisabled(True) cls.__ui_mainwindow.radioButton_9.setDisabled(True) cls.__ui_mainwindow.radioButton_10.setDisabled(True) cls.__ui_mainwindow.textEdit_8.setDisabled(True) cls.__ui_mainwindow.textEdit_9.setDisabled(True) cls.__ui_mainwindow.textEdit_10.setDisabled(True) cls.__ui_mainwindow.textEdit_11.setDisabled(True) cls.__ui_mainwindow.textEdit_20.setDisabled(True) cls.__ui_mainwindow.lineEdit_6.setText(str(year_level)) cls.__ui_mainwindow.lineEdit_8.setText(question_tag) cls.__ui_mainwindow.lineEdit_28.setText(str(points)) @classmethod def display_question_id_invalid_to_load_message(cls): cls.__ui_mainwindow.label_12.setText("Invalid Question ID To Load") @classmethod def display_modification_success_message(cls): cls.__ui_mainwindow.label_57.setText("Modification Success") @classmethod def display_invalid_school_class_id_message(cls): cls.__ui_mainwindow.label_14.setText("Invalid School Class ID") cls.__ui_mainwindow.tableWidget_15.clear() @classmethod def get_question_type_to_modify(cls): question_type_text = cls.__ui_mainwindow.label_47.text() if (question_type_text == "Question Type: Single Answer"): return "Single Answer" elif (question_type_text == "Question Type: Multiple Answers"): return "Multiple Answers" elif (question_type_text == "Question Type: Essay"): return "Essay" @classmethod def get_single_answer_question_details_to_modify(cls): question_pk = cls.get_question_id_to_modify() question_type = cls.get_question_type_to_modify() points = int(cls.__ui_mainwindow.lineEdit_28.text()) year_level = int(cls.__ui_mainwindow.lineEdit_6.text()) question_tag = cls.__ui_mainwindow.lineEdit_8.text() question_body = cls.__ui_mainwindow.textEdit_7.toPlainText() option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText() option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText() option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText() option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText() option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText() correct_answer = cls.get_single_correct_answer_to_modify() if (correct_answer == None): return None return (question_pk, question_type, points, year_level, question_tag,question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, correct_answer) @classmethod def get_multiple_answers_question_details_to_modify(cls): question_pk = cls.get_question_id_to_modify() question_type = cls.get_question_type_to_modify() points = int(cls.__ui_mainwindow.lineEdit_28.text()) year_level = int(cls.__ui_mainwindow.lineEdit_6.text()) question_tag = cls.__ui_mainwindow.lineEdit_8.text() question_body = cls.__ui_mainwindow.textEdit_7.toPlainText() option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText() option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText() option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText() option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText() option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText() correct_answers = cls.get_multiple_correct_answers_to_modify() if (correct_answers == None): return None return (question_pk, question_type, points, year_level, question_tag,question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, correct_answers) @classmethod def get_essay_question_details_to_modify(cls): question_pk = cls.get_question_id_to_modify() question_type = cls.get_question_type_to_modify() try: points = int(cls.__ui_mainwindow.lineEdit_28.text()) except: return None try: year_level = int(cls.__ui_mainwindow.lineEdit_6.text()) except: return None question_tag = cls.__ui_mainwindow.lineEdit_8.text() if (question_tag == ""): return None question_body = cls.__ui_mainwindow.textEdit_7.toPlainText() if (question_body == ""): return None return (question_pk, question_type, points, year_level, question_tag, question_body) @classmethod def get_question_id_to_modify(cls): question_id_text = cls.__ui_mainwindow.label_45.text() question_id_text_split = question_id_text.split() question_id = int(question_id_text_split.pop()) return question_id @classmethod def get_single_correct_answer_to_modify(cls): correct_answer = "" if (cls.__ui_mainwindow.radioButton_6.isChecked()): correct_answer = correct_answer + "A" if (cls.__ui_mainwindow.radioButton_7.isChecked()): correct_answer = correct_answer + "B" if (cls.__ui_mainwindow.radioButton_8.isChecked()): correct_answer = correct_answer + "C" if (cls.__ui_mainwindow.radioButton_9.isChecked()): correct_answer = correct_answer + "D" if (cls.__ui_mainwindow.radioButton_10.isChecked()): correct_answer = correct_answer + "E" if (len(correct_answer) == 0): return None if (len(correct_answer) > 1): return None return correct_answer @classmethod def get_multiple_correct_answers_to_modify(cls): correct_answers = "" if (cls.__ui_mainwindow.radioButton_6.isChecked()): correct_answers = correct_answers + "A" if (cls.__ui_mainwindow.radioButton_7.isChecked()): correct_answers = correct_answers + "B" if (cls.__ui_mainwindow.radioButton_8.isChecked()): correct_answers = correct_answers + "C" if (cls.__ui_mainwindow.radioButton_9.isChecked()): correct_answers = correct_answers + "D" if (cls.__ui_mainwindow.radioButton_10.isChecked()): correct_answers = correct_answers + "E" if (len(correct_answers) == 0): return None if (len(correct_answers) > 4): return None return correct_answers @classmethod def get_school_class_id_to_view_students(cls): school_class_id_text = cls.__ui_mainwindow.lineEdit_9.text() try: school_class_id = int(school_class_id_text) return school_class_id except: return None @classmethod def display_school_class_details(cls, school_class_details): cls.__ui_mainwindow.tableWidget_15.clear() row = 0 col = 0 for (student, ) in school_class_details: student_item = QTableWidgetItem(student) cls.__ui_mainwindow.tableWidget_15.setItem(row, col, student_item) if (col >= 1): col = 0 row += 1 else: col += 1 @classmethod def refresh_view_school_class_details_page(cls): cls.__ui_mainwindow.label_14.clear() @classmethod def get_number_of_questions_in_current_exam(cls): number_of_questions = 0 row = 0 col = 0 for counter in range(10): if (cls.__ui_mainwindow.tableWidget_3.item(row, col) != None): number_of_questions += 1 row += 1 return number_of_questions @classmethod def get_number_of_school_classes_in_current_exam(cls): number_of_school_classes = 0 row = 0 col = 0 for counter in range(5): if (cls.__ui_mainwindow.tableWidget_4.item(row, col) != None): number_of_school_classes += 1 row += 1 return number_of_school_classes @classmethod def display_number_of_questions_full_in_current_exam_message(cls): cls.__ui_mainwindow.label_17.setText("Questions Are Full In Current Exam") @classmethod def display_number_of_school_classes_full_in_current_exam_message(cls): cls.__ui_mainwindow.label_17.setText("School Classes Are Full In Current Exam") @classmethod def display_no_question_in_current_exam_message(cls): cls.__ui_mainwindow.label_17.setText("No Question In Current Exam") @classmethod def display_no_school_class_in_current_exam_message(cls): cls.__ui_mainwindow.label_17.setText("No School Class In Current Exam") @classmethod def display_question_id_already_added_to_current_exam_message(cls): cls.__ui_mainwindow.label_17.setText("Question ID Already Added To Current Exam") @classmethod def display_school_class_id_already_added_to_current_exam_message(cls): cls.__ui_mainwindow.label_17.setText("School Class ID Already Added To Current Exam") @classmethod def display_question_id_invalid_message(cls): cls.__ui_mainwindow.label_17.setText("Question ID Invalid") @classmethod def display_school_class_id_invalid_message(cls): cls.__ui_mainwindow.label_17.setText("School CLass ID Invalid") @classmethod def display_question_id_not_already_in_current_exam_message(cls): cls.__ui_mainwindow.label_17.setText("Question ID Not Aleady In Current Exam") @classmethod def display_school_class_id_not_already_in_current_exam_message(cls): cls.__ui_mainwindow.label_17.setText("School Class ID Not Aleady In Current Exam") @classmethod def display_create_exam_success_message(cls): cls.__ui_mainwindow.label_17.setText("Create Exam Success") @classmethod def refresh_mark_exam_drop_box(cls): cls.__ui_mainwindow.tableWidget_19.clear() @classmethod def get_question_id_to_add_to_exam(cls): question_id_text = cls.__ui_mainwindow.lineEdit_10.text() try: question_id = int(question_id_text) return question_id except: return None @classmethod def get_school_class_id_to_add_to_exam(cls): school_class_id_text = cls.__ui_mainwindow.lineEdit_11.text() try: school_class_id = int(school_class_id_text) return school_class_id except: return None @classmethod def get_question_id_to_remove_from_exam(cls): question_id_text = cls.__ui_mainwindow.lineEdit_12.text() try: question_id = int(question_id_text) return question_id except: return None @classmethod def get_school_class_id_to_remove_from_exam(cls): school_class_id_text = cls.__ui_mainwindow.lineEdit_13.text() try: school_class_id = int(school_class_id_text) return school_class_id except: return None @classmethod def add_question_id_to_current_exam(cls, question_id): row = 0 col = 0 for counter in range(10): if (cls.__ui_mainwindow.tableWidget_3.item(row, col) == None): question_text = "Question " + str(question_id) question_item = QTableWidgetItem(question_text) cls.__ui_mainwindow.tableWidget_3.setItem(row, col, question_item) cls.__ui_mainwindow.lineEdit_10.clear() cls.__ui_mainwindow.label_17.clear() return row += 1 @classmethod def add_school_class_id_to_current_exam(cls, school_class_id): row = 0 col = 0 for counter in range(10): if (cls.__ui_mainwindow.tableWidget_4.item(row, col) == None): school_class_text = "CLass " + str(school_class_id) school_class_item = QTableWidgetItem(school_class_text) cls.__ui_mainwindow.tableWidget_4.setItem(row, col, school_class_item) cls.__ui_mainwindow.lineEdit_11.clear() cls.__ui_mainwindow.label_17.clear() return row += 1 @classmethod def remove_question_id_from_current_exam(cls, question_id): col = 0 for row in range(10): question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col) if (question_item != None): question_text = question_item.text() question_text_split = question_text.split(" ") question_id_in_exam = int(question_text_split.pop()) if (question_id_in_exam == question_id): cls.__ui_mainwindow.tableWidget_3.takeItem(row, col) cls.__ui_mainwindow.lineEdit_12.clear() cls.__ui_mainwindow.label_17.clear() return @classmethod def remove_school_class_id_from_current_exam(cls, school_class_id): col = 0 for row in range(5): school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col) if (school_class_item != None): school_class_text = school_class_item.text() school_class_text_split = school_class_text.split(" ") school_class_id_in_exam = int(school_class_text_split.pop()) if (school_class_id_in_exam == school_class_id): cls.__ui_mainwindow.tableWidget_4.takeItem(row, col) cls.__ui_mainwindow.lineEdit_13.clear() cls.__ui_mainwindow.label_17.clear() return @classmethod def is_question_id_already_added_to_current_exam(cls, question_id): string_of_question_ids_in_current_exam = cls.get_string_of_question_ids_in_current_exam() list_of_question_ids = string_of_question_ids_in_current_exam.split(" ") return list_of_question_ids.count(str(question_id)) == 1 @classmethod def is_school_class_id_already_added_to_current_exam(cls, school_class_id): string_of_school_classes_ids_in_current_exam = cls.get_string_of_school_classes_ids_in_current_exam() list_of_school_classes_ids = string_of_school_classes_ids_in_current_exam.split(" ") return list_of_school_classes_ids.count(str(school_class_id)) == 1 @classmethod def get_string_of_question_ids_in_current_exam(cls): string_of_question_ids = "" col = 0 for row in range(10): question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col) if (question_item != None): question_text = question_item.text() question_text_split = question_text.split(" ") question_id = question_text_split.pop() string_of_question_ids = string_of_question_ids + question_id + " " return string_of_question_ids.rstrip() @classmethod def get_string_of_school_classes_ids_in_current_exam(cls): string_of_school_classes_ids = "" col = 0 for row in range(10): school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col) if (school_class_item != None): school_class_text = school_class_item.text() school_class_text_split = school_class_text.split(" ") school_class_id = school_class_text_split.pop() string_of_school_classes_ids = string_of_school_classes_ids + school_class_id + " " return string_of_school_classes_ids.rstrip() @classmethod def get_exam_id_to_mark(cls): exam_item = cls.__ui_mainwindow.tableWidget_20.item(0, 0) exam_text = exam_item.text() exam_text_split = exam_text.split(" ") exam_id_text = exam_text_split.pop() return int(exam_id_text) @classmethod def display_exam_id_on_marking_exam_page(cls, exam_id): cls.__ui_mainwindow.label_49.setText("Exam ID: " + str(exam_id)) @classmethod def display_students_full_names_with_questions_ready_to_be_marked(cls, students_names_list): cls.__ui_mainwindow.tableWidget_6.clear() row = 0 col = 0 for student_name in students_names_list: student_item = QTableWidgetItem(student_name) cls.__ui_mainwindow.tableWidget_6.setItem(row, col, student_item) if (col >= 4): row += 1 col = 0 else: col += 1 @classmethod def get_student_name_to_mark_answers(cls): student_item = cls.__ui_mainwindow.tableWidget_19.item(0,0) student_name = student_item.text() return student_name @classmethod def get_exam_id_to_mark_student_answers(cls): exam_id_text = cls.__ui_mainwindow.label_49.text() exam_id_text_split = exam_id_text.split(" ") exam_id = exam_id_text_split.pop() return int(exam_id) @classmethod def display_exam_id_on_mark_student_answers_page(cls, exam_id): exam_id_text = "Exam ID: " + str(exam_id) cls.__ui_mainwindow.label_62.setText(exam_id_text) @classmethod def display_student_id_on_mark_student_answers_page(cls, student_id): student_id_text = "Student ID: " + str(student_id) cls.__ui_mainwindow.label_63.setText(student_id_text) @classmethod def display_student_name_on_mark_student_answers_page(cls,student_name): student_name_text = "Student Name: " + str(student_name) cls.__ui_mainwindow.label_50.setText(student_name_text) @classmethod def display_questions_ready_to_be_marked(cls, questions_ids_tuple): cls.__ui_mainwindow.tableWidget_25.clear() row = 0 col = 0 for (question_id,) in questions_ids_tuple: question_text = "Question " + str(question_id) question_item = QTableWidgetItem(question_text) cls.__ui_mainwindow.tableWidget_25.setItem(row, col, question_item) row += 1 @classmethod def get_question_id_to_mark(cls): question_item = cls.__ui_mainwindow.tableWidget_26.item(0,0) if (question_item == None): return None question_id_text = question_item.text() question_id_text_list = question_id_text.split(" ") question_id = question_id_text_list.pop() return int(question_id) @classmethod def get_exam_id_on_marking_question_page(cls): exam_id_text = cls.__ui_mainwindow.label_62.text() exam_id_text_list = exam_id_text.split(" ") exam_id = exam_id_text_list.pop() return int(exam_id) @classmethod def get_student_id_on_marking_question_page(cls): student_id_text = cls.__ui_mainwindow.label_63.text() student_id_text_list = student_id_text.split(" ") student_id = student_id_text_list.pop() return int(student_id) @classmethod def setup_essay_question_ui_dialog_to_mark(cls, question_details): question_body = question_details[0] student_answer = question_details[1] available_points = question_details[2] cls.__dialog = QtWidgets.QDialog() cls.__ui_dialog = Ui_MarkingEssayQuestionDialog() cls.__ui_dialog.setupUi(cls.__dialog) cls.__ui_dialog.label_2.setText(question_body) cls.__ui_dialog.label_3.setText(student_answer) cls.__ui_dialog.label_4.setText("Total Available Points: " + str(available_points)) cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog) cls.__dialog.show() return cls.__ui_dialog @classmethod def get_essay_question_marked_points(cls): points_text = cls.__ui_dialog.lineEdit.text() return int(points_text) @classmethod def refresh_drop_question_to_mark_box(cls): cls.__ui_mainwindow.tableWidget_26.clear() @classmethod def refresh_mark_student_questions_answers_page(cls): cls.__ui_mainwindow.label_62.clear() cls.__ui_mainwindow.label_63.clear() cls.__ui_mainwindow.label_50.clear() @classmethod def display_no_more_questions_to_mark_message(cls): cls.__ui_mainwindow.label_66.setText("No More Questions To Mark") @classmethod def display_marked_exams(cls, marked_exams_ids): cls.__ui_mainwindow.tableWidget_18.clear() row = 0 col = 0 for (exam_id,) in marked_exams_ids: exam_text = "Exam " + str(exam_id) exam_item = QTableWidgetItem(exam_text) cls.__ui_mainwindow.tableWidget_18.setItem(row, col, exam_item) if (col >= 4): row += 1 col = 0 else: col += 1 @classmethod def display_no_question_selected_to_mark_message(cls): cls.__ui_mainwindow.label_66.setText("No Question Selected To Mark") @classmethod def refresh_drop_student_to_mark_questions_box(cls): cls.__ui_mainwindow.tableWidget_19.clear() @classmethod def get_exam_id_to_release_result(cls): exam_item = cls.__ui_mainwindow.tableWidget_21.item(0,0) if (exam_item == None): return None exam_id_text = exam_item.text() exam_id_text_list = exam_id_text.split(" ") exam_id = exam_id_text_list.pop() return int(exam_id) @classmethod def display_result_released_exams(cls, result_released_exams_ids): cls.__ui_mainwindow.tableWidget_11.clear() row = 0 col = 0 for (exam_id,) in result_released_exams_ids: exam_text = "Exam " + str(exam_id) + " Result" exam_item = QTableWidgetItem(exam_text) cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_item) if (col >= 9): row += 1 col = 0 else: col += 1 @classmethod def refresh_drop_exam_to_release_result_box(cls): cls.__ui_mainwindow.tableWidget_21.clear() @classmethod def display_exam_results(cls, exam_results_ids): cls.__ui_mainwindow.tableWidget_11.clear() row = 0 col = 0 for (exam_result_id, ) in exam_results_ids: exam_result_text = "Exam " + str(exam_result_id) + " Result" exam_result_item = QTableWidgetItem(exam_result_text) cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_result_item) if (col >= 9): row += 1 col = 0 else: col += 1 @classmethod def get_exam_result_id_to_load_details(cls): exam_result_id_text = cls.__ui_mainwindow.lineEdit_22.text() return int(exam_result_id_text) @classmethod def display_school_classes_to_view_exam_result_details(cls, school_classes_ids): school_classes_ids_list = cls.make_string_to_list(school_classes_ids) cls.__ui_mainwindow.tableWidget_12.clear() row = 0 col = 0 for school_class_id in school_classes_ids_list: school_class_text = "Class " + str(school_class_id) school_class_item = QTableWidgetItem(school_class_text) cls.__ui_mainwindow.tableWidget_12.setItem(row, col, school_class_item) row += 1 @classmethod def display_exam_result_id_on_view_exam_result_details_page(cls, exam_result_id): cls.__ui_mainwindow.label_33.setText("Exam Result ID: " + str(exam_result_id)) @classmethod def get_school_class_id_to_view_exam_result(cls): school_class_id_text = cls.__ui_mainwindow.lineEdit_23.text() try: school_class_id = int(school_class_id_text) except: return None return school_class_id @classmethod def display_students_full_names_to_view_exam_result(cls, students_full_names): cls.__ui_mainwindow.tableWidget_13.clear() row = 0 col = 0 for (student_full_name, ) in students_full_names: student_item = QTableWidgetItem(student_full_name) cls.__ui_mainwindow.tableWidget_13.setItem(row, col, student_item) row += 1 @classmethod def get_student_full_name_to_view_exam_result(cls): student_item = cls.__ui_mainwindow.tableWidget_22.item(0, 0) student_name_text = student_item.text() return student_name_text @classmethod def get_exam_result_id_on_view_exam_result_page(cls): exam_result_id_text = cls.__ui_mainwindow.label_33.text() exam_result_id_text_list = exam_result_id_text.split(" ") exam_result_id = exam_result_id_text_list.pop() try: exam_result_id_int = int(exam_result_id) return exam_result_id_int except: return None @classmethod def display_student_exam_result_details(cls, exam_result_details): student_id = exam_result_details[0] student_full_name = exam_result_details[1] date_of_birth = exam_result_details[2] school_class_id = exam_result_details[3] exam_id = exam_result_details[4] total_available_points = exam_result_details[5] total_points_gained = exam_result_details[6] average_percentage_mark = exam_result_details[7] cls.__ui_mainwindow.label_58.setText(str(student_id)) cls.__ui_mainwindow.label_72.setText(str(student_full_name)) cls.__ui_mainwindow.label_75.setText(str(date_of_birth)) cls.__ui_mainwindow.label_76.setText(str(school_class_id)) cls.__ui_mainwindow.label_77.setText(str(exam_id)) cls.__ui_mainwindow.label_78.setText(str(total_available_points)) cls.__ui_mainwindow.label_79.setText(str(total_points_gained)) cls.__ui_mainwindow.label_80.setText(str(average_percentage_mark) + " %") @classmethod def get_exam_id_to_view_details(cls): exam_id_text = cls.__ui_mainwindow.lineEdit_14.text() if (exam_id_text == ""): return None try: exam_id = int(exam_id_text) return exam_id except: return None @classmethod def diaplay_exam_id_on_view_exam_details_page(cls, exam_id): cls.__ui_mainwindow.label_18.setText("Exam ID: " + str(exam_id)) @classmethod def display_questions_on_view_exam_details_page(cls, questions_ids): cls.__ui_mainwindow.tableWidget_7.clear() questions_ids_list = cls.make_string_to_list(questions_ids) row = 0 col = 0 for question_id in questions_ids_list: question_text = "Question " + str(question_id) question_item = QTableWidgetItem(question_text) cls.__ui_mainwindow.tableWidget_7.setItem(row, col, question_item) row += 1 @classmethod def display_first_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names): cls.display_first_school_class_id_on_view_exam_details_page(school_class_id) cls.__ui_mainwindow.tableWidget_27.clear() row = 0 col = 0 for (student_name, ) in students_full_names: student_item = QTableWidgetItem(student_name) cls.__ui_mainwindow.tableWidget_27.setItem(row, col, student_item) row += 1 @classmethod def display_first_school_class_id_on_view_exam_details_page(cls, school_class_id): cls.__ui_mainwindow.label_67.setText("CLass " + str(school_class_id)) @classmethod def display_second_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names): cls.display_second_school_class_id_on_view_exam_details_page(school_class_id) cls.__ui_mainwindow.tableWidget_28.clear() row = 0 col = 0 for (student_name, ) in students_full_names: student_item = QTableWidgetItem(student_name) cls.__ui_mainwindow.tableWidget_28.setItem(row, col, student_item) row += 1 @classmethod def display_second_school_class_id_on_view_exam_details_page(cls, school_class_id): cls.__ui_mainwindow.label_68.setText("CLass " + str(school_class_id)) @classmethod def display_third_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names): cls.display_third_school_class_id_on_view_exam_details_page(school_class_id) cls.__ui_mainwindow.tableWidget_29.clear() row = 0 col = 0 for (student_name, ) in students_full_names: student_item = QTableWidgetItem(student_name) cls.__ui_mainwindow.tableWidget_29.setItem(row, col, student_item) row += 1 @classmethod def display_third_school_class_id_on_view_exam_details_page(cls, school_class_id): cls.__ui_mainwindow.label_69.setText("CLass " + str(school_class_id)) @classmethod def display_fourth_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names): cls.display_fourth_school_class_id_on_view_exam_details_page(school_class_id) cls.__ui_mainwindow.tableWidget_30.clear() row = 0 col = 0 for (student_name, ) in students_full_names: student_item = QTableWidgetItem(student_name) cls.__ui_mainwindow.tableWidget_30.setItem(row, col, student_item) row += 1 @classmethod def display_fourth_school_class_id_on_view_exam_details_page(cls, school_class_id): cls.__ui_mainwindow.label_70.setText("CLass " + str(school_class_id)) @classmethod def display_fifth_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names): cls.display_fifth_school_class_id_on_view_exam_details_page(school_class_id) cls.__ui_mainwindow.tableWidget_31.clear() row = 0 col = 0 for (student_name, ) in students_full_names: student_item = QTableWidgetItem(student_name) cls.__ui_mainwindow.tableWidget_31.setItem(row, col, student_item) row += 1 @classmethod def display_fifth_school_class_id_on_view_exam_details_page(cls, school_class_id): cls.__ui_mainwindow.label_71.setText("CLass " + str(school_class_id)) @classmethod def make_string_to_list(cls, any_string): any_string = str(any_string) any_list = any_string.split(" ") return any_list @classmethod def refresh_drop_student_to_view_exam_result_details_box(cls): cls.__ui_mainwindow.tableWidget_22.clear() @classmethod def display_exam_result_id_invalid_message(cls): cls.__ui_mainwindow.label_32.setText("Exam Result ID Invalid") @classmethod def refresh_load_exam_result_details_page(cls): cls.__ui_mainwindow.label_33.clear() cls.__ui_mainwindow.tableWidget_12.clear() cls.__ui_mainwindow.lineEdit_23.clear() cls.__ui_mainwindow.tableWidget_13.clear() cls.__ui_mainwindow.tableWidget_22.clear() cls.__ui_mainwindow.label_58.clear() cls.__ui_mainwindow.label_72.clear() cls.__ui_mainwindow.label_75.clear() cls.__ui_mainwindow.label_76.clear() cls.__ui_mainwindow.label_77.clear() cls.__ui_mainwindow.label_78.clear() cls.__ui_mainwindow.label_79.clear() cls.__ui_mainwindow.label_80.clear() @classmethod def refresh_exam_result_id_validity_error_message(cls): cls.__ui_mainwindow.label_32.clear() @classmethod def display_school_class_id_invalid_to_view_result_message(cls): cls.__ui_mainwindow.label_81.setText("School Class ID Invalid To View") @classmethod def refresh_school_class_details_table_on_view_exam_result_page(cls): cls.__ui_mainwindow.tableWidget_13.clear() @classmethod def refresh_school_class_id_invalid_to_view_exam_result_error_label(cls): cls.__ui_mainwindow.label_81.clear() @classmethod def refresh_student_exam_result_details(cls): cls.__ui_mainwindow.label_58.clear() cls.__ui_mainwindow.label_72.clear() cls.__ui_mainwindow.label_75.clear() cls.__ui_mainwindow.label_76.clear() cls.__ui_mainwindow.label_77.clear() cls.__ui_mainwindow.label_78.clear() cls.__ui_mainwindow.label_79.clear() cls.__ui_mainwindow.label_80.clear() @classmethod def display_no_exam_result_id_selected_message(cls): cls.__ui_mainwindow.label_81.setText("No Exam Result ID Selected") @classmethod def refresh_school_class_id_input_box_on_view_exam_result_details_page(cls): cls.__ui_mainwindow.lineEdit_23.clear() @classmethod def refresh_view_exam_details_by_id_page(cls): cls.__ui_mainwindow.label_18.setText("Exam ID : ") cls.__ui_mainwindow.tableWidget_7.clear() cls.__ui_mainwindow.label_67.clear() cls.__ui_mainwindow.label_68.clear() cls.__ui_mainwindow.label_69.clear() cls.__ui_mainwindow.label_70.clear() cls.__ui_mainwindow.label_71.clear() cls.__ui_mainwindow.tableWidget_27.clear() cls.__ui_mainwindow.tableWidget_28.clear() cls.__ui_mainwindow.tableWidget_29.clear() cls.__ui_mainwindow.tableWidget_30.clear() cls.__ui_mainwindow.tableWidget_31.clear() @classmethod def refresh_students_table_on_view_exam_result_details_page(cls): cls.__ui_mainwindow.tableWidget_13.clear() @classmethod def refresh_school_classes_table_on_view_exam_result_details_page(cls): cls.__ui_mainwindow.tableWidget_12.clear() def __str__(self): return ("This is TeacherGUI Object")
normal
{ "blob_id": "98f234ca0cbec419466de0504fd8d5c68fd07627", "index": 9609, "step-1": "<mask token>\n\n\nclass TeacherGUI:\n <mask token>\n\n @classmethod\n def setup(cls, ui_mainwindow):\n cls.__ui_mainwindow = ui_mainwindow\n\n @classmethod\n def display_all_active_school_classes(cls, school_classes):\n cls.__ui_mainwindow.tableWidget_14.clear()\n row = 0\n col = 0\n for school_class_id, in school_classes:\n school_class_text = 'Class ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_14.setItem(row, col,\n school_class_item)\n if col >= 4:\n col = 0\n row += 1\n else:\n col += 1\n <mask token>\n\n @classmethod\n def display_not_completed_exams(cls, not_completed_exams):\n cls.__ui_mainwindow.tableWidget_16.clear()\n row = 0\n col = 0\n for exam_id, in not_completed_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_16.setItem(row, col, exam_item)\n if col >= 6:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_ready_to_be_marked_exams(cls, ready_to_be_marked_exams):\n cls.__ui_mainwindow.tableWidget_17.clear()\n row = 0\n col = 0\n for exam_id, in ready_to_be_marked_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_17.setItem(row, col, exam_item)\n if col >= 3:\n col = 0\n row += 1\n else:\n col += 1\n <mask token>\n\n @classmethod\n def display_multiple_answers_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_MultipleAnswersQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText(option_A_text)\n cls.__ui_dialog.label_4.setText(option_B_text)\n cls.__ui_dialog.label_5.setText(option_C_text)\n cls.__ui_dialog.label_6.setText(option_D_text)\n cls.__ui_dialog.label_7.setText(option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_essay_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_EssayQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n if question_body == '':\n cls.__ui_dialog.label.setText('Question Body')\n else:\n cls.__ui_dialog.label.setText(question_body)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def close_dialog(cls):\n cls.__dialog.close()\n\n @classmethod\n def get_single_answer_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n if question_body == '':\n return None\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n if option_A_text == '':\n return None\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n if option_B_text == '':\n return None\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n if option_C_text == '':\n return None\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n if option_D_text == '':\n return None\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n if option_E_text == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_3.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_4.text()\n if phrase_tag_text == '':\n return None\n correct_answers_list = []\n if cls.__ui_mainwindow.radioButton.isChecked():\n correct_answers_list.append('A')\n if cls.__ui_mainwindow.radioButton_2.isChecked():\n correct_answers_list.append('B')\n if cls.__ui_mainwindow.radioButton_5.isChecked():\n correct_answers_list.append('C')\n if cls.__ui_mainwindow.radioButton_3.isChecked():\n correct_answers_list.append('D')\n if cls.__ui_mainwindow.radioButton_4.isChecked():\n correct_answers_list.append('E')\n if correct_answers_list == []:\n return None\n if len(correct_answers_list) > 1:\n return None\n return (question_body, option_A_text, option_B_text, option_C_text,\n option_D_text, option_E_text, year_level, phrase_tag_text,\n correct_answers_list)\n <mask token>\n\n @classmethod\n def get_essay_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n if question_body == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_26.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_27.text()\n if phrase_tag_text == '':\n return None\n return question_body, year_level, phrase_tag_text\n\n @classmethod\n def display_all_active_questions(cls, active_questions_tuple):\n row = 0\n col = 0\n for question_pk_tuple in active_questions_tuple:\n question_pk = question_pk_tuple[0]\n question_text = 'Question ' + str(question_pk)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget.setItem(row, col, question_item)\n if col >= 7:\n col = 0\n row += 1\n else:\n col += 1\n <mask token>\n\n @classmethod\n def display_invalid_single_answer_question_creation_message(cls):\n cls.__ui_mainwindow.label_4.setText(\n 'Invalid Single Answer Question Creation')\n\n @classmethod\n def display_create_multiple_answers_question_success(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Create Multiple Answers Question Success')\n\n @classmethod\n def display_invalid_multiple_answers_question_creation_message(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Invalid Multiple Answers Question Creation')\n\n @classmethod\n def display_invalid_essay_question_creation_message(cls):\n cls.__ui_mainwindow.label_42.setText('Invalid Essay Question Creation')\n\n @classmethod\n def display_create_essay_question_success(cls):\n cls.__ui_mainwindow.label_42.setText('Create Essay Question Success')\n\n @classmethod\n def display_invalid_modification_message(cls):\n cls.__ui_mainwindow.label_57.setText('Invalid Modification')\n\n @classmethod\n def refresh_create_single_answer_question_page(cls):\n cls.__ui_mainwindow.textEdit.clear()\n cls.__ui_mainwindow.textEdit_2.clear()\n cls.__ui_mainwindow.textEdit_3.clear()\n cls.__ui_mainwindow.textEdit_4.clear()\n cls.__ui_mainwindow.textEdit_5.clear()\n cls.__ui_mainwindow.textEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_3.clear()\n cls.__ui_mainwindow.lineEdit_4.clear()\n cls.__ui_mainwindow.radioButton.setChecked(False)\n cls.__ui_mainwindow.radioButton_2.setChecked(False)\n cls.__ui_mainwindow.radioButton_3.setChecked(False)\n cls.__ui_mainwindow.radioButton_4.setChecked(False)\n cls.__ui_mainwindow.radioButton_5.setChecked(False)\n <mask token>\n\n @classmethod\n def refresh_view_or_modify_question_page(cls):\n cls.__ui_mainwindow.lineEdit_5.clear()\n cls.__ui_mainwindow.label_45.setText('Question ID: ')\n cls.__ui_mainwindow.label_47.setText('Question Type: ')\n cls.__ui_mainwindow.label_57.clear()\n cls.__ui_mainwindow.label_12.clear()\n cls.__ui_mainwindow.textEdit_7.clear()\n cls.__ui_mainwindow.textEdit_8.clear()\n cls.__ui_mainwindow.textEdit_9.clear()\n cls.__ui_mainwindow.textEdit_10.clear()\n cls.__ui_mainwindow.textEdit_11.clear()\n cls.__ui_mainwindow.textEdit_20.clear()\n cls.__ui_mainwindow.lineEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_8.clear()\n cls.__ui_mainwindow.lineEdit_28.clear()\n cls.__ui_mainwindow.radioButton_6.setDisabled(False)\n cls.__ui_mainwindow.radioButton_7.setDisabled(False)\n cls.__ui_mainwindow.radioButton_8.setDisabled(False)\n cls.__ui_mainwindow.radioButton_9.setDisabled(False)\n cls.__ui_mainwindow.radioButton_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_8.setDisabled(False)\n cls.__ui_mainwindow.textEdit_9.setDisabled(False)\n cls.__ui_mainwindow.textEdit_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_11.setDisabled(False)\n cls.__ui_mainwindow.textEdit_20.setDisabled(False)\n cls.__ui_mainwindow.radioButton_6.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_6.setChecked(False)\n cls.__ui_mainwindow.radioButton_7.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_7.setChecked(False)\n cls.__ui_mainwindow.radioButton_8.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_8.setChecked(False)\n cls.__ui_mainwindow.radioButton_9.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_9.setChecked(False)\n cls.__ui_mainwindow.radioButton_10.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_10.setChecked(False)\n\n @classmethod\n def refresh_create_essay_question_page(cls):\n cls.__ui_mainwindow.textEdit_19.clear()\n cls.__ui_mainwindow.lineEdit_26.clear()\n cls.__ui_mainwindow.lineEdit_27.clear()\n\n @classmethod\n def refresh_create_exam_page(cls):\n cls.__ui_mainwindow.tableWidget_3.clear()\n cls.__ui_mainwindow.tableWidget_4.clear()\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.lineEdit_13.clear()\n\n @classmethod\n def get_question_id_to_load(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_5.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def load_single_answer_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answer = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answer == 'A':\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n elif correct_answer == 'B':\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n elif correct_answer == 'C':\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n elif correct_answer == 'D':\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n elif correct_answer == 'E':\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_multiple_answers_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answers = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answers.count('A') == 1:\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n if correct_answers.count('B') == 1:\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n if correct_answers.count('C') == 1:\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n if correct_answers.count('D') == 1:\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n if correct_answers.count('E') == 1:\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_essay_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.radioButton_6.setDisabled(True)\n cls.__ui_mainwindow.radioButton_7.setDisabled(True)\n cls.__ui_mainwindow.radioButton_8.setDisabled(True)\n cls.__ui_mainwindow.radioButton_9.setDisabled(True)\n cls.__ui_mainwindow.radioButton_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_8.setDisabled(True)\n cls.__ui_mainwindow.textEdit_9.setDisabled(True)\n cls.__ui_mainwindow.textEdit_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_11.setDisabled(True)\n cls.__ui_mainwindow.textEdit_20.setDisabled(True)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n\n @classmethod\n def display_question_id_invalid_to_load_message(cls):\n cls.__ui_mainwindow.label_12.setText('Invalid Question ID To Load')\n\n @classmethod\n def display_modification_success_message(cls):\n cls.__ui_mainwindow.label_57.setText('Modification Success')\n\n @classmethod\n def display_invalid_school_class_id_message(cls):\n cls.__ui_mainwindow.label_14.setText('Invalid School Class ID')\n cls.__ui_mainwindow.tableWidget_15.clear()\n\n @classmethod\n def get_question_type_to_modify(cls):\n question_type_text = cls.__ui_mainwindow.label_47.text()\n if question_type_text == 'Question Type: Single Answer':\n return 'Single Answer'\n elif question_type_text == 'Question Type: Multiple Answers':\n return 'Multiple Answers'\n elif question_type_text == 'Question Type: Essay':\n return 'Essay'\n\n @classmethod\n def get_single_answer_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answer = cls.get_single_correct_answer_to_modify()\n if correct_answer == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answer)\n\n @classmethod\n def get_multiple_answers_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answers = cls.get_multiple_correct_answers_to_modify()\n if correct_answers == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answers)\n\n @classmethod\n def get_essay_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n try:\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n except:\n return None\n try:\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n except:\n return None\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n if question_tag == '':\n return None\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n if question_body == '':\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body)\n\n @classmethod\n def get_question_id_to_modify(cls):\n question_id_text = cls.__ui_mainwindow.label_45.text()\n question_id_text_split = question_id_text.split()\n question_id = int(question_id_text_split.pop())\n return question_id\n <mask token>\n\n @classmethod\n def get_multiple_correct_answers_to_modify(cls):\n correct_answers = ''\n if cls.__ui_mainwindow.radioButton_6.isChecked():\n correct_answers = correct_answers + 'A'\n if cls.__ui_mainwindow.radioButton_7.isChecked():\n correct_answers = correct_answers + 'B'\n if cls.__ui_mainwindow.radioButton_8.isChecked():\n correct_answers = correct_answers + 'C'\n if cls.__ui_mainwindow.radioButton_9.isChecked():\n correct_answers = correct_answers + 'D'\n if cls.__ui_mainwindow.radioButton_10.isChecked():\n correct_answers = correct_answers + 'E'\n if len(correct_answers) == 0:\n return None\n if len(correct_answers) > 4:\n return None\n return correct_answers\n\n @classmethod\n def get_school_class_id_to_view_students(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_9.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def display_school_class_details(cls, school_class_details):\n cls.__ui_mainwindow.tableWidget_15.clear()\n row = 0\n col = 0\n for student, in school_class_details:\n student_item = QTableWidgetItem(student)\n cls.__ui_mainwindow.tableWidget_15.setItem(row, col, student_item)\n if col >= 1:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def refresh_view_school_class_details_page(cls):\n cls.__ui_mainwindow.label_14.clear()\n <mask token>\n\n @classmethod\n def get_number_of_school_classes_in_current_exam(cls):\n number_of_school_classes = 0\n row = 0\n col = 0\n for counter in range(5):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) != None:\n number_of_school_classes += 1\n row += 1\n return number_of_school_classes\n\n @classmethod\n def display_number_of_questions_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Questions Are Full In Current Exam')\n\n @classmethod\n def display_number_of_school_classes_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Classes Are Full In Current Exam')\n\n @classmethod\n def display_no_question_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No Question In Current Exam')\n\n @classmethod\n def display_no_school_class_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No School Class In Current Exam')\n <mask token>\n\n @classmethod\n def display_school_class_id_already_added_to_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Class ID Already Added To Current Exam')\n\n @classmethod\n def display_question_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('Question ID Invalid')\n\n @classmethod\n def display_school_class_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('School CLass ID Invalid')\n\n @classmethod\n def display_question_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Question ID Not Aleady In Current Exam')\n <mask token>\n\n @classmethod\n def display_create_exam_success_message(cls):\n cls.__ui_mainwindow.label_17.setText('Create Exam Success')\n\n @classmethod\n def refresh_mark_exam_drop_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n @classmethod\n def get_question_id_to_add_to_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_10.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n <mask token>\n <mask token>\n\n @classmethod\n def get_school_class_id_to_remove_from_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_13.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def add_question_id_to_current_exam(cls, question_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_3.item(row, col) == None:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_3.setItem(row, col,\n question_item)\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def add_school_class_id_to_current_exam(cls, school_class_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) == None:\n school_class_text = 'CLass ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_4.setItem(row, col,\n school_class_item)\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def remove_question_id_from_current_exam(cls, question_id):\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id_in_exam = int(question_text_split.pop())\n if question_id_in_exam == question_id:\n cls.__ui_mainwindow.tableWidget_3.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n\n @classmethod\n def remove_school_class_id_from_current_exam(cls, school_class_id):\n col = 0\n for row in range(5):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id_in_exam = int(school_class_text_split.pop())\n if school_class_id_in_exam == school_class_id:\n cls.__ui_mainwindow.tableWidget_4.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_13.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n <mask token>\n\n @classmethod\n def is_school_class_id_already_added_to_current_exam(cls, school_class_id):\n string_of_school_classes_ids_in_current_exam = (cls.\n get_string_of_school_classes_ids_in_current_exam())\n list_of_school_classes_ids = (\n string_of_school_classes_ids_in_current_exam.split(' '))\n return list_of_school_classes_ids.count(str(school_class_id)) == 1\n\n @classmethod\n def get_string_of_question_ids_in_current_exam(cls):\n string_of_question_ids = ''\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id = question_text_split.pop()\n string_of_question_ids = (string_of_question_ids +\n question_id + ' ')\n return string_of_question_ids.rstrip()\n\n @classmethod\n def get_string_of_school_classes_ids_in_current_exam(cls):\n string_of_school_classes_ids = ''\n col = 0\n for row in range(10):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id = school_class_text_split.pop()\n string_of_school_classes_ids = (\n string_of_school_classes_ids + school_class_id + ' ')\n return string_of_school_classes_ids.rstrip()\n\n @classmethod\n def get_exam_id_to_mark(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_20.item(0, 0)\n exam_text = exam_item.text()\n exam_text_split = exam_text.split(' ')\n exam_id_text = exam_text_split.pop()\n return int(exam_id_text)\n <mask token>\n\n @classmethod\n def display_students_full_names_with_questions_ready_to_be_marked(cls,\n students_names_list):\n cls.__ui_mainwindow.tableWidget_6.clear()\n row = 0\n col = 0\n for student_name in students_names_list:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_6.setItem(row, col, student_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_student_name_to_mark_answers(cls):\n student_item = cls.__ui_mainwindow.tableWidget_19.item(0, 0)\n student_name = student_item.text()\n return student_name\n\n @classmethod\n def get_exam_id_to_mark_student_answers(cls):\n exam_id_text = cls.__ui_mainwindow.label_49.text()\n exam_id_text_split = exam_id_text.split(' ')\n exam_id = exam_id_text_split.pop()\n return int(exam_id)\n <mask token>\n\n @classmethod\n def display_student_id_on_mark_student_answers_page(cls, student_id):\n student_id_text = 'Student ID: ' + str(student_id)\n cls.__ui_mainwindow.label_63.setText(student_id_text)\n\n @classmethod\n def display_student_name_on_mark_student_answers_page(cls, student_name):\n student_name_text = 'Student Name: ' + str(student_name)\n cls.__ui_mainwindow.label_50.setText(student_name_text)\n\n @classmethod\n def display_questions_ready_to_be_marked(cls, questions_ids_tuple):\n cls.__ui_mainwindow.tableWidget_25.clear()\n row = 0\n col = 0\n for question_id, in questions_ids_tuple:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_25.setItem(row, col, question_item)\n row += 1\n <mask token>\n\n @classmethod\n def get_exam_id_on_marking_question_page(cls):\n exam_id_text = cls.__ui_mainwindow.label_62.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def get_student_id_on_marking_question_page(cls):\n student_id_text = cls.__ui_mainwindow.label_63.text()\n student_id_text_list = student_id_text.split(' ')\n student_id = student_id_text_list.pop()\n return int(student_id)\n <mask token>\n\n @classmethod\n def get_essay_question_marked_points(cls):\n points_text = cls.__ui_dialog.lineEdit.text()\n return int(points_text)\n\n @classmethod\n def refresh_drop_question_to_mark_box(cls):\n cls.__ui_mainwindow.tableWidget_26.clear()\n\n @classmethod\n def refresh_mark_student_questions_answers_page(cls):\n cls.__ui_mainwindow.label_62.clear()\n cls.__ui_mainwindow.label_63.clear()\n cls.__ui_mainwindow.label_50.clear()\n\n @classmethod\n def display_no_more_questions_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No More Questions To Mark')\n\n @classmethod\n def display_marked_exams(cls, marked_exams_ids):\n cls.__ui_mainwindow.tableWidget_18.clear()\n row = 0\n col = 0\n for exam_id, in marked_exams_ids:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_18.setItem(row, col, exam_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def display_no_question_selected_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No Question Selected To Mark')\n <mask token>\n\n @classmethod\n def get_exam_id_to_release_result(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_21.item(0, 0)\n if exam_item == None:\n return None\n exam_id_text = exam_item.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def display_result_released_exams(cls, result_released_exams_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for exam_id, in result_released_exams_ids:\n exam_text = 'Exam ' + str(exam_id) + ' Result'\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_item)\n if col >= 9:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def refresh_drop_exam_to_release_result_box(cls):\n cls.__ui_mainwindow.tableWidget_21.clear()\n <mask token>\n\n @classmethod\n def get_exam_result_id_to_load_details(cls):\n exam_result_id_text = cls.__ui_mainwindow.lineEdit_22.text()\n return int(exam_result_id_text)\n <mask token>\n <mask token>\n\n @classmethod\n def get_school_class_id_to_view_exam_result(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_23.text()\n try:\n school_class_id = int(school_class_id_text)\n except:\n return None\n return school_class_id\n\n @classmethod\n def display_students_full_names_to_view_exam_result(cls,\n students_full_names):\n cls.__ui_mainwindow.tableWidget_13.clear()\n row = 0\n col = 0\n for student_full_name, in students_full_names:\n student_item = QTableWidgetItem(student_full_name)\n cls.__ui_mainwindow.tableWidget_13.setItem(row, col, student_item)\n row += 1\n <mask token>\n\n @classmethod\n def get_exam_result_id_on_view_exam_result_page(cls):\n exam_result_id_text = cls.__ui_mainwindow.label_33.text()\n exam_result_id_text_list = exam_result_id_text.split(' ')\n exam_result_id = exam_result_id_text_list.pop()\n try:\n exam_result_id_int = int(exam_result_id)\n return exam_result_id_int\n except:\n return None\n <mask token>\n <mask token>\n <mask token>\n\n @classmethod\n def display_questions_on_view_exam_details_page(cls, questions_ids):\n cls.__ui_mainwindow.tableWidget_7.clear()\n questions_ids_list = cls.make_string_to_list(questions_ids)\n row = 0\n col = 0\n for question_id in questions_ids_list:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_7.setItem(row, col, question_item)\n row += 1\n\n @classmethod\n def display_first_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_first_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_27.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_27.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_first_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_67.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_second_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_second_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_28.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_28.setItem(row, col, student_item)\n row += 1\n <mask token>\n <mask token>\n\n @classmethod\n def display_third_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_69.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fourth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fourth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_30.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_30.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fourth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_70.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fifth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fifth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_31.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_31.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fifth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_71.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def make_string_to_list(cls, any_string):\n any_string = str(any_string)\n any_list = any_string.split(' ')\n return any_list\n\n @classmethod\n def refresh_drop_student_to_view_exam_result_details_box(cls):\n cls.__ui_mainwindow.tableWidget_22.clear()\n\n @classmethod\n def display_exam_result_id_invalid_message(cls):\n cls.__ui_mainwindow.label_32.setText('Exam Result ID Invalid')\n\n @classmethod\n def refresh_load_exam_result_details_page(cls):\n cls.__ui_mainwindow.label_33.clear()\n cls.__ui_mainwindow.tableWidget_12.clear()\n cls.__ui_mainwindow.lineEdit_23.clear()\n cls.__ui_mainwindow.tableWidget_13.clear()\n cls.__ui_mainwindow.tableWidget_22.clear()\n cls.__ui_mainwindow.label_58.clear()\n cls.__ui_mainwindow.label_72.clear()\n cls.__ui_mainwindow.label_75.clear()\n cls.__ui_mainwindow.label_76.clear()\n cls.__ui_mainwindow.label_77.clear()\n cls.__ui_mainwindow.label_78.clear()\n cls.__ui_mainwindow.label_79.clear()\n cls.__ui_mainwindow.label_80.clear()\n\n @classmethod\n def refresh_exam_result_id_validity_error_message(cls):\n cls.__ui_mainwindow.label_32.clear()\n\n @classmethod\n def display_school_class_id_invalid_to_view_result_message(cls):\n cls.__ui_mainwindow.label_81.setText('School Class ID Invalid To View')\n\n @classmethod\n def refresh_school_class_details_table_on_view_exam_result_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n\n @classmethod\n def refresh_school_class_id_invalid_to_view_exam_result_error_label(cls):\n cls.__ui_mainwindow.label_81.clear()\n <mask token>\n\n @classmethod\n def display_no_exam_result_id_selected_message(cls):\n cls.__ui_mainwindow.label_81.setText('No Exam Result ID Selected')\n\n @classmethod\n def refresh_school_class_id_input_box_on_view_exam_result_details_page(cls\n ):\n cls.__ui_mainwindow.lineEdit_23.clear()\n\n @classmethod\n def refresh_view_exam_details_by_id_page(cls):\n cls.__ui_mainwindow.label_18.setText('Exam ID : ')\n cls.__ui_mainwindow.tableWidget_7.clear()\n cls.__ui_mainwindow.label_67.clear()\n cls.__ui_mainwindow.label_68.clear()\n cls.__ui_mainwindow.label_69.clear()\n cls.__ui_mainwindow.label_70.clear()\n cls.__ui_mainwindow.label_71.clear()\n cls.__ui_mainwindow.tableWidget_27.clear()\n cls.__ui_mainwindow.tableWidget_28.clear()\n cls.__ui_mainwindow.tableWidget_29.clear()\n cls.__ui_mainwindow.tableWidget_30.clear()\n cls.__ui_mainwindow.tableWidget_31.clear()\n\n @classmethod\n def refresh_students_table_on_view_exam_result_details_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n <mask token>\n <mask token>\n", "step-2": "<mask token>\n\n\nclass TeacherGUI:\n <mask token>\n\n @classmethod\n def setup(cls, ui_mainwindow):\n cls.__ui_mainwindow = ui_mainwindow\n\n @classmethod\n def display_all_active_school_classes(cls, school_classes):\n cls.__ui_mainwindow.tableWidget_14.clear()\n row = 0\n col = 0\n for school_class_id, in school_classes:\n school_class_text = 'Class ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_14.setItem(row, col,\n school_class_item)\n if col >= 4:\n col = 0\n row += 1\n else:\n col += 1\n <mask token>\n\n @classmethod\n def display_not_completed_exams(cls, not_completed_exams):\n cls.__ui_mainwindow.tableWidget_16.clear()\n row = 0\n col = 0\n for exam_id, in not_completed_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_16.setItem(row, col, exam_item)\n if col >= 6:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_ready_to_be_marked_exams(cls, ready_to_be_marked_exams):\n cls.__ui_mainwindow.tableWidget_17.clear()\n row = 0\n col = 0\n for exam_id, in ready_to_be_marked_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_17.setItem(row, col, exam_item)\n if col >= 3:\n col = 0\n row += 1\n else:\n col += 1\n <mask token>\n\n @classmethod\n def display_multiple_answers_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_MultipleAnswersQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText(option_A_text)\n cls.__ui_dialog.label_4.setText(option_B_text)\n cls.__ui_dialog.label_5.setText(option_C_text)\n cls.__ui_dialog.label_6.setText(option_D_text)\n cls.__ui_dialog.label_7.setText(option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_essay_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_EssayQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n if question_body == '':\n cls.__ui_dialog.label.setText('Question Body')\n else:\n cls.__ui_dialog.label.setText(question_body)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def close_dialog(cls):\n cls.__dialog.close()\n\n @classmethod\n def get_single_answer_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n if question_body == '':\n return None\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n if option_A_text == '':\n return None\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n if option_B_text == '':\n return None\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n if option_C_text == '':\n return None\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n if option_D_text == '':\n return None\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n if option_E_text == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_3.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_4.text()\n if phrase_tag_text == '':\n return None\n correct_answers_list = []\n if cls.__ui_mainwindow.radioButton.isChecked():\n correct_answers_list.append('A')\n if cls.__ui_mainwindow.radioButton_2.isChecked():\n correct_answers_list.append('B')\n if cls.__ui_mainwindow.radioButton_5.isChecked():\n correct_answers_list.append('C')\n if cls.__ui_mainwindow.radioButton_3.isChecked():\n correct_answers_list.append('D')\n if cls.__ui_mainwindow.radioButton_4.isChecked():\n correct_answers_list.append('E')\n if correct_answers_list == []:\n return None\n if len(correct_answers_list) > 1:\n return None\n return (question_body, option_A_text, option_B_text, option_C_text,\n option_D_text, option_E_text, year_level, phrase_tag_text,\n correct_answers_list)\n <mask token>\n\n @classmethod\n def get_essay_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n if question_body == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_26.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_27.text()\n if phrase_tag_text == '':\n return None\n return question_body, year_level, phrase_tag_text\n\n @classmethod\n def display_all_active_questions(cls, active_questions_tuple):\n row = 0\n col = 0\n for question_pk_tuple in active_questions_tuple:\n question_pk = question_pk_tuple[0]\n question_text = 'Question ' + str(question_pk)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget.setItem(row, col, question_item)\n if col >= 7:\n col = 0\n row += 1\n else:\n col += 1\n <mask token>\n\n @classmethod\n def display_invalid_single_answer_question_creation_message(cls):\n cls.__ui_mainwindow.label_4.setText(\n 'Invalid Single Answer Question Creation')\n\n @classmethod\n def display_create_multiple_answers_question_success(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Create Multiple Answers Question Success')\n\n @classmethod\n def display_invalid_multiple_answers_question_creation_message(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Invalid Multiple Answers Question Creation')\n\n @classmethod\n def display_invalid_essay_question_creation_message(cls):\n cls.__ui_mainwindow.label_42.setText('Invalid Essay Question Creation')\n\n @classmethod\n def display_create_essay_question_success(cls):\n cls.__ui_mainwindow.label_42.setText('Create Essay Question Success')\n\n @classmethod\n def display_invalid_modification_message(cls):\n cls.__ui_mainwindow.label_57.setText('Invalid Modification')\n\n @classmethod\n def refresh_create_single_answer_question_page(cls):\n cls.__ui_mainwindow.textEdit.clear()\n cls.__ui_mainwindow.textEdit_2.clear()\n cls.__ui_mainwindow.textEdit_3.clear()\n cls.__ui_mainwindow.textEdit_4.clear()\n cls.__ui_mainwindow.textEdit_5.clear()\n cls.__ui_mainwindow.textEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_3.clear()\n cls.__ui_mainwindow.lineEdit_4.clear()\n cls.__ui_mainwindow.radioButton.setChecked(False)\n cls.__ui_mainwindow.radioButton_2.setChecked(False)\n cls.__ui_mainwindow.radioButton_3.setChecked(False)\n cls.__ui_mainwindow.radioButton_4.setChecked(False)\n cls.__ui_mainwindow.radioButton_5.setChecked(False)\n <mask token>\n\n @classmethod\n def refresh_view_or_modify_question_page(cls):\n cls.__ui_mainwindow.lineEdit_5.clear()\n cls.__ui_mainwindow.label_45.setText('Question ID: ')\n cls.__ui_mainwindow.label_47.setText('Question Type: ')\n cls.__ui_mainwindow.label_57.clear()\n cls.__ui_mainwindow.label_12.clear()\n cls.__ui_mainwindow.textEdit_7.clear()\n cls.__ui_mainwindow.textEdit_8.clear()\n cls.__ui_mainwindow.textEdit_9.clear()\n cls.__ui_mainwindow.textEdit_10.clear()\n cls.__ui_mainwindow.textEdit_11.clear()\n cls.__ui_mainwindow.textEdit_20.clear()\n cls.__ui_mainwindow.lineEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_8.clear()\n cls.__ui_mainwindow.lineEdit_28.clear()\n cls.__ui_mainwindow.radioButton_6.setDisabled(False)\n cls.__ui_mainwindow.radioButton_7.setDisabled(False)\n cls.__ui_mainwindow.radioButton_8.setDisabled(False)\n cls.__ui_mainwindow.radioButton_9.setDisabled(False)\n cls.__ui_mainwindow.radioButton_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_8.setDisabled(False)\n cls.__ui_mainwindow.textEdit_9.setDisabled(False)\n cls.__ui_mainwindow.textEdit_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_11.setDisabled(False)\n cls.__ui_mainwindow.textEdit_20.setDisabled(False)\n cls.__ui_mainwindow.radioButton_6.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_6.setChecked(False)\n cls.__ui_mainwindow.radioButton_7.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_7.setChecked(False)\n cls.__ui_mainwindow.radioButton_8.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_8.setChecked(False)\n cls.__ui_mainwindow.radioButton_9.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_9.setChecked(False)\n cls.__ui_mainwindow.radioButton_10.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_10.setChecked(False)\n\n @classmethod\n def refresh_create_essay_question_page(cls):\n cls.__ui_mainwindow.textEdit_19.clear()\n cls.__ui_mainwindow.lineEdit_26.clear()\n cls.__ui_mainwindow.lineEdit_27.clear()\n\n @classmethod\n def refresh_create_exam_page(cls):\n cls.__ui_mainwindow.tableWidget_3.clear()\n cls.__ui_mainwindow.tableWidget_4.clear()\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.lineEdit_13.clear()\n\n @classmethod\n def get_question_id_to_load(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_5.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def load_single_answer_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answer = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answer == 'A':\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n elif correct_answer == 'B':\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n elif correct_answer == 'C':\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n elif correct_answer == 'D':\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n elif correct_answer == 'E':\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_multiple_answers_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answers = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answers.count('A') == 1:\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n if correct_answers.count('B') == 1:\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n if correct_answers.count('C') == 1:\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n if correct_answers.count('D') == 1:\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n if correct_answers.count('E') == 1:\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_essay_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.radioButton_6.setDisabled(True)\n cls.__ui_mainwindow.radioButton_7.setDisabled(True)\n cls.__ui_mainwindow.radioButton_8.setDisabled(True)\n cls.__ui_mainwindow.radioButton_9.setDisabled(True)\n cls.__ui_mainwindow.radioButton_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_8.setDisabled(True)\n cls.__ui_mainwindow.textEdit_9.setDisabled(True)\n cls.__ui_mainwindow.textEdit_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_11.setDisabled(True)\n cls.__ui_mainwindow.textEdit_20.setDisabled(True)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n\n @classmethod\n def display_question_id_invalid_to_load_message(cls):\n cls.__ui_mainwindow.label_12.setText('Invalid Question ID To Load')\n\n @classmethod\n def display_modification_success_message(cls):\n cls.__ui_mainwindow.label_57.setText('Modification Success')\n\n @classmethod\n def display_invalid_school_class_id_message(cls):\n cls.__ui_mainwindow.label_14.setText('Invalid School Class ID')\n cls.__ui_mainwindow.tableWidget_15.clear()\n\n @classmethod\n def get_question_type_to_modify(cls):\n question_type_text = cls.__ui_mainwindow.label_47.text()\n if question_type_text == 'Question Type: Single Answer':\n return 'Single Answer'\n elif question_type_text == 'Question Type: Multiple Answers':\n return 'Multiple Answers'\n elif question_type_text == 'Question Type: Essay':\n return 'Essay'\n\n @classmethod\n def get_single_answer_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answer = cls.get_single_correct_answer_to_modify()\n if correct_answer == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answer)\n\n @classmethod\n def get_multiple_answers_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answers = cls.get_multiple_correct_answers_to_modify()\n if correct_answers == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answers)\n\n @classmethod\n def get_essay_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n try:\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n except:\n return None\n try:\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n except:\n return None\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n if question_tag == '':\n return None\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n if question_body == '':\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body)\n\n @classmethod\n def get_question_id_to_modify(cls):\n question_id_text = cls.__ui_mainwindow.label_45.text()\n question_id_text_split = question_id_text.split()\n question_id = int(question_id_text_split.pop())\n return question_id\n <mask token>\n\n @classmethod\n def get_multiple_correct_answers_to_modify(cls):\n correct_answers = ''\n if cls.__ui_mainwindow.radioButton_6.isChecked():\n correct_answers = correct_answers + 'A'\n if cls.__ui_mainwindow.radioButton_7.isChecked():\n correct_answers = correct_answers + 'B'\n if cls.__ui_mainwindow.radioButton_8.isChecked():\n correct_answers = correct_answers + 'C'\n if cls.__ui_mainwindow.radioButton_9.isChecked():\n correct_answers = correct_answers + 'D'\n if cls.__ui_mainwindow.radioButton_10.isChecked():\n correct_answers = correct_answers + 'E'\n if len(correct_answers) == 0:\n return None\n if len(correct_answers) > 4:\n return None\n return correct_answers\n\n @classmethod\n def get_school_class_id_to_view_students(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_9.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def display_school_class_details(cls, school_class_details):\n cls.__ui_mainwindow.tableWidget_15.clear()\n row = 0\n col = 0\n for student, in school_class_details:\n student_item = QTableWidgetItem(student)\n cls.__ui_mainwindow.tableWidget_15.setItem(row, col, student_item)\n if col >= 1:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def refresh_view_school_class_details_page(cls):\n cls.__ui_mainwindow.label_14.clear()\n <mask token>\n\n @classmethod\n def get_number_of_school_classes_in_current_exam(cls):\n number_of_school_classes = 0\n row = 0\n col = 0\n for counter in range(5):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) != None:\n number_of_school_classes += 1\n row += 1\n return number_of_school_classes\n\n @classmethod\n def display_number_of_questions_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Questions Are Full In Current Exam')\n\n @classmethod\n def display_number_of_school_classes_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Classes Are Full In Current Exam')\n\n @classmethod\n def display_no_question_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No Question In Current Exam')\n\n @classmethod\n def display_no_school_class_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No School Class In Current Exam')\n <mask token>\n\n @classmethod\n def display_school_class_id_already_added_to_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Class ID Already Added To Current Exam')\n\n @classmethod\n def display_question_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('Question ID Invalid')\n\n @classmethod\n def display_school_class_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('School CLass ID Invalid')\n\n @classmethod\n def display_question_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Question ID Not Aleady In Current Exam')\n <mask token>\n\n @classmethod\n def display_create_exam_success_message(cls):\n cls.__ui_mainwindow.label_17.setText('Create Exam Success')\n\n @classmethod\n def refresh_mark_exam_drop_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n @classmethod\n def get_question_id_to_add_to_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_10.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def get_school_class_id_to_add_to_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_11.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n <mask token>\n\n @classmethod\n def get_school_class_id_to_remove_from_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_13.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def add_question_id_to_current_exam(cls, question_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_3.item(row, col) == None:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_3.setItem(row, col,\n question_item)\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def add_school_class_id_to_current_exam(cls, school_class_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) == None:\n school_class_text = 'CLass ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_4.setItem(row, col,\n school_class_item)\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def remove_question_id_from_current_exam(cls, question_id):\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id_in_exam = int(question_text_split.pop())\n if question_id_in_exam == question_id:\n cls.__ui_mainwindow.tableWidget_3.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n\n @classmethod\n def remove_school_class_id_from_current_exam(cls, school_class_id):\n col = 0\n for row in range(5):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id_in_exam = int(school_class_text_split.pop())\n if school_class_id_in_exam == school_class_id:\n cls.__ui_mainwindow.tableWidget_4.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_13.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n <mask token>\n\n @classmethod\n def is_school_class_id_already_added_to_current_exam(cls, school_class_id):\n string_of_school_classes_ids_in_current_exam = (cls.\n get_string_of_school_classes_ids_in_current_exam())\n list_of_school_classes_ids = (\n string_of_school_classes_ids_in_current_exam.split(' '))\n return list_of_school_classes_ids.count(str(school_class_id)) == 1\n\n @classmethod\n def get_string_of_question_ids_in_current_exam(cls):\n string_of_question_ids = ''\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id = question_text_split.pop()\n string_of_question_ids = (string_of_question_ids +\n question_id + ' ')\n return string_of_question_ids.rstrip()\n\n @classmethod\n def get_string_of_school_classes_ids_in_current_exam(cls):\n string_of_school_classes_ids = ''\n col = 0\n for row in range(10):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id = school_class_text_split.pop()\n string_of_school_classes_ids = (\n string_of_school_classes_ids + school_class_id + ' ')\n return string_of_school_classes_ids.rstrip()\n\n @classmethod\n def get_exam_id_to_mark(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_20.item(0, 0)\n exam_text = exam_item.text()\n exam_text_split = exam_text.split(' ')\n exam_id_text = exam_text_split.pop()\n return int(exam_id_text)\n <mask token>\n\n @classmethod\n def display_students_full_names_with_questions_ready_to_be_marked(cls,\n students_names_list):\n cls.__ui_mainwindow.tableWidget_6.clear()\n row = 0\n col = 0\n for student_name in students_names_list:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_6.setItem(row, col, student_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_student_name_to_mark_answers(cls):\n student_item = cls.__ui_mainwindow.tableWidget_19.item(0, 0)\n student_name = student_item.text()\n return student_name\n\n @classmethod\n def get_exam_id_to_mark_student_answers(cls):\n exam_id_text = cls.__ui_mainwindow.label_49.text()\n exam_id_text_split = exam_id_text.split(' ')\n exam_id = exam_id_text_split.pop()\n return int(exam_id)\n <mask token>\n\n @classmethod\n def display_student_id_on_mark_student_answers_page(cls, student_id):\n student_id_text = 'Student ID: ' + str(student_id)\n cls.__ui_mainwindow.label_63.setText(student_id_text)\n\n @classmethod\n def display_student_name_on_mark_student_answers_page(cls, student_name):\n student_name_text = 'Student Name: ' + str(student_name)\n cls.__ui_mainwindow.label_50.setText(student_name_text)\n\n @classmethod\n def display_questions_ready_to_be_marked(cls, questions_ids_tuple):\n cls.__ui_mainwindow.tableWidget_25.clear()\n row = 0\n col = 0\n for question_id, in questions_ids_tuple:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_25.setItem(row, col, question_item)\n row += 1\n <mask token>\n\n @classmethod\n def get_exam_id_on_marking_question_page(cls):\n exam_id_text = cls.__ui_mainwindow.label_62.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def get_student_id_on_marking_question_page(cls):\n student_id_text = cls.__ui_mainwindow.label_63.text()\n student_id_text_list = student_id_text.split(' ')\n student_id = student_id_text_list.pop()\n return int(student_id)\n <mask token>\n\n @classmethod\n def get_essay_question_marked_points(cls):\n points_text = cls.__ui_dialog.lineEdit.text()\n return int(points_text)\n\n @classmethod\n def refresh_drop_question_to_mark_box(cls):\n cls.__ui_mainwindow.tableWidget_26.clear()\n\n @classmethod\n def refresh_mark_student_questions_answers_page(cls):\n cls.__ui_mainwindow.label_62.clear()\n cls.__ui_mainwindow.label_63.clear()\n cls.__ui_mainwindow.label_50.clear()\n\n @classmethod\n def display_no_more_questions_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No More Questions To Mark')\n\n @classmethod\n def display_marked_exams(cls, marked_exams_ids):\n cls.__ui_mainwindow.tableWidget_18.clear()\n row = 0\n col = 0\n for exam_id, in marked_exams_ids:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_18.setItem(row, col, exam_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def display_no_question_selected_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No Question Selected To Mark')\n <mask token>\n\n @classmethod\n def get_exam_id_to_release_result(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_21.item(0, 0)\n if exam_item == None:\n return None\n exam_id_text = exam_item.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def display_result_released_exams(cls, result_released_exams_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for exam_id, in result_released_exams_ids:\n exam_text = 'Exam ' + str(exam_id) + ' Result'\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_item)\n if col >= 9:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def refresh_drop_exam_to_release_result_box(cls):\n cls.__ui_mainwindow.tableWidget_21.clear()\n <mask token>\n\n @classmethod\n def get_exam_result_id_to_load_details(cls):\n exam_result_id_text = cls.__ui_mainwindow.lineEdit_22.text()\n return int(exam_result_id_text)\n <mask token>\n\n @classmethod\n def display_exam_result_id_on_view_exam_result_details_page(cls,\n exam_result_id):\n cls.__ui_mainwindow.label_33.setText('Exam Result ID: ' + str(\n exam_result_id))\n\n @classmethod\n def get_school_class_id_to_view_exam_result(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_23.text()\n try:\n school_class_id = int(school_class_id_text)\n except:\n return None\n return school_class_id\n\n @classmethod\n def display_students_full_names_to_view_exam_result(cls,\n students_full_names):\n cls.__ui_mainwindow.tableWidget_13.clear()\n row = 0\n col = 0\n for student_full_name, in students_full_names:\n student_item = QTableWidgetItem(student_full_name)\n cls.__ui_mainwindow.tableWidget_13.setItem(row, col, student_item)\n row += 1\n <mask token>\n\n @classmethod\n def get_exam_result_id_on_view_exam_result_page(cls):\n exam_result_id_text = cls.__ui_mainwindow.label_33.text()\n exam_result_id_text_list = exam_result_id_text.split(' ')\n exam_result_id = exam_result_id_text_list.pop()\n try:\n exam_result_id_int = int(exam_result_id)\n return exam_result_id_int\n except:\n return None\n\n @classmethod\n def display_student_exam_result_details(cls, exam_result_details):\n student_id = exam_result_details[0]\n student_full_name = exam_result_details[1]\n date_of_birth = exam_result_details[2]\n school_class_id = exam_result_details[3]\n exam_id = exam_result_details[4]\n total_available_points = exam_result_details[5]\n total_points_gained = exam_result_details[6]\n average_percentage_mark = exam_result_details[7]\n cls.__ui_mainwindow.label_58.setText(str(student_id))\n cls.__ui_mainwindow.label_72.setText(str(student_full_name))\n cls.__ui_mainwindow.label_75.setText(str(date_of_birth))\n cls.__ui_mainwindow.label_76.setText(str(school_class_id))\n cls.__ui_mainwindow.label_77.setText(str(exam_id))\n cls.__ui_mainwindow.label_78.setText(str(total_available_points))\n cls.__ui_mainwindow.label_79.setText(str(total_points_gained))\n cls.__ui_mainwindow.label_80.setText(str(average_percentage_mark) +\n ' %')\n <mask token>\n <mask token>\n\n @classmethod\n def display_questions_on_view_exam_details_page(cls, questions_ids):\n cls.__ui_mainwindow.tableWidget_7.clear()\n questions_ids_list = cls.make_string_to_list(questions_ids)\n row = 0\n col = 0\n for question_id in questions_ids_list:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_7.setItem(row, col, question_item)\n row += 1\n\n @classmethod\n def display_first_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_first_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_27.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_27.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_first_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_67.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_second_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_second_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_28.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_28.setItem(row, col, student_item)\n row += 1\n <mask token>\n <mask token>\n\n @classmethod\n def display_third_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_69.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fourth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fourth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_30.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_30.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fourth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_70.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fifth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fifth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_31.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_31.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fifth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_71.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def make_string_to_list(cls, any_string):\n any_string = str(any_string)\n any_list = any_string.split(' ')\n return any_list\n\n @classmethod\n def refresh_drop_student_to_view_exam_result_details_box(cls):\n cls.__ui_mainwindow.tableWidget_22.clear()\n\n @classmethod\n def display_exam_result_id_invalid_message(cls):\n cls.__ui_mainwindow.label_32.setText('Exam Result ID Invalid')\n\n @classmethod\n def refresh_load_exam_result_details_page(cls):\n cls.__ui_mainwindow.label_33.clear()\n cls.__ui_mainwindow.tableWidget_12.clear()\n cls.__ui_mainwindow.lineEdit_23.clear()\n cls.__ui_mainwindow.tableWidget_13.clear()\n cls.__ui_mainwindow.tableWidget_22.clear()\n cls.__ui_mainwindow.label_58.clear()\n cls.__ui_mainwindow.label_72.clear()\n cls.__ui_mainwindow.label_75.clear()\n cls.__ui_mainwindow.label_76.clear()\n cls.__ui_mainwindow.label_77.clear()\n cls.__ui_mainwindow.label_78.clear()\n cls.__ui_mainwindow.label_79.clear()\n cls.__ui_mainwindow.label_80.clear()\n\n @classmethod\n def refresh_exam_result_id_validity_error_message(cls):\n cls.__ui_mainwindow.label_32.clear()\n\n @classmethod\n def display_school_class_id_invalid_to_view_result_message(cls):\n cls.__ui_mainwindow.label_81.setText('School Class ID Invalid To View')\n\n @classmethod\n def refresh_school_class_details_table_on_view_exam_result_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n\n @classmethod\n def refresh_school_class_id_invalid_to_view_exam_result_error_label(cls):\n cls.__ui_mainwindow.label_81.clear()\n <mask token>\n\n @classmethod\n def display_no_exam_result_id_selected_message(cls):\n cls.__ui_mainwindow.label_81.setText('No Exam Result ID Selected')\n\n @classmethod\n def refresh_school_class_id_input_box_on_view_exam_result_details_page(cls\n ):\n cls.__ui_mainwindow.lineEdit_23.clear()\n\n @classmethod\n def refresh_view_exam_details_by_id_page(cls):\n cls.__ui_mainwindow.label_18.setText('Exam ID : ')\n cls.__ui_mainwindow.tableWidget_7.clear()\n cls.__ui_mainwindow.label_67.clear()\n cls.__ui_mainwindow.label_68.clear()\n cls.__ui_mainwindow.label_69.clear()\n cls.__ui_mainwindow.label_70.clear()\n cls.__ui_mainwindow.label_71.clear()\n cls.__ui_mainwindow.tableWidget_27.clear()\n cls.__ui_mainwindow.tableWidget_28.clear()\n cls.__ui_mainwindow.tableWidget_29.clear()\n cls.__ui_mainwindow.tableWidget_30.clear()\n cls.__ui_mainwindow.tableWidget_31.clear()\n\n @classmethod\n def refresh_students_table_on_view_exam_result_details_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n <mask token>\n <mask token>\n", "step-3": "<mask token>\n\n\nclass TeacherGUI:\n\n def __init__(self):\n pass\n\n @classmethod\n def setup(cls, ui_mainwindow):\n cls.__ui_mainwindow = ui_mainwindow\n\n @classmethod\n def display_all_active_school_classes(cls, school_classes):\n cls.__ui_mainwindow.tableWidget_14.clear()\n row = 0\n col = 0\n for school_class_id, in school_classes:\n school_class_text = 'Class ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_14.setItem(row, col,\n school_class_item)\n if col >= 4:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_all_exams(cls, all_exams):\n cls.__ui_mainwindow.tableWidget_5.clear()\n row = 0\n col = 0\n for exam_id, in all_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_5.setItem(row, col, exam_item)\n if col >= 9:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_not_completed_exams(cls, not_completed_exams):\n cls.__ui_mainwindow.tableWidget_16.clear()\n row = 0\n col = 0\n for exam_id, in not_completed_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_16.setItem(row, col, exam_item)\n if col >= 6:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_ready_to_be_marked_exams(cls, ready_to_be_marked_exams):\n cls.__ui_mainwindow.tableWidget_17.clear()\n row = 0\n col = 0\n for exam_id, in ready_to_be_marked_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_17.setItem(row, col, exam_item)\n if col >= 3:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_single_answer_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_SingleAnswerQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText('A ' + option_A_text)\n cls.__ui_dialog.label_4.setText('B ' + option_B_text)\n cls.__ui_dialog.label_5.setText('C ' + option_C_text)\n cls.__ui_dialog.label_6.setText('D ' + option_D_text)\n cls.__ui_dialog.label_7.setText('E ' + option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_multiple_answers_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_MultipleAnswersQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText(option_A_text)\n cls.__ui_dialog.label_4.setText(option_B_text)\n cls.__ui_dialog.label_5.setText(option_C_text)\n cls.__ui_dialog.label_6.setText(option_D_text)\n cls.__ui_dialog.label_7.setText(option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_essay_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_EssayQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n if question_body == '':\n cls.__ui_dialog.label.setText('Question Body')\n else:\n cls.__ui_dialog.label.setText(question_body)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def close_dialog(cls):\n cls.__dialog.close()\n\n @classmethod\n def get_single_answer_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n if question_body == '':\n return None\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n if option_A_text == '':\n return None\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n if option_B_text == '':\n return None\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n if option_C_text == '':\n return None\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n if option_D_text == '':\n return None\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n if option_E_text == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_3.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_4.text()\n if phrase_tag_text == '':\n return None\n correct_answers_list = []\n if cls.__ui_mainwindow.radioButton.isChecked():\n correct_answers_list.append('A')\n if cls.__ui_mainwindow.radioButton_2.isChecked():\n correct_answers_list.append('B')\n if cls.__ui_mainwindow.radioButton_5.isChecked():\n correct_answers_list.append('C')\n if cls.__ui_mainwindow.radioButton_3.isChecked():\n correct_answers_list.append('D')\n if cls.__ui_mainwindow.radioButton_4.isChecked():\n correct_answers_list.append('E')\n if correct_answers_list == []:\n return None\n if len(correct_answers_list) > 1:\n return None\n return (question_body, option_A_text, option_B_text, option_C_text,\n option_D_text, option_E_text, year_level, phrase_tag_text,\n correct_answers_list)\n <mask token>\n\n @classmethod\n def get_essay_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n if question_body == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_26.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_27.text()\n if phrase_tag_text == '':\n return None\n return question_body, year_level, phrase_tag_text\n\n @classmethod\n def display_all_active_questions(cls, active_questions_tuple):\n row = 0\n col = 0\n for question_pk_tuple in active_questions_tuple:\n question_pk = question_pk_tuple[0]\n question_text = 'Question ' + str(question_pk)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget.setItem(row, col, question_item)\n if col >= 7:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_create_single_answer_question_success(cls):\n cls.__ui_mainwindow.label_4.setText(\n 'Create Single Answer Question Success')\n\n @classmethod\n def display_invalid_single_answer_question_creation_message(cls):\n cls.__ui_mainwindow.label_4.setText(\n 'Invalid Single Answer Question Creation')\n\n @classmethod\n def display_create_multiple_answers_question_success(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Create Multiple Answers Question Success')\n\n @classmethod\n def display_invalid_multiple_answers_question_creation_message(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Invalid Multiple Answers Question Creation')\n\n @classmethod\n def display_invalid_essay_question_creation_message(cls):\n cls.__ui_mainwindow.label_42.setText('Invalid Essay Question Creation')\n\n @classmethod\n def display_create_essay_question_success(cls):\n cls.__ui_mainwindow.label_42.setText('Create Essay Question Success')\n\n @classmethod\n def display_invalid_modification_message(cls):\n cls.__ui_mainwindow.label_57.setText('Invalid Modification')\n\n @classmethod\n def refresh_create_single_answer_question_page(cls):\n cls.__ui_mainwindow.textEdit.clear()\n cls.__ui_mainwindow.textEdit_2.clear()\n cls.__ui_mainwindow.textEdit_3.clear()\n cls.__ui_mainwindow.textEdit_4.clear()\n cls.__ui_mainwindow.textEdit_5.clear()\n cls.__ui_mainwindow.textEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_3.clear()\n cls.__ui_mainwindow.lineEdit_4.clear()\n cls.__ui_mainwindow.radioButton.setChecked(False)\n cls.__ui_mainwindow.radioButton_2.setChecked(False)\n cls.__ui_mainwindow.radioButton_3.setChecked(False)\n cls.__ui_mainwindow.radioButton_4.setChecked(False)\n cls.__ui_mainwindow.radioButton_5.setChecked(False)\n <mask token>\n\n @classmethod\n def refresh_view_or_modify_question_page(cls):\n cls.__ui_mainwindow.lineEdit_5.clear()\n cls.__ui_mainwindow.label_45.setText('Question ID: ')\n cls.__ui_mainwindow.label_47.setText('Question Type: ')\n cls.__ui_mainwindow.label_57.clear()\n cls.__ui_mainwindow.label_12.clear()\n cls.__ui_mainwindow.textEdit_7.clear()\n cls.__ui_mainwindow.textEdit_8.clear()\n cls.__ui_mainwindow.textEdit_9.clear()\n cls.__ui_mainwindow.textEdit_10.clear()\n cls.__ui_mainwindow.textEdit_11.clear()\n cls.__ui_mainwindow.textEdit_20.clear()\n cls.__ui_mainwindow.lineEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_8.clear()\n cls.__ui_mainwindow.lineEdit_28.clear()\n cls.__ui_mainwindow.radioButton_6.setDisabled(False)\n cls.__ui_mainwindow.radioButton_7.setDisabled(False)\n cls.__ui_mainwindow.radioButton_8.setDisabled(False)\n cls.__ui_mainwindow.radioButton_9.setDisabled(False)\n cls.__ui_mainwindow.radioButton_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_8.setDisabled(False)\n cls.__ui_mainwindow.textEdit_9.setDisabled(False)\n cls.__ui_mainwindow.textEdit_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_11.setDisabled(False)\n cls.__ui_mainwindow.textEdit_20.setDisabled(False)\n cls.__ui_mainwindow.radioButton_6.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_6.setChecked(False)\n cls.__ui_mainwindow.radioButton_7.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_7.setChecked(False)\n cls.__ui_mainwindow.radioButton_8.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_8.setChecked(False)\n cls.__ui_mainwindow.radioButton_9.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_9.setChecked(False)\n cls.__ui_mainwindow.radioButton_10.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_10.setChecked(False)\n\n @classmethod\n def refresh_create_essay_question_page(cls):\n cls.__ui_mainwindow.textEdit_19.clear()\n cls.__ui_mainwindow.lineEdit_26.clear()\n cls.__ui_mainwindow.lineEdit_27.clear()\n\n @classmethod\n def refresh_create_exam_page(cls):\n cls.__ui_mainwindow.tableWidget_3.clear()\n cls.__ui_mainwindow.tableWidget_4.clear()\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.lineEdit_13.clear()\n\n @classmethod\n def get_question_id_to_load(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_5.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def load_single_answer_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answer = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answer == 'A':\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n elif correct_answer == 'B':\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n elif correct_answer == 'C':\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n elif correct_answer == 'D':\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n elif correct_answer == 'E':\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_multiple_answers_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answers = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answers.count('A') == 1:\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n if correct_answers.count('B') == 1:\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n if correct_answers.count('C') == 1:\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n if correct_answers.count('D') == 1:\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n if correct_answers.count('E') == 1:\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_essay_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.radioButton_6.setDisabled(True)\n cls.__ui_mainwindow.radioButton_7.setDisabled(True)\n cls.__ui_mainwindow.radioButton_8.setDisabled(True)\n cls.__ui_mainwindow.radioButton_9.setDisabled(True)\n cls.__ui_mainwindow.radioButton_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_8.setDisabled(True)\n cls.__ui_mainwindow.textEdit_9.setDisabled(True)\n cls.__ui_mainwindow.textEdit_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_11.setDisabled(True)\n cls.__ui_mainwindow.textEdit_20.setDisabled(True)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n\n @classmethod\n def display_question_id_invalid_to_load_message(cls):\n cls.__ui_mainwindow.label_12.setText('Invalid Question ID To Load')\n\n @classmethod\n def display_modification_success_message(cls):\n cls.__ui_mainwindow.label_57.setText('Modification Success')\n\n @classmethod\n def display_invalid_school_class_id_message(cls):\n cls.__ui_mainwindow.label_14.setText('Invalid School Class ID')\n cls.__ui_mainwindow.tableWidget_15.clear()\n\n @classmethod\n def get_question_type_to_modify(cls):\n question_type_text = cls.__ui_mainwindow.label_47.text()\n if question_type_text == 'Question Type: Single Answer':\n return 'Single Answer'\n elif question_type_text == 'Question Type: Multiple Answers':\n return 'Multiple Answers'\n elif question_type_text == 'Question Type: Essay':\n return 'Essay'\n\n @classmethod\n def get_single_answer_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answer = cls.get_single_correct_answer_to_modify()\n if correct_answer == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answer)\n\n @classmethod\n def get_multiple_answers_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answers = cls.get_multiple_correct_answers_to_modify()\n if correct_answers == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answers)\n\n @classmethod\n def get_essay_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n try:\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n except:\n return None\n try:\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n except:\n return None\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n if question_tag == '':\n return None\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n if question_body == '':\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body)\n\n @classmethod\n def get_question_id_to_modify(cls):\n question_id_text = cls.__ui_mainwindow.label_45.text()\n question_id_text_split = question_id_text.split()\n question_id = int(question_id_text_split.pop())\n return question_id\n <mask token>\n\n @classmethod\n def get_multiple_correct_answers_to_modify(cls):\n correct_answers = ''\n if cls.__ui_mainwindow.radioButton_6.isChecked():\n correct_answers = correct_answers + 'A'\n if cls.__ui_mainwindow.radioButton_7.isChecked():\n correct_answers = correct_answers + 'B'\n if cls.__ui_mainwindow.radioButton_8.isChecked():\n correct_answers = correct_answers + 'C'\n if cls.__ui_mainwindow.radioButton_9.isChecked():\n correct_answers = correct_answers + 'D'\n if cls.__ui_mainwindow.radioButton_10.isChecked():\n correct_answers = correct_answers + 'E'\n if len(correct_answers) == 0:\n return None\n if len(correct_answers) > 4:\n return None\n return correct_answers\n\n @classmethod\n def get_school_class_id_to_view_students(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_9.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def display_school_class_details(cls, school_class_details):\n cls.__ui_mainwindow.tableWidget_15.clear()\n row = 0\n col = 0\n for student, in school_class_details:\n student_item = QTableWidgetItem(student)\n cls.__ui_mainwindow.tableWidget_15.setItem(row, col, student_item)\n if col >= 1:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def refresh_view_school_class_details_page(cls):\n cls.__ui_mainwindow.label_14.clear()\n <mask token>\n\n @classmethod\n def get_number_of_school_classes_in_current_exam(cls):\n number_of_school_classes = 0\n row = 0\n col = 0\n for counter in range(5):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) != None:\n number_of_school_classes += 1\n row += 1\n return number_of_school_classes\n\n @classmethod\n def display_number_of_questions_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Questions Are Full In Current Exam')\n\n @classmethod\n def display_number_of_school_classes_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Classes Are Full In Current Exam')\n\n @classmethod\n def display_no_question_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No Question In Current Exam')\n\n @classmethod\n def display_no_school_class_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No School Class In Current Exam')\n <mask token>\n\n @classmethod\n def display_school_class_id_already_added_to_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Class ID Already Added To Current Exam')\n\n @classmethod\n def display_question_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('Question ID Invalid')\n\n @classmethod\n def display_school_class_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('School CLass ID Invalid')\n\n @classmethod\n def display_question_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Question ID Not Aleady In Current Exam')\n\n @classmethod\n def display_school_class_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Class ID Not Aleady In Current Exam')\n\n @classmethod\n def display_create_exam_success_message(cls):\n cls.__ui_mainwindow.label_17.setText('Create Exam Success')\n\n @classmethod\n def refresh_mark_exam_drop_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n @classmethod\n def get_question_id_to_add_to_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_10.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def get_school_class_id_to_add_to_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_11.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def get_question_id_to_remove_from_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_12.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def get_school_class_id_to_remove_from_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_13.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def add_question_id_to_current_exam(cls, question_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_3.item(row, col) == None:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_3.setItem(row, col,\n question_item)\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def add_school_class_id_to_current_exam(cls, school_class_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) == None:\n school_class_text = 'CLass ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_4.setItem(row, col,\n school_class_item)\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def remove_question_id_from_current_exam(cls, question_id):\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id_in_exam = int(question_text_split.pop())\n if question_id_in_exam == question_id:\n cls.__ui_mainwindow.tableWidget_3.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n\n @classmethod\n def remove_school_class_id_from_current_exam(cls, school_class_id):\n col = 0\n for row in range(5):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id_in_exam = int(school_class_text_split.pop())\n if school_class_id_in_exam == school_class_id:\n cls.__ui_mainwindow.tableWidget_4.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_13.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n <mask token>\n\n @classmethod\n def is_school_class_id_already_added_to_current_exam(cls, school_class_id):\n string_of_school_classes_ids_in_current_exam = (cls.\n get_string_of_school_classes_ids_in_current_exam())\n list_of_school_classes_ids = (\n string_of_school_classes_ids_in_current_exam.split(' '))\n return list_of_school_classes_ids.count(str(school_class_id)) == 1\n\n @classmethod\n def get_string_of_question_ids_in_current_exam(cls):\n string_of_question_ids = ''\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id = question_text_split.pop()\n string_of_question_ids = (string_of_question_ids +\n question_id + ' ')\n return string_of_question_ids.rstrip()\n\n @classmethod\n def get_string_of_school_classes_ids_in_current_exam(cls):\n string_of_school_classes_ids = ''\n col = 0\n for row in range(10):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id = school_class_text_split.pop()\n string_of_school_classes_ids = (\n string_of_school_classes_ids + school_class_id + ' ')\n return string_of_school_classes_ids.rstrip()\n\n @classmethod\n def get_exam_id_to_mark(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_20.item(0, 0)\n exam_text = exam_item.text()\n exam_text_split = exam_text.split(' ')\n exam_id_text = exam_text_split.pop()\n return int(exam_id_text)\n <mask token>\n\n @classmethod\n def display_students_full_names_with_questions_ready_to_be_marked(cls,\n students_names_list):\n cls.__ui_mainwindow.tableWidget_6.clear()\n row = 0\n col = 0\n for student_name in students_names_list:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_6.setItem(row, col, student_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_student_name_to_mark_answers(cls):\n student_item = cls.__ui_mainwindow.tableWidget_19.item(0, 0)\n student_name = student_item.text()\n return student_name\n\n @classmethod\n def get_exam_id_to_mark_student_answers(cls):\n exam_id_text = cls.__ui_mainwindow.label_49.text()\n exam_id_text_split = exam_id_text.split(' ')\n exam_id = exam_id_text_split.pop()\n return int(exam_id)\n <mask token>\n\n @classmethod\n def display_student_id_on_mark_student_answers_page(cls, student_id):\n student_id_text = 'Student ID: ' + str(student_id)\n cls.__ui_mainwindow.label_63.setText(student_id_text)\n\n @classmethod\n def display_student_name_on_mark_student_answers_page(cls, student_name):\n student_name_text = 'Student Name: ' + str(student_name)\n cls.__ui_mainwindow.label_50.setText(student_name_text)\n\n @classmethod\n def display_questions_ready_to_be_marked(cls, questions_ids_tuple):\n cls.__ui_mainwindow.tableWidget_25.clear()\n row = 0\n col = 0\n for question_id, in questions_ids_tuple:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_25.setItem(row, col, question_item)\n row += 1\n <mask token>\n\n @classmethod\n def get_exam_id_on_marking_question_page(cls):\n exam_id_text = cls.__ui_mainwindow.label_62.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def get_student_id_on_marking_question_page(cls):\n student_id_text = cls.__ui_mainwindow.label_63.text()\n student_id_text_list = student_id_text.split(' ')\n student_id = student_id_text_list.pop()\n return int(student_id)\n <mask token>\n\n @classmethod\n def get_essay_question_marked_points(cls):\n points_text = cls.__ui_dialog.lineEdit.text()\n return int(points_text)\n\n @classmethod\n def refresh_drop_question_to_mark_box(cls):\n cls.__ui_mainwindow.tableWidget_26.clear()\n\n @classmethod\n def refresh_mark_student_questions_answers_page(cls):\n cls.__ui_mainwindow.label_62.clear()\n cls.__ui_mainwindow.label_63.clear()\n cls.__ui_mainwindow.label_50.clear()\n\n @classmethod\n def display_no_more_questions_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No More Questions To Mark')\n\n @classmethod\n def display_marked_exams(cls, marked_exams_ids):\n cls.__ui_mainwindow.tableWidget_18.clear()\n row = 0\n col = 0\n for exam_id, in marked_exams_ids:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_18.setItem(row, col, exam_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def display_no_question_selected_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No Question Selected To Mark')\n\n @classmethod\n def refresh_drop_student_to_mark_questions_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n @classmethod\n def get_exam_id_to_release_result(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_21.item(0, 0)\n if exam_item == None:\n return None\n exam_id_text = exam_item.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def display_result_released_exams(cls, result_released_exams_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for exam_id, in result_released_exams_ids:\n exam_text = 'Exam ' + str(exam_id) + ' Result'\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_item)\n if col >= 9:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def refresh_drop_exam_to_release_result_box(cls):\n cls.__ui_mainwindow.tableWidget_21.clear()\n\n @classmethod\n def display_exam_results(cls, exam_results_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for exam_result_id, in exam_results_ids:\n exam_result_text = 'Exam ' + str(exam_result_id) + ' Result'\n exam_result_item = QTableWidgetItem(exam_result_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col,\n exam_result_item)\n if col >= 9:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_exam_result_id_to_load_details(cls):\n exam_result_id_text = cls.__ui_mainwindow.lineEdit_22.text()\n return int(exam_result_id_text)\n <mask token>\n\n @classmethod\n def display_exam_result_id_on_view_exam_result_details_page(cls,\n exam_result_id):\n cls.__ui_mainwindow.label_33.setText('Exam Result ID: ' + str(\n exam_result_id))\n\n @classmethod\n def get_school_class_id_to_view_exam_result(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_23.text()\n try:\n school_class_id = int(school_class_id_text)\n except:\n return None\n return school_class_id\n\n @classmethod\n def display_students_full_names_to_view_exam_result(cls,\n students_full_names):\n cls.__ui_mainwindow.tableWidget_13.clear()\n row = 0\n col = 0\n for student_full_name, in students_full_names:\n student_item = QTableWidgetItem(student_full_name)\n cls.__ui_mainwindow.tableWidget_13.setItem(row, col, student_item)\n row += 1\n <mask token>\n\n @classmethod\n def get_exam_result_id_on_view_exam_result_page(cls):\n exam_result_id_text = cls.__ui_mainwindow.label_33.text()\n exam_result_id_text_list = exam_result_id_text.split(' ')\n exam_result_id = exam_result_id_text_list.pop()\n try:\n exam_result_id_int = int(exam_result_id)\n return exam_result_id_int\n except:\n return None\n\n @classmethod\n def display_student_exam_result_details(cls, exam_result_details):\n student_id = exam_result_details[0]\n student_full_name = exam_result_details[1]\n date_of_birth = exam_result_details[2]\n school_class_id = exam_result_details[3]\n exam_id = exam_result_details[4]\n total_available_points = exam_result_details[5]\n total_points_gained = exam_result_details[6]\n average_percentage_mark = exam_result_details[7]\n cls.__ui_mainwindow.label_58.setText(str(student_id))\n cls.__ui_mainwindow.label_72.setText(str(student_full_name))\n cls.__ui_mainwindow.label_75.setText(str(date_of_birth))\n cls.__ui_mainwindow.label_76.setText(str(school_class_id))\n cls.__ui_mainwindow.label_77.setText(str(exam_id))\n cls.__ui_mainwindow.label_78.setText(str(total_available_points))\n cls.__ui_mainwindow.label_79.setText(str(total_points_gained))\n cls.__ui_mainwindow.label_80.setText(str(average_percentage_mark) +\n ' %')\n <mask token>\n <mask token>\n\n @classmethod\n def display_questions_on_view_exam_details_page(cls, questions_ids):\n cls.__ui_mainwindow.tableWidget_7.clear()\n questions_ids_list = cls.make_string_to_list(questions_ids)\n row = 0\n col = 0\n for question_id in questions_ids_list:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_7.setItem(row, col, question_item)\n row += 1\n\n @classmethod\n def display_first_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_first_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_27.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_27.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_first_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_67.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_second_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_second_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_28.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_28.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_second_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_68.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_third_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_third_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_29.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_29.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_third_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_69.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fourth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fourth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_30.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_30.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fourth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_70.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fifth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fifth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_31.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_31.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fifth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_71.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def make_string_to_list(cls, any_string):\n any_string = str(any_string)\n any_list = any_string.split(' ')\n return any_list\n\n @classmethod\n def refresh_drop_student_to_view_exam_result_details_box(cls):\n cls.__ui_mainwindow.tableWidget_22.clear()\n\n @classmethod\n def display_exam_result_id_invalid_message(cls):\n cls.__ui_mainwindow.label_32.setText('Exam Result ID Invalid')\n\n @classmethod\n def refresh_load_exam_result_details_page(cls):\n cls.__ui_mainwindow.label_33.clear()\n cls.__ui_mainwindow.tableWidget_12.clear()\n cls.__ui_mainwindow.lineEdit_23.clear()\n cls.__ui_mainwindow.tableWidget_13.clear()\n cls.__ui_mainwindow.tableWidget_22.clear()\n cls.__ui_mainwindow.label_58.clear()\n cls.__ui_mainwindow.label_72.clear()\n cls.__ui_mainwindow.label_75.clear()\n cls.__ui_mainwindow.label_76.clear()\n cls.__ui_mainwindow.label_77.clear()\n cls.__ui_mainwindow.label_78.clear()\n cls.__ui_mainwindow.label_79.clear()\n cls.__ui_mainwindow.label_80.clear()\n\n @classmethod\n def refresh_exam_result_id_validity_error_message(cls):\n cls.__ui_mainwindow.label_32.clear()\n\n @classmethod\n def display_school_class_id_invalid_to_view_result_message(cls):\n cls.__ui_mainwindow.label_81.setText('School Class ID Invalid To View')\n\n @classmethod\n def refresh_school_class_details_table_on_view_exam_result_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n\n @classmethod\n def refresh_school_class_id_invalid_to_view_exam_result_error_label(cls):\n cls.__ui_mainwindow.label_81.clear()\n <mask token>\n\n @classmethod\n def display_no_exam_result_id_selected_message(cls):\n cls.__ui_mainwindow.label_81.setText('No Exam Result ID Selected')\n\n @classmethod\n def refresh_school_class_id_input_box_on_view_exam_result_details_page(cls\n ):\n cls.__ui_mainwindow.lineEdit_23.clear()\n\n @classmethod\n def refresh_view_exam_details_by_id_page(cls):\n cls.__ui_mainwindow.label_18.setText('Exam ID : ')\n cls.__ui_mainwindow.tableWidget_7.clear()\n cls.__ui_mainwindow.label_67.clear()\n cls.__ui_mainwindow.label_68.clear()\n cls.__ui_mainwindow.label_69.clear()\n cls.__ui_mainwindow.label_70.clear()\n cls.__ui_mainwindow.label_71.clear()\n cls.__ui_mainwindow.tableWidget_27.clear()\n cls.__ui_mainwindow.tableWidget_28.clear()\n cls.__ui_mainwindow.tableWidget_29.clear()\n cls.__ui_mainwindow.tableWidget_30.clear()\n cls.__ui_mainwindow.tableWidget_31.clear()\n\n @classmethod\n def refresh_students_table_on_view_exam_result_details_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n <mask token>\n <mask token>\n", "step-4": "<mask token>\n\n\nclass TeacherGUI:\n\n def __init__(self):\n pass\n\n @classmethod\n def setup(cls, ui_mainwindow):\n cls.__ui_mainwindow = ui_mainwindow\n\n @classmethod\n def display_all_active_school_classes(cls, school_classes):\n cls.__ui_mainwindow.tableWidget_14.clear()\n row = 0\n col = 0\n for school_class_id, in school_classes:\n school_class_text = 'Class ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_14.setItem(row, col,\n school_class_item)\n if col >= 4:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_all_exams(cls, all_exams):\n cls.__ui_mainwindow.tableWidget_5.clear()\n row = 0\n col = 0\n for exam_id, in all_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_5.setItem(row, col, exam_item)\n if col >= 9:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_not_completed_exams(cls, not_completed_exams):\n cls.__ui_mainwindow.tableWidget_16.clear()\n row = 0\n col = 0\n for exam_id, in not_completed_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_16.setItem(row, col, exam_item)\n if col >= 6:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_ready_to_be_marked_exams(cls, ready_to_be_marked_exams):\n cls.__ui_mainwindow.tableWidget_17.clear()\n row = 0\n col = 0\n for exam_id, in ready_to_be_marked_exams:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_17.setItem(row, col, exam_item)\n if col >= 3:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_single_answer_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_SingleAnswerQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText('A ' + option_A_text)\n cls.__ui_dialog.label_4.setText('B ' + option_B_text)\n cls.__ui_dialog.label_5.setText('C ' + option_C_text)\n cls.__ui_dialog.label_6.setText('D ' + option_D_text)\n cls.__ui_dialog.label_7.setText('E ' + option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_multiple_answers_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_MultipleAnswersQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText(option_A_text)\n cls.__ui_dialog.label_4.setText(option_B_text)\n cls.__ui_dialog.label_5.setText(option_C_text)\n cls.__ui_dialog.label_6.setText(option_D_text)\n cls.__ui_dialog.label_7.setText(option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_essay_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_EssayQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n if question_body == '':\n cls.__ui_dialog.label.setText('Question Body')\n else:\n cls.__ui_dialog.label.setText(question_body)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def close_dialog(cls):\n cls.__dialog.close()\n\n @classmethod\n def get_single_answer_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n if question_body == '':\n return None\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n if option_A_text == '':\n return None\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n if option_B_text == '':\n return None\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n if option_C_text == '':\n return None\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n if option_D_text == '':\n return None\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n if option_E_text == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_3.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_4.text()\n if phrase_tag_text == '':\n return None\n correct_answers_list = []\n if cls.__ui_mainwindow.radioButton.isChecked():\n correct_answers_list.append('A')\n if cls.__ui_mainwindow.radioButton_2.isChecked():\n correct_answers_list.append('B')\n if cls.__ui_mainwindow.radioButton_5.isChecked():\n correct_answers_list.append('C')\n if cls.__ui_mainwindow.radioButton_3.isChecked():\n correct_answers_list.append('D')\n if cls.__ui_mainwindow.radioButton_4.isChecked():\n correct_answers_list.append('E')\n if correct_answers_list == []:\n return None\n if len(correct_answers_list) > 1:\n return None\n return (question_body, option_A_text, option_B_text, option_C_text,\n option_D_text, option_E_text, year_level, phrase_tag_text,\n correct_answers_list)\n\n @classmethod\n def get_multiple_answers_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()\n if question_body == '':\n return None\n option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()\n if option_A_text == '':\n return None\n option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()\n if option_B_text == '':\n return None\n option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()\n if option_C_text == '':\n return None\n option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()\n if option_D_text == '':\n return None\n option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()\n if option_E_text == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_25.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_7.text()\n if phrase_tag_text == '':\n return None\n correct_answers_list = []\n if cls.__ui_mainwindow.checkBox.isChecked():\n correct_answers_list.append('A')\n if cls.__ui_mainwindow.checkBox_2.isChecked():\n correct_answers_list.append('B')\n if cls.__ui_mainwindow.checkBox_3.isChecked():\n correct_answers_list.append('C')\n if cls.__ui_mainwindow.checkBox_4.isChecked():\n correct_answers_list.append('D')\n if cls.__ui_mainwindow.checkBox_5.isChecked():\n correct_answers_list.append('E')\n if correct_answers_list == []:\n return None\n if len(correct_answers_list) > 4:\n return None\n return (question_body, option_A_text, option_B_text, option_C_text,\n option_D_text, option_E_text, year_level, phrase_tag_text,\n correct_answers_list)\n\n @classmethod\n def get_essay_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n if question_body == '':\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_26.text()\n if year_level_text == '':\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_27.text()\n if phrase_tag_text == '':\n return None\n return question_body, year_level, phrase_tag_text\n\n @classmethod\n def display_all_active_questions(cls, active_questions_tuple):\n row = 0\n col = 0\n for question_pk_tuple in active_questions_tuple:\n question_pk = question_pk_tuple[0]\n question_text = 'Question ' + str(question_pk)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget.setItem(row, col, question_item)\n if col >= 7:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_create_single_answer_question_success(cls):\n cls.__ui_mainwindow.label_4.setText(\n 'Create Single Answer Question Success')\n\n @classmethod\n def display_invalid_single_answer_question_creation_message(cls):\n cls.__ui_mainwindow.label_4.setText(\n 'Invalid Single Answer Question Creation')\n\n @classmethod\n def display_create_multiple_answers_question_success(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Create Multiple Answers Question Success')\n\n @classmethod\n def display_invalid_multiple_answers_question_creation_message(cls):\n cls.__ui_mainwindow.label_11.setText(\n 'Invalid Multiple Answers Question Creation')\n\n @classmethod\n def display_invalid_essay_question_creation_message(cls):\n cls.__ui_mainwindow.label_42.setText('Invalid Essay Question Creation')\n\n @classmethod\n def display_create_essay_question_success(cls):\n cls.__ui_mainwindow.label_42.setText('Create Essay Question Success')\n\n @classmethod\n def display_invalid_modification_message(cls):\n cls.__ui_mainwindow.label_57.setText('Invalid Modification')\n\n @classmethod\n def refresh_create_single_answer_question_page(cls):\n cls.__ui_mainwindow.textEdit.clear()\n cls.__ui_mainwindow.textEdit_2.clear()\n cls.__ui_mainwindow.textEdit_3.clear()\n cls.__ui_mainwindow.textEdit_4.clear()\n cls.__ui_mainwindow.textEdit_5.clear()\n cls.__ui_mainwindow.textEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_3.clear()\n cls.__ui_mainwindow.lineEdit_4.clear()\n cls.__ui_mainwindow.radioButton.setChecked(False)\n cls.__ui_mainwindow.radioButton_2.setChecked(False)\n cls.__ui_mainwindow.radioButton_3.setChecked(False)\n cls.__ui_mainwindow.radioButton_4.setChecked(False)\n cls.__ui_mainwindow.radioButton_5.setChecked(False)\n <mask token>\n\n @classmethod\n def refresh_view_or_modify_question_page(cls):\n cls.__ui_mainwindow.lineEdit_5.clear()\n cls.__ui_mainwindow.label_45.setText('Question ID: ')\n cls.__ui_mainwindow.label_47.setText('Question Type: ')\n cls.__ui_mainwindow.label_57.clear()\n cls.__ui_mainwindow.label_12.clear()\n cls.__ui_mainwindow.textEdit_7.clear()\n cls.__ui_mainwindow.textEdit_8.clear()\n cls.__ui_mainwindow.textEdit_9.clear()\n cls.__ui_mainwindow.textEdit_10.clear()\n cls.__ui_mainwindow.textEdit_11.clear()\n cls.__ui_mainwindow.textEdit_20.clear()\n cls.__ui_mainwindow.lineEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_8.clear()\n cls.__ui_mainwindow.lineEdit_28.clear()\n cls.__ui_mainwindow.radioButton_6.setDisabled(False)\n cls.__ui_mainwindow.radioButton_7.setDisabled(False)\n cls.__ui_mainwindow.radioButton_8.setDisabled(False)\n cls.__ui_mainwindow.radioButton_9.setDisabled(False)\n cls.__ui_mainwindow.radioButton_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_8.setDisabled(False)\n cls.__ui_mainwindow.textEdit_9.setDisabled(False)\n cls.__ui_mainwindow.textEdit_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_11.setDisabled(False)\n cls.__ui_mainwindow.textEdit_20.setDisabled(False)\n cls.__ui_mainwindow.radioButton_6.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_6.setChecked(False)\n cls.__ui_mainwindow.radioButton_7.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_7.setChecked(False)\n cls.__ui_mainwindow.radioButton_8.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_8.setChecked(False)\n cls.__ui_mainwindow.radioButton_9.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_9.setChecked(False)\n cls.__ui_mainwindow.radioButton_10.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_10.setChecked(False)\n\n @classmethod\n def refresh_create_essay_question_page(cls):\n cls.__ui_mainwindow.textEdit_19.clear()\n cls.__ui_mainwindow.lineEdit_26.clear()\n cls.__ui_mainwindow.lineEdit_27.clear()\n\n @classmethod\n def refresh_create_exam_page(cls):\n cls.__ui_mainwindow.tableWidget_3.clear()\n cls.__ui_mainwindow.tableWidget_4.clear()\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.lineEdit_13.clear()\n\n @classmethod\n def get_question_id_to_load(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_5.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def load_single_answer_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answer = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answer == 'A':\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n elif correct_answer == 'B':\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n elif correct_answer == 'C':\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n elif correct_answer == 'D':\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n elif correct_answer == 'E':\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_multiple_answers_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answers = question_details[11]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n if correct_answers.count('A') == 1:\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n if correct_answers.count('B') == 1:\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n if correct_answers.count('C') == 1:\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n if correct_answers.count('D') == 1:\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n if correct_answers.count('E') == 1:\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_essay_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n cls.__ui_mainwindow.label_45.setText('Question ID: ' + str(question_id)\n )\n cls.__ui_mainwindow.label_47.setText('Question Type: ' + str(\n question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.radioButton_6.setDisabled(True)\n cls.__ui_mainwindow.radioButton_7.setDisabled(True)\n cls.__ui_mainwindow.radioButton_8.setDisabled(True)\n cls.__ui_mainwindow.radioButton_9.setDisabled(True)\n cls.__ui_mainwindow.radioButton_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_8.setDisabled(True)\n cls.__ui_mainwindow.textEdit_9.setDisabled(True)\n cls.__ui_mainwindow.textEdit_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_11.setDisabled(True)\n cls.__ui_mainwindow.textEdit_20.setDisabled(True)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n\n @classmethod\n def display_question_id_invalid_to_load_message(cls):\n cls.__ui_mainwindow.label_12.setText('Invalid Question ID To Load')\n\n @classmethod\n def display_modification_success_message(cls):\n cls.__ui_mainwindow.label_57.setText('Modification Success')\n\n @classmethod\n def display_invalid_school_class_id_message(cls):\n cls.__ui_mainwindow.label_14.setText('Invalid School Class ID')\n cls.__ui_mainwindow.tableWidget_15.clear()\n\n @classmethod\n def get_question_type_to_modify(cls):\n question_type_text = cls.__ui_mainwindow.label_47.text()\n if question_type_text == 'Question Type: Single Answer':\n return 'Single Answer'\n elif question_type_text == 'Question Type: Multiple Answers':\n return 'Multiple Answers'\n elif question_type_text == 'Question Type: Essay':\n return 'Essay'\n\n @classmethod\n def get_single_answer_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answer = cls.get_single_correct_answer_to_modify()\n if correct_answer == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answer)\n\n @classmethod\n def get_multiple_answers_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answers = cls.get_multiple_correct_answers_to_modify()\n if correct_answers == None:\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body, option_A_text, option_B_text,\n option_C_text, option_D_text, option_E_text, correct_answers)\n\n @classmethod\n def get_essay_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n try:\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n except:\n return None\n try:\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n except:\n return None\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n if question_tag == '':\n return None\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n if question_body == '':\n return None\n return (question_pk, question_type, points, year_level,\n question_tag, question_body)\n\n @classmethod\n def get_question_id_to_modify(cls):\n question_id_text = cls.__ui_mainwindow.label_45.text()\n question_id_text_split = question_id_text.split()\n question_id = int(question_id_text_split.pop())\n return question_id\n\n @classmethod\n def get_single_correct_answer_to_modify(cls):\n correct_answer = ''\n if cls.__ui_mainwindow.radioButton_6.isChecked():\n correct_answer = correct_answer + 'A'\n if cls.__ui_mainwindow.radioButton_7.isChecked():\n correct_answer = correct_answer + 'B'\n if cls.__ui_mainwindow.radioButton_8.isChecked():\n correct_answer = correct_answer + 'C'\n if cls.__ui_mainwindow.radioButton_9.isChecked():\n correct_answer = correct_answer + 'D'\n if cls.__ui_mainwindow.radioButton_10.isChecked():\n correct_answer = correct_answer + 'E'\n if len(correct_answer) == 0:\n return None\n if len(correct_answer) > 1:\n return None\n return correct_answer\n\n @classmethod\n def get_multiple_correct_answers_to_modify(cls):\n correct_answers = ''\n if cls.__ui_mainwindow.radioButton_6.isChecked():\n correct_answers = correct_answers + 'A'\n if cls.__ui_mainwindow.radioButton_7.isChecked():\n correct_answers = correct_answers + 'B'\n if cls.__ui_mainwindow.radioButton_8.isChecked():\n correct_answers = correct_answers + 'C'\n if cls.__ui_mainwindow.radioButton_9.isChecked():\n correct_answers = correct_answers + 'D'\n if cls.__ui_mainwindow.radioButton_10.isChecked():\n correct_answers = correct_answers + 'E'\n if len(correct_answers) == 0:\n return None\n if len(correct_answers) > 4:\n return None\n return correct_answers\n\n @classmethod\n def get_school_class_id_to_view_students(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_9.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def display_school_class_details(cls, school_class_details):\n cls.__ui_mainwindow.tableWidget_15.clear()\n row = 0\n col = 0\n for student, in school_class_details:\n student_item = QTableWidgetItem(student)\n cls.__ui_mainwindow.tableWidget_15.setItem(row, col, student_item)\n if col >= 1:\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def refresh_view_school_class_details_page(cls):\n cls.__ui_mainwindow.label_14.clear()\n\n @classmethod\n def get_number_of_questions_in_current_exam(cls):\n number_of_questions = 0\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_3.item(row, col) != None:\n number_of_questions += 1\n row += 1\n return number_of_questions\n\n @classmethod\n def get_number_of_school_classes_in_current_exam(cls):\n number_of_school_classes = 0\n row = 0\n col = 0\n for counter in range(5):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) != None:\n number_of_school_classes += 1\n row += 1\n return number_of_school_classes\n\n @classmethod\n def display_number_of_questions_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Questions Are Full In Current Exam')\n\n @classmethod\n def display_number_of_school_classes_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Classes Are Full In Current Exam')\n\n @classmethod\n def display_no_question_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No Question In Current Exam')\n\n @classmethod\n def display_no_school_class_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText('No School Class In Current Exam')\n <mask token>\n\n @classmethod\n def display_school_class_id_already_added_to_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Class ID Already Added To Current Exam')\n\n @classmethod\n def display_question_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('Question ID Invalid')\n\n @classmethod\n def display_school_class_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText('School CLass ID Invalid')\n\n @classmethod\n def display_question_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'Question ID Not Aleady In Current Exam')\n\n @classmethod\n def display_school_class_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\n 'School Class ID Not Aleady In Current Exam')\n\n @classmethod\n def display_create_exam_success_message(cls):\n cls.__ui_mainwindow.label_17.setText('Create Exam Success')\n\n @classmethod\n def refresh_mark_exam_drop_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n @classmethod\n def get_question_id_to_add_to_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_10.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def get_school_class_id_to_add_to_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_11.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def get_question_id_to_remove_from_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_12.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def get_school_class_id_to_remove_from_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_13.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def add_question_id_to_current_exam(cls, question_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_3.item(row, col) == None:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_3.setItem(row, col,\n question_item)\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def add_school_class_id_to_current_exam(cls, school_class_id):\n row = 0\n col = 0\n for counter in range(10):\n if cls.__ui_mainwindow.tableWidget_4.item(row, col) == None:\n school_class_text = 'CLass ' + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_4.setItem(row, col,\n school_class_item)\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def remove_question_id_from_current_exam(cls, question_id):\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id_in_exam = int(question_text_split.pop())\n if question_id_in_exam == question_id:\n cls.__ui_mainwindow.tableWidget_3.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n\n @classmethod\n def remove_school_class_id_from_current_exam(cls, school_class_id):\n col = 0\n for row in range(5):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id_in_exam = int(school_class_text_split.pop())\n if school_class_id_in_exam == school_class_id:\n cls.__ui_mainwindow.tableWidget_4.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_13.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n <mask token>\n\n @classmethod\n def is_school_class_id_already_added_to_current_exam(cls, school_class_id):\n string_of_school_classes_ids_in_current_exam = (cls.\n get_string_of_school_classes_ids_in_current_exam())\n list_of_school_classes_ids = (\n string_of_school_classes_ids_in_current_exam.split(' '))\n return list_of_school_classes_ids.count(str(school_class_id)) == 1\n\n @classmethod\n def get_string_of_question_ids_in_current_exam(cls):\n string_of_question_ids = ''\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if question_item != None:\n question_text = question_item.text()\n question_text_split = question_text.split(' ')\n question_id = question_text_split.pop()\n string_of_question_ids = (string_of_question_ids +\n question_id + ' ')\n return string_of_question_ids.rstrip()\n\n @classmethod\n def get_string_of_school_classes_ids_in_current_exam(cls):\n string_of_school_classes_ids = ''\n col = 0\n for row in range(10):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col\n )\n if school_class_item != None:\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(' ')\n school_class_id = school_class_text_split.pop()\n string_of_school_classes_ids = (\n string_of_school_classes_ids + school_class_id + ' ')\n return string_of_school_classes_ids.rstrip()\n\n @classmethod\n def get_exam_id_to_mark(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_20.item(0, 0)\n exam_text = exam_item.text()\n exam_text_split = exam_text.split(' ')\n exam_id_text = exam_text_split.pop()\n return int(exam_id_text)\n\n @classmethod\n def display_exam_id_on_marking_exam_page(cls, exam_id):\n cls.__ui_mainwindow.label_49.setText('Exam ID: ' + str(exam_id))\n\n @classmethod\n def display_students_full_names_with_questions_ready_to_be_marked(cls,\n students_names_list):\n cls.__ui_mainwindow.tableWidget_6.clear()\n row = 0\n col = 0\n for student_name in students_names_list:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_6.setItem(row, col, student_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_student_name_to_mark_answers(cls):\n student_item = cls.__ui_mainwindow.tableWidget_19.item(0, 0)\n student_name = student_item.text()\n return student_name\n\n @classmethod\n def get_exam_id_to_mark_student_answers(cls):\n exam_id_text = cls.__ui_mainwindow.label_49.text()\n exam_id_text_split = exam_id_text.split(' ')\n exam_id = exam_id_text_split.pop()\n return int(exam_id)\n <mask token>\n\n @classmethod\n def display_student_id_on_mark_student_answers_page(cls, student_id):\n student_id_text = 'Student ID: ' + str(student_id)\n cls.__ui_mainwindow.label_63.setText(student_id_text)\n\n @classmethod\n def display_student_name_on_mark_student_answers_page(cls, student_name):\n student_name_text = 'Student Name: ' + str(student_name)\n cls.__ui_mainwindow.label_50.setText(student_name_text)\n\n @classmethod\n def display_questions_ready_to_be_marked(cls, questions_ids_tuple):\n cls.__ui_mainwindow.tableWidget_25.clear()\n row = 0\n col = 0\n for question_id, in questions_ids_tuple:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_25.setItem(row, col, question_item)\n row += 1\n\n @classmethod\n def get_question_id_to_mark(cls):\n question_item = cls.__ui_mainwindow.tableWidget_26.item(0, 0)\n if question_item == None:\n return None\n question_id_text = question_item.text()\n question_id_text_list = question_id_text.split(' ')\n question_id = question_id_text_list.pop()\n return int(question_id)\n\n @classmethod\n def get_exam_id_on_marking_question_page(cls):\n exam_id_text = cls.__ui_mainwindow.label_62.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def get_student_id_on_marking_question_page(cls):\n student_id_text = cls.__ui_mainwindow.label_63.text()\n student_id_text_list = student_id_text.split(' ')\n student_id = student_id_text_list.pop()\n return int(student_id)\n\n @classmethod\n def setup_essay_question_ui_dialog_to_mark(cls, question_details):\n question_body = question_details[0]\n student_answer = question_details[1]\n available_points = question_details[2]\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_MarkingEssayQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label_2.setText(question_body)\n cls.__ui_dialog.label_3.setText(student_answer)\n cls.__ui_dialog.label_4.setText('Total Available Points: ' + str(\n available_points))\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n cls.__dialog.show()\n return cls.__ui_dialog\n\n @classmethod\n def get_essay_question_marked_points(cls):\n points_text = cls.__ui_dialog.lineEdit.text()\n return int(points_text)\n\n @classmethod\n def refresh_drop_question_to_mark_box(cls):\n cls.__ui_mainwindow.tableWidget_26.clear()\n\n @classmethod\n def refresh_mark_student_questions_answers_page(cls):\n cls.__ui_mainwindow.label_62.clear()\n cls.__ui_mainwindow.label_63.clear()\n cls.__ui_mainwindow.label_50.clear()\n\n @classmethod\n def display_no_more_questions_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No More Questions To Mark')\n\n @classmethod\n def display_marked_exams(cls, marked_exams_ids):\n cls.__ui_mainwindow.tableWidget_18.clear()\n row = 0\n col = 0\n for exam_id, in marked_exams_ids:\n exam_text = 'Exam ' + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_18.setItem(row, col, exam_item)\n if col >= 4:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def display_no_question_selected_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText('No Question Selected To Mark')\n\n @classmethod\n def refresh_drop_student_to_mark_questions_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n @classmethod\n def get_exam_id_to_release_result(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_21.item(0, 0)\n if exam_item == None:\n return None\n exam_id_text = exam_item.text()\n exam_id_text_list = exam_id_text.split(' ')\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def display_result_released_exams(cls, result_released_exams_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for exam_id, in result_released_exams_ids:\n exam_text = 'Exam ' + str(exam_id) + ' Result'\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_item)\n if col >= 9:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def refresh_drop_exam_to_release_result_box(cls):\n cls.__ui_mainwindow.tableWidget_21.clear()\n\n @classmethod\n def display_exam_results(cls, exam_results_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for exam_result_id, in exam_results_ids:\n exam_result_text = 'Exam ' + str(exam_result_id) + ' Result'\n exam_result_item = QTableWidgetItem(exam_result_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col,\n exam_result_item)\n if col >= 9:\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_exam_result_id_to_load_details(cls):\n exam_result_id_text = cls.__ui_mainwindow.lineEdit_22.text()\n return int(exam_result_id_text)\n <mask token>\n\n @classmethod\n def display_exam_result_id_on_view_exam_result_details_page(cls,\n exam_result_id):\n cls.__ui_mainwindow.label_33.setText('Exam Result ID: ' + str(\n exam_result_id))\n\n @classmethod\n def get_school_class_id_to_view_exam_result(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_23.text()\n try:\n school_class_id = int(school_class_id_text)\n except:\n return None\n return school_class_id\n\n @classmethod\n def display_students_full_names_to_view_exam_result(cls,\n students_full_names):\n cls.__ui_mainwindow.tableWidget_13.clear()\n row = 0\n col = 0\n for student_full_name, in students_full_names:\n student_item = QTableWidgetItem(student_full_name)\n cls.__ui_mainwindow.tableWidget_13.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def get_student_full_name_to_view_exam_result(cls):\n student_item = cls.__ui_mainwindow.tableWidget_22.item(0, 0)\n student_name_text = student_item.text()\n return student_name_text\n\n @classmethod\n def get_exam_result_id_on_view_exam_result_page(cls):\n exam_result_id_text = cls.__ui_mainwindow.label_33.text()\n exam_result_id_text_list = exam_result_id_text.split(' ')\n exam_result_id = exam_result_id_text_list.pop()\n try:\n exam_result_id_int = int(exam_result_id)\n return exam_result_id_int\n except:\n return None\n\n @classmethod\n def display_student_exam_result_details(cls, exam_result_details):\n student_id = exam_result_details[0]\n student_full_name = exam_result_details[1]\n date_of_birth = exam_result_details[2]\n school_class_id = exam_result_details[3]\n exam_id = exam_result_details[4]\n total_available_points = exam_result_details[5]\n total_points_gained = exam_result_details[6]\n average_percentage_mark = exam_result_details[7]\n cls.__ui_mainwindow.label_58.setText(str(student_id))\n cls.__ui_mainwindow.label_72.setText(str(student_full_name))\n cls.__ui_mainwindow.label_75.setText(str(date_of_birth))\n cls.__ui_mainwindow.label_76.setText(str(school_class_id))\n cls.__ui_mainwindow.label_77.setText(str(exam_id))\n cls.__ui_mainwindow.label_78.setText(str(total_available_points))\n cls.__ui_mainwindow.label_79.setText(str(total_points_gained))\n cls.__ui_mainwindow.label_80.setText(str(average_percentage_mark) +\n ' %')\n\n @classmethod\n def get_exam_id_to_view_details(cls):\n exam_id_text = cls.__ui_mainwindow.lineEdit_14.text()\n if exam_id_text == '':\n return None\n try:\n exam_id = int(exam_id_text)\n return exam_id\n except:\n return None\n <mask token>\n\n @classmethod\n def display_questions_on_view_exam_details_page(cls, questions_ids):\n cls.__ui_mainwindow.tableWidget_7.clear()\n questions_ids_list = cls.make_string_to_list(questions_ids)\n row = 0\n col = 0\n for question_id in questions_ids_list:\n question_text = 'Question ' + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_7.setItem(row, col, question_item)\n row += 1\n\n @classmethod\n def display_first_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_first_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_27.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_27.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_first_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_67.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_second_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_second_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_28.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_28.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_second_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_68.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_third_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_third_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_29.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_29.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_third_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_69.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fourth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fourth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_30.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_30.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fourth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_70.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def display_fifth_school_class_details_on_view_exam_details_page(cls,\n school_class_id, students_full_names):\n cls.display_fifth_school_class_id_on_view_exam_details_page(\n school_class_id)\n cls.__ui_mainwindow.tableWidget_31.clear()\n row = 0\n col = 0\n for student_name, in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_31.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fifth_school_class_id_on_view_exam_details_page(cls,\n school_class_id):\n cls.__ui_mainwindow.label_71.setText('CLass ' + str(school_class_id))\n\n @classmethod\n def make_string_to_list(cls, any_string):\n any_string = str(any_string)\n any_list = any_string.split(' ')\n return any_list\n\n @classmethod\n def refresh_drop_student_to_view_exam_result_details_box(cls):\n cls.__ui_mainwindow.tableWidget_22.clear()\n\n @classmethod\n def display_exam_result_id_invalid_message(cls):\n cls.__ui_mainwindow.label_32.setText('Exam Result ID Invalid')\n\n @classmethod\n def refresh_load_exam_result_details_page(cls):\n cls.__ui_mainwindow.label_33.clear()\n cls.__ui_mainwindow.tableWidget_12.clear()\n cls.__ui_mainwindow.lineEdit_23.clear()\n cls.__ui_mainwindow.tableWidget_13.clear()\n cls.__ui_mainwindow.tableWidget_22.clear()\n cls.__ui_mainwindow.label_58.clear()\n cls.__ui_mainwindow.label_72.clear()\n cls.__ui_mainwindow.label_75.clear()\n cls.__ui_mainwindow.label_76.clear()\n cls.__ui_mainwindow.label_77.clear()\n cls.__ui_mainwindow.label_78.clear()\n cls.__ui_mainwindow.label_79.clear()\n cls.__ui_mainwindow.label_80.clear()\n\n @classmethod\n def refresh_exam_result_id_validity_error_message(cls):\n cls.__ui_mainwindow.label_32.clear()\n\n @classmethod\n def display_school_class_id_invalid_to_view_result_message(cls):\n cls.__ui_mainwindow.label_81.setText('School Class ID Invalid To View')\n\n @classmethod\n def refresh_school_class_details_table_on_view_exam_result_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n\n @classmethod\n def refresh_school_class_id_invalid_to_view_exam_result_error_label(cls):\n cls.__ui_mainwindow.label_81.clear()\n\n @classmethod\n def refresh_student_exam_result_details(cls):\n cls.__ui_mainwindow.label_58.clear()\n cls.__ui_mainwindow.label_72.clear()\n cls.__ui_mainwindow.label_75.clear()\n cls.__ui_mainwindow.label_76.clear()\n cls.__ui_mainwindow.label_77.clear()\n cls.__ui_mainwindow.label_78.clear()\n cls.__ui_mainwindow.label_79.clear()\n cls.__ui_mainwindow.label_80.clear()\n\n @classmethod\n def display_no_exam_result_id_selected_message(cls):\n cls.__ui_mainwindow.label_81.setText('No Exam Result ID Selected')\n\n @classmethod\n def refresh_school_class_id_input_box_on_view_exam_result_details_page(cls\n ):\n cls.__ui_mainwindow.lineEdit_23.clear()\n\n @classmethod\n def refresh_view_exam_details_by_id_page(cls):\n cls.__ui_mainwindow.label_18.setText('Exam ID : ')\n cls.__ui_mainwindow.tableWidget_7.clear()\n cls.__ui_mainwindow.label_67.clear()\n cls.__ui_mainwindow.label_68.clear()\n cls.__ui_mainwindow.label_69.clear()\n cls.__ui_mainwindow.label_70.clear()\n cls.__ui_mainwindow.label_71.clear()\n cls.__ui_mainwindow.tableWidget_27.clear()\n cls.__ui_mainwindow.tableWidget_28.clear()\n cls.__ui_mainwindow.tableWidget_29.clear()\n cls.__ui_mainwindow.tableWidget_30.clear()\n cls.__ui_mainwindow.tableWidget_31.clear()\n\n @classmethod\n def refresh_students_table_on_view_exam_result_details_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n <mask token>\n <mask token>\n", "step-5": "from PyQt5 import QtCore, QtGui, QtWidgets\nfrom PyQt5.QtWidgets import QLineEdit, QRadioButton, QPushButton, QTableWidgetItem, QTableWidget, QApplication, QMainWindow, QDateEdit, QLabel, QDialog, QTextEdit, QCheckBox\nfrom PyQt5.QtCore import QDate, QTime, QDateTime, Qt\n\n\nfrom OOPCourseWorkTwo.GUI.SingleAnswerQuestionDialog import Ui_SingleAnswerQuestionDialog\nfrom OOPCourseWorkTwo.GUI.MultipleAnswersQuestionDialog import Ui_MultipleAnswersQuestionDialog\nfrom OOPCourseWorkTwo.GUI.EssayQuestionDialog import Ui_EssayQuestionDialog\nfrom OOPCourseWorkTwo.GUI.MarkingEssayQuestionDialog import Ui_MarkingEssayQuestionDialog\n\n\nclass TeacherGUI():\n\n def __init__(self):\n pass\n\n @classmethod\n def setup(cls, ui_mainwindow):\n cls.__ui_mainwindow = ui_mainwindow\n\n @classmethod\n def display_all_active_school_classes(cls, school_classes):\n cls.__ui_mainwindow.tableWidget_14.clear()\n row = 0\n col = 0\n for (school_class_id, ) in school_classes:\n school_class_text = \"Class \" + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_14.setItem(row, col, school_class_item)\n if (col >= 4):\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_all_exams(cls, all_exams):\n cls.__ui_mainwindow.tableWidget_5.clear()\n row = 0\n col = 0\n for (exam_id, ) in all_exams:\n exam_text = \"Exam \" + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_5.setItem(row, col, exam_item)\n if (col >= 9):\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_not_completed_exams(cls, not_completed_exams):\n cls.__ui_mainwindow.tableWidget_16.clear()\n row = 0\n col = 0\n for (exam_id, ) in not_completed_exams:\n exam_text = \"Exam \" + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_16.setItem(row, col, exam_item)\n if (col >= 6):\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def display_ready_to_be_marked_exams(cls, ready_to_be_marked_exams):\n cls.__ui_mainwindow.tableWidget_17.clear()\n row = 0\n col = 0\n for (exam_id, ) in ready_to_be_marked_exams:\n exam_text = \"Exam \" + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_17.setItem(row, col, exam_item)\n if (col >= 3):\n col = 0\n row += 1\n else:\n col += 1\n\n\n @classmethod\n def display_single_answer_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_SingleAnswerQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText(\"A \" + option_A_text)\n cls.__ui_dialog.label_4.setText(\"B \" + option_B_text)\n cls.__ui_dialog.label_5.setText(\"C \" + option_C_text)\n cls.__ui_dialog.label_6.setText(\"D \" + option_D_text)\n cls.__ui_dialog.label_7.setText(\"E \" + option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_multiple_answers_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_MultipleAnswersQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label.setText(question_body)\n cls.__ui_dialog.label_3.setText(option_A_text)\n cls.__ui_dialog.label_4.setText(option_B_text)\n cls.__ui_dialog.label_5.setText(option_C_text)\n cls.__ui_dialog.label_6.setText(option_D_text)\n cls.__ui_dialog.label_7.setText(option_E_text)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n @classmethod\n def display_essay_question_dialog_preview(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_EssayQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n if (question_body == \"\"):\n cls.__ui_dialog.label.setText(\"Question Body\")\n else:\n cls.__ui_dialog.label.setText(question_body)\n cls.__dialog.show()\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n\n\n @classmethod\n def close_dialog(cls):\n cls.__dialog.close()\n\n @classmethod\n def get_single_answer_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit.toPlainText()\n if (question_body == \"\"):\n return None\n option_A_text = cls.__ui_mainwindow.textEdit_2.toPlainText()\n if (option_A_text == \"\"):\n return None\n option_B_text = cls.__ui_mainwindow.textEdit_3.toPlainText()\n if (option_B_text == \"\"):\n return None\n option_C_text = cls.__ui_mainwindow.textEdit_6.toPlainText()\n if (option_C_text == \"\"):\n return None\n option_D_text = cls.__ui_mainwindow.textEdit_4.toPlainText()\n if (option_D_text == \"\"):\n return None\n option_E_text = cls.__ui_mainwindow.textEdit_5.toPlainText()\n if (option_E_text == \"\"):\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_3.text()\n if (year_level_text == \"\"):\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_4.text()\n if (phrase_tag_text == \"\"):\n return None\n correct_answers_list = []\n if (cls.__ui_mainwindow.radioButton.isChecked()):\n correct_answers_list.append(\"A\")\n if (cls.__ui_mainwindow.radioButton_2.isChecked()):\n correct_answers_list.append(\"B\")\n if (cls.__ui_mainwindow.radioButton_5.isChecked()):\n correct_answers_list.append(\"C\")\n if (cls.__ui_mainwindow.radioButton_3.isChecked()):\n correct_answers_list.append(\"D\")\n if (cls.__ui_mainwindow.radioButton_4.isChecked()):\n correct_answers_list.append(\"E\")\n if (correct_answers_list == []):\n return None\n if (len(correct_answers_list) > 1):\n return None\n return (question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, year_level, phrase_tag_text, correct_answers_list)\n\n @classmethod\n def get_multiple_answers_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit_14.toPlainText()\n if (question_body == \"\"):\n return None\n option_A_text = cls.__ui_mainwindow.textEdit_13.toPlainText()\n if (option_A_text == \"\"):\n return None\n option_B_text = cls.__ui_mainwindow.textEdit_15.toPlainText()\n if (option_B_text == \"\"):\n return None\n option_C_text = cls.__ui_mainwindow.textEdit_16.toPlainText()\n if (option_C_text == \"\"):\n return None\n option_D_text = cls.__ui_mainwindow.textEdit_17.toPlainText()\n if (option_D_text == \"\"):\n return None\n option_E_text = cls.__ui_mainwindow.textEdit_18.toPlainText()\n if (option_E_text == \"\"):\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_25.text()\n if (year_level_text == \"\"):\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_7.text()\n if (phrase_tag_text == \"\"):\n return None\n correct_answers_list = []\n if (cls.__ui_mainwindow.checkBox.isChecked()):\n correct_answers_list.append(\"A\")\n if (cls.__ui_mainwindow.checkBox_2.isChecked()):\n correct_answers_list.append(\"B\")\n if (cls.__ui_mainwindow.checkBox_3.isChecked()):\n correct_answers_list.append(\"C\")\n if (cls.__ui_mainwindow.checkBox_4.isChecked()):\n correct_answers_list.append(\"D\")\n if (cls.__ui_mainwindow.checkBox_5.isChecked()):\n correct_answers_list.append(\"E\")\n if (correct_answers_list == []):\n return None\n if (len(correct_answers_list) > 4):\n return None\n return (question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, year_level, phrase_tag_text, correct_answers_list)\n\n @classmethod\n def get_essay_question_details(cls):\n question_body = cls.__ui_mainwindow.textEdit_19.toPlainText()\n if (question_body == \"\"):\n return None\n year_level_text = cls.__ui_mainwindow.lineEdit_26.text()\n if (year_level_text == \"\"):\n return None\n try:\n year_level = int(year_level_text)\n except:\n return None\n phrase_tag_text = cls.__ui_mainwindow.lineEdit_27.text()\n if (phrase_tag_text == \"\"):\n return None\n return (question_body, year_level, phrase_tag_text)\n\n\n @classmethod\n def display_all_active_questions(cls, active_questions_tuple):\n row = 0\n col = 0\n for question_pk_tuple in active_questions_tuple:\n question_pk = question_pk_tuple[0]\n question_text = \"Question \" + str(question_pk)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget.setItem(row, col, question_item)\n if (col >= 7):\n col = 0\n row += 1\n else:\n col += 1\n\n\n @classmethod\n def display_create_single_answer_question_success(cls):\n cls.__ui_mainwindow.label_4.setText(\"Create Single Answer Question Success\")\n\n @classmethod\n def display_invalid_single_answer_question_creation_message(cls):\n cls.__ui_mainwindow.label_4.setText(\"Invalid Single Answer Question Creation\")\n\n @classmethod\n def display_create_multiple_answers_question_success(cls):\n cls.__ui_mainwindow.label_11.setText(\"Create Multiple Answers Question Success\")\n\n @classmethod\n def display_invalid_multiple_answers_question_creation_message(cls):\n cls.__ui_mainwindow.label_11.setText(\"Invalid Multiple Answers Question Creation\")\n\n @classmethod\n def display_invalid_essay_question_creation_message(cls):\n cls.__ui_mainwindow.label_42.setText(\"Invalid Essay Question Creation\")\n\n @classmethod\n def display_create_essay_question_success(cls):\n cls.__ui_mainwindow.label_42.setText(\"Create Essay Question Success\")\n\n @classmethod\n def display_invalid_modification_message(cls):\n cls.__ui_mainwindow.label_57.setText(\"Invalid Modification\")\n\n\n @classmethod\n def refresh_create_single_answer_question_page(cls):\n cls.__ui_mainwindow.textEdit.clear()\n cls.__ui_mainwindow.textEdit_2.clear()\n cls.__ui_mainwindow.textEdit_3.clear()\n cls.__ui_mainwindow.textEdit_4.clear()\n cls.__ui_mainwindow.textEdit_5.clear()\n cls.__ui_mainwindow.textEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_3.clear()\n cls.__ui_mainwindow.lineEdit_4.clear()\n cls.__ui_mainwindow.radioButton.setChecked(False)\n cls.__ui_mainwindow.radioButton_2.setChecked(False)\n cls.__ui_mainwindow.radioButton_3.setChecked(False)\n cls.__ui_mainwindow.radioButton_4.setChecked(False)\n cls.__ui_mainwindow.radioButton_5.setChecked(False)\n\n @classmethod\n def refresh_create_multiple_answers_question_page(cls):\n cls.__ui_mainwindow.textEdit_14.clear()\n cls.__ui_mainwindow.textEdit_13.clear()\n cls.__ui_mainwindow.textEdit_15.clear()\n cls.__ui_mainwindow.textEdit_16.clear()\n cls.__ui_mainwindow.textEdit_17.clear()\n cls.__ui_mainwindow.textEdit_18.clear()\n cls.__ui_mainwindow.lineEdit_25.clear()\n cls.__ui_mainwindow.lineEdit_7.clear()\n cls.__ui_mainwindow.checkBox.setChecked(False)\n cls.__ui_mainwindow.checkBox_2.setChecked(False)\n cls.__ui_mainwindow.checkBox_3.setChecked(False)\n cls.__ui_mainwindow.checkBox_4.setChecked(False)\n cls.__ui_mainwindow.checkBox_5.setChecked(False)\n\n @classmethod\n def refresh_view_or_modify_question_page(cls):\n cls.__ui_mainwindow.lineEdit_5.clear()\n cls.__ui_mainwindow.label_45.setText(\"Question ID: \")\n cls.__ui_mainwindow.label_47.setText(\"Question Type: \")\n cls.__ui_mainwindow.label_57.clear()\n cls.__ui_mainwindow.label_12.clear()\n cls.__ui_mainwindow.textEdit_7.clear()\n cls.__ui_mainwindow.textEdit_8.clear()\n cls.__ui_mainwindow.textEdit_9.clear()\n cls.__ui_mainwindow.textEdit_10.clear()\n cls.__ui_mainwindow.textEdit_11.clear()\n cls.__ui_mainwindow.textEdit_20.clear()\n cls.__ui_mainwindow.lineEdit_6.clear()\n cls.__ui_mainwindow.lineEdit_8.clear()\n cls.__ui_mainwindow.lineEdit_28.clear()\n cls.__ui_mainwindow.radioButton_6.setDisabled(False)\n cls.__ui_mainwindow.radioButton_7.setDisabled(False)\n cls.__ui_mainwindow.radioButton_8.setDisabled(False)\n cls.__ui_mainwindow.radioButton_9.setDisabled(False)\n cls.__ui_mainwindow.radioButton_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_8.setDisabled(False)\n cls.__ui_mainwindow.textEdit_9.setDisabled(False)\n cls.__ui_mainwindow.textEdit_10.setDisabled(False)\n cls.__ui_mainwindow.textEdit_11.setDisabled(False)\n cls.__ui_mainwindow.textEdit_20.setDisabled(False)\n cls.__ui_mainwindow.radioButton_6.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_6.setChecked(False)\n cls.__ui_mainwindow.radioButton_7.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_7.setChecked(False)\n cls.__ui_mainwindow.radioButton_8.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_8.setChecked(False)\n cls.__ui_mainwindow.radioButton_9.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_9.setChecked(False)\n cls.__ui_mainwindow.radioButton_10.setAutoExclusive(False)\n cls.__ui_mainwindow.radioButton_10.setChecked(False)\n\n @classmethod\n def refresh_create_essay_question_page(cls):\n cls.__ui_mainwindow.textEdit_19.clear()\n cls.__ui_mainwindow.lineEdit_26.clear()\n cls.__ui_mainwindow.lineEdit_27.clear()\n\n @classmethod\n def refresh_create_exam_page(cls):\n cls.__ui_mainwindow.tableWidget_3.clear()\n cls.__ui_mainwindow.tableWidget_4.clear()\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.lineEdit_13.clear()\n\n @classmethod\n def get_question_id_to_load(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_5.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def load_single_answer_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answer = question_details[11]\n\n cls.__ui_mainwindow.label_45.setText(\"Question ID: \" + str(question_id))\n cls.__ui_mainwindow.label_47.setText(\"Question Type: \" + str(question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n\n if (correct_answer == \"A\"):\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n elif (correct_answer == \"B\"):\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n elif (correct_answer == \"C\"):\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n elif (correct_answer == \"D\"):\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n elif (correct_answer == \"E\"):\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n @classmethod\n def load_multiple_answers_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n option_A_text = question_details[6]\n option_B_text = question_details[7]\n option_C_text = question_details[8]\n option_D_text = question_details[9]\n option_E_text = question_details[10]\n correct_answers = question_details[11]\n\n cls.__ui_mainwindow.label_45.setText(\"Question ID: \" + str(question_id))\n cls.__ui_mainwindow.label_47.setText(\"Question Type: \" + str(question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.textEdit_8.setText(option_A_text)\n cls.__ui_mainwindow.textEdit_9.setText(option_B_text)\n cls.__ui_mainwindow.textEdit_10.setText(option_C_text)\n cls.__ui_mainwindow.textEdit_11.setText(option_D_text)\n cls.__ui_mainwindow.textEdit_20.setText(option_E_text)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n\n if (correct_answers.count(\"A\") == 1):\n cls.__ui_mainwindow.radioButton_6.setChecked(True)\n if (correct_answers.count(\"B\") == 1):\n cls.__ui_mainwindow.radioButton_7.setChecked(True)\n if (correct_answers.count(\"C\") == 1):\n cls.__ui_mainwindow.radioButton_8.setChecked(True)\n if (correct_answers.count(\"D\") == 1):\n cls.__ui_mainwindow.radioButton_9.setChecked(True)\n if (correct_answers.count(\"E\") == 1):\n cls.__ui_mainwindow.radioButton_10.setChecked(True)\n\n\n @classmethod\n def load_essay_question_details(cls, question_details):\n question_id = question_details[0]\n question_type = question_details[1]\n points = question_details[2]\n year_level = question_details[3]\n question_tag = question_details[4]\n question_body = question_details[5]\n\n cls.__ui_mainwindow.label_45.setText(\"Question ID: \" + str(question_id))\n cls.__ui_mainwindow.label_47.setText(\"Question Type: \" + str(question_type))\n cls.__ui_mainwindow.textEdit_7.setText(question_body)\n cls.__ui_mainwindow.radioButton_6.setDisabled(True)\n cls.__ui_mainwindow.radioButton_7.setDisabled(True)\n cls.__ui_mainwindow.radioButton_8.setDisabled(True)\n cls.__ui_mainwindow.radioButton_9.setDisabled(True)\n cls.__ui_mainwindow.radioButton_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_8.setDisabled(True)\n cls.__ui_mainwindow.textEdit_9.setDisabled(True)\n cls.__ui_mainwindow.textEdit_10.setDisabled(True)\n cls.__ui_mainwindow.textEdit_11.setDisabled(True)\n cls.__ui_mainwindow.textEdit_20.setDisabled(True)\n cls.__ui_mainwindow.lineEdit_6.setText(str(year_level))\n cls.__ui_mainwindow.lineEdit_8.setText(question_tag)\n cls.__ui_mainwindow.lineEdit_28.setText(str(points))\n\n @classmethod\n def display_question_id_invalid_to_load_message(cls):\n cls.__ui_mainwindow.label_12.setText(\"Invalid Question ID To Load\")\n\n @classmethod\n def display_modification_success_message(cls):\n cls.__ui_mainwindow.label_57.setText(\"Modification Success\")\n\n @classmethod\n def display_invalid_school_class_id_message(cls):\n cls.__ui_mainwindow.label_14.setText(\"Invalid School Class ID\")\n cls.__ui_mainwindow.tableWidget_15.clear()\n\n\n @classmethod\n def get_question_type_to_modify(cls):\n question_type_text = cls.__ui_mainwindow.label_47.text()\n if (question_type_text == \"Question Type: Single Answer\"):\n return \"Single Answer\"\n elif (question_type_text == \"Question Type: Multiple Answers\"):\n return \"Multiple Answers\"\n elif (question_type_text == \"Question Type: Essay\"):\n return \"Essay\"\n\n @classmethod\n def get_single_answer_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answer = cls.get_single_correct_answer_to_modify()\n if (correct_answer == None):\n return None\n return (question_pk, question_type, points, year_level, question_tag,question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, correct_answer)\n\n @classmethod\n def get_multiple_answers_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n option_A_text = cls.__ui_mainwindow.textEdit_8.toPlainText()\n option_B_text = cls.__ui_mainwindow.textEdit_9.toPlainText()\n option_C_text = cls.__ui_mainwindow.textEdit_10.toPlainText()\n option_D_text = cls.__ui_mainwindow.textEdit_11.toPlainText()\n option_E_text = cls.__ui_mainwindow.textEdit_20.toPlainText()\n correct_answers = cls.get_multiple_correct_answers_to_modify()\n if (correct_answers == None):\n return None\n return (question_pk, question_type, points, year_level, question_tag,question_body, option_A_text, option_B_text, option_C_text, option_D_text, option_E_text, correct_answers)\n\n @classmethod\n def get_essay_question_details_to_modify(cls):\n question_pk = cls.get_question_id_to_modify()\n question_type = cls.get_question_type_to_modify()\n try:\n points = int(cls.__ui_mainwindow.lineEdit_28.text())\n except:\n return None\n try:\n year_level = int(cls.__ui_mainwindow.lineEdit_6.text())\n except:\n return None\n question_tag = cls.__ui_mainwindow.lineEdit_8.text()\n if (question_tag == \"\"):\n return None\n question_body = cls.__ui_mainwindow.textEdit_7.toPlainText()\n if (question_body == \"\"):\n return None\n return (question_pk, question_type, points, year_level, question_tag, question_body)\n\n @classmethod\n def get_question_id_to_modify(cls):\n question_id_text = cls.__ui_mainwindow.label_45.text()\n question_id_text_split = question_id_text.split()\n question_id = int(question_id_text_split.pop())\n return question_id\n\n\n @classmethod\n def get_single_correct_answer_to_modify(cls):\n correct_answer = \"\"\n if (cls.__ui_mainwindow.radioButton_6.isChecked()):\n correct_answer = correct_answer + \"A\"\n if (cls.__ui_mainwindow.radioButton_7.isChecked()):\n correct_answer = correct_answer + \"B\"\n if (cls.__ui_mainwindow.radioButton_8.isChecked()):\n correct_answer = correct_answer + \"C\"\n if (cls.__ui_mainwindow.radioButton_9.isChecked()):\n correct_answer = correct_answer + \"D\"\n if (cls.__ui_mainwindow.radioButton_10.isChecked()):\n correct_answer = correct_answer + \"E\"\n if (len(correct_answer) == 0):\n return None\n if (len(correct_answer) > 1):\n return None\n return correct_answer\n\n @classmethod\n def get_multiple_correct_answers_to_modify(cls):\n correct_answers = \"\"\n if (cls.__ui_mainwindow.radioButton_6.isChecked()):\n correct_answers = correct_answers + \"A\"\n if (cls.__ui_mainwindow.radioButton_7.isChecked()):\n correct_answers = correct_answers + \"B\"\n if (cls.__ui_mainwindow.radioButton_8.isChecked()):\n correct_answers = correct_answers + \"C\"\n if (cls.__ui_mainwindow.radioButton_9.isChecked()):\n correct_answers = correct_answers + \"D\"\n if (cls.__ui_mainwindow.radioButton_10.isChecked()):\n correct_answers = correct_answers + \"E\"\n if (len(correct_answers) == 0):\n return None\n if (len(correct_answers) > 4):\n return None\n return correct_answers\n\n @classmethod\n def get_school_class_id_to_view_students(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_9.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def display_school_class_details(cls, school_class_details):\n cls.__ui_mainwindow.tableWidget_15.clear()\n row = 0\n col = 0\n for (student, ) in school_class_details:\n student_item = QTableWidgetItem(student)\n cls.__ui_mainwindow.tableWidget_15.setItem(row, col, student_item)\n if (col >= 1):\n col = 0\n row += 1\n else:\n col += 1\n\n @classmethod\n def refresh_view_school_class_details_page(cls):\n cls.__ui_mainwindow.label_14.clear()\n\n @classmethod\n def get_number_of_questions_in_current_exam(cls):\n number_of_questions = 0\n row = 0\n col = 0\n for counter in range(10):\n if (cls.__ui_mainwindow.tableWidget_3.item(row, col) != None):\n number_of_questions += 1\n row += 1\n return number_of_questions\n\n @classmethod\n def get_number_of_school_classes_in_current_exam(cls):\n number_of_school_classes = 0\n row = 0\n col = 0\n for counter in range(5):\n if (cls.__ui_mainwindow.tableWidget_4.item(row, col) != None):\n number_of_school_classes += 1\n row += 1\n return number_of_school_classes\n\n @classmethod\n def display_number_of_questions_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"Questions Are Full In Current Exam\")\n\n @classmethod\n def display_number_of_school_classes_full_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"School Classes Are Full In Current Exam\")\n\n @classmethod\n def display_no_question_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"No Question In Current Exam\")\n\n @classmethod\n def display_no_school_class_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"No School Class In Current Exam\")\n\n @classmethod\n def display_question_id_already_added_to_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"Question ID Already Added To Current Exam\")\n\n @classmethod\n def display_school_class_id_already_added_to_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"School Class ID Already Added To Current Exam\")\n\n @classmethod\n def display_question_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"Question ID Invalid\")\n\n @classmethod\n def display_school_class_id_invalid_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"School CLass ID Invalid\")\n\n @classmethod\n def display_question_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"Question ID Not Aleady In Current Exam\")\n\n @classmethod\n def display_school_class_id_not_already_in_current_exam_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"School Class ID Not Aleady In Current Exam\")\n\n @classmethod\n def display_create_exam_success_message(cls):\n cls.__ui_mainwindow.label_17.setText(\"Create Exam Success\")\n\n @classmethod\n def refresh_mark_exam_drop_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n\n @classmethod\n def get_question_id_to_add_to_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_10.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def get_school_class_id_to_add_to_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_11.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def get_question_id_to_remove_from_exam(cls):\n question_id_text = cls.__ui_mainwindow.lineEdit_12.text()\n try:\n question_id = int(question_id_text)\n return question_id\n except:\n return None\n\n @classmethod\n def get_school_class_id_to_remove_from_exam(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_13.text()\n try:\n school_class_id = int(school_class_id_text)\n return school_class_id\n except:\n return None\n\n @classmethod\n def add_question_id_to_current_exam(cls, question_id):\n row = 0\n col = 0\n for counter in range(10):\n if (cls.__ui_mainwindow.tableWidget_3.item(row, col) == None):\n question_text = \"Question \" + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_3.setItem(row, col, question_item)\n cls.__ui_mainwindow.lineEdit_10.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def add_school_class_id_to_current_exam(cls, school_class_id):\n row = 0\n col = 0\n for counter in range(10):\n if (cls.__ui_mainwindow.tableWidget_4.item(row, col) == None):\n school_class_text = \"CLass \" + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_4.setItem(row, col, school_class_item)\n cls.__ui_mainwindow.lineEdit_11.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n row += 1\n\n @classmethod\n def remove_question_id_from_current_exam(cls, question_id):\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if (question_item != None):\n question_text = question_item.text()\n question_text_split = question_text.split(\" \")\n question_id_in_exam = int(question_text_split.pop())\n if (question_id_in_exam == question_id):\n cls.__ui_mainwindow.tableWidget_3.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_12.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n\n @classmethod\n def remove_school_class_id_from_current_exam(cls, school_class_id):\n col = 0\n for row in range(5):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col)\n if (school_class_item != None):\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(\" \")\n school_class_id_in_exam = int(school_class_text_split.pop())\n if (school_class_id_in_exam == school_class_id):\n cls.__ui_mainwindow.tableWidget_4.takeItem(row, col)\n cls.__ui_mainwindow.lineEdit_13.clear()\n cls.__ui_mainwindow.label_17.clear()\n return\n\n @classmethod\n def is_question_id_already_added_to_current_exam(cls, question_id):\n string_of_question_ids_in_current_exam = cls.get_string_of_question_ids_in_current_exam()\n list_of_question_ids = string_of_question_ids_in_current_exam.split(\" \")\n return list_of_question_ids.count(str(question_id)) == 1\n\n @classmethod\n def is_school_class_id_already_added_to_current_exam(cls, school_class_id):\n string_of_school_classes_ids_in_current_exam = cls.get_string_of_school_classes_ids_in_current_exam()\n list_of_school_classes_ids = string_of_school_classes_ids_in_current_exam.split(\" \")\n return list_of_school_classes_ids.count(str(school_class_id)) == 1\n\n @classmethod\n def get_string_of_question_ids_in_current_exam(cls):\n string_of_question_ids = \"\"\n col = 0\n for row in range(10):\n question_item = cls.__ui_mainwindow.tableWidget_3.item(row, col)\n if (question_item != None):\n question_text = question_item.text()\n question_text_split = question_text.split(\" \")\n question_id = question_text_split.pop()\n string_of_question_ids = string_of_question_ids + question_id + \" \"\n return string_of_question_ids.rstrip()\n\n @classmethod\n def get_string_of_school_classes_ids_in_current_exam(cls):\n string_of_school_classes_ids = \"\"\n col = 0\n for row in range(10):\n school_class_item = cls.__ui_mainwindow.tableWidget_4.item(row, col)\n if (school_class_item != None):\n school_class_text = school_class_item.text()\n school_class_text_split = school_class_text.split(\" \")\n school_class_id = school_class_text_split.pop()\n string_of_school_classes_ids = string_of_school_classes_ids + school_class_id + \" \"\n return string_of_school_classes_ids.rstrip()\n\n @classmethod\n def get_exam_id_to_mark(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_20.item(0, 0)\n exam_text = exam_item.text()\n exam_text_split = exam_text.split(\" \")\n exam_id_text = exam_text_split.pop()\n return int(exam_id_text)\n\n\n @classmethod\n def display_exam_id_on_marking_exam_page(cls, exam_id):\n cls.__ui_mainwindow.label_49.setText(\"Exam ID: \" + str(exam_id))\n\n @classmethod\n def display_students_full_names_with_questions_ready_to_be_marked(cls, students_names_list):\n cls.__ui_mainwindow.tableWidget_6.clear()\n row = 0\n col = 0\n for student_name in students_names_list:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_6.setItem(row, col, student_item)\n if (col >= 4):\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_student_name_to_mark_answers(cls):\n student_item = cls.__ui_mainwindow.tableWidget_19.item(0,0)\n student_name = student_item.text()\n return student_name\n\n @classmethod\n def get_exam_id_to_mark_student_answers(cls):\n exam_id_text = cls.__ui_mainwindow.label_49.text()\n exam_id_text_split = exam_id_text.split(\" \")\n exam_id = exam_id_text_split.pop()\n return int(exam_id)\n\n @classmethod\n def display_exam_id_on_mark_student_answers_page(cls, exam_id):\n exam_id_text = \"Exam ID: \" + str(exam_id)\n cls.__ui_mainwindow.label_62.setText(exam_id_text)\n\n @classmethod\n def display_student_id_on_mark_student_answers_page(cls, student_id):\n student_id_text = \"Student ID: \" + str(student_id)\n cls.__ui_mainwindow.label_63.setText(student_id_text)\n\n @classmethod\n def display_student_name_on_mark_student_answers_page(cls,student_name):\n student_name_text = \"Student Name: \" + str(student_name)\n cls.__ui_mainwindow.label_50.setText(student_name_text)\n\n @classmethod\n def display_questions_ready_to_be_marked(cls, questions_ids_tuple):\n cls.__ui_mainwindow.tableWidget_25.clear()\n row = 0\n col = 0\n for (question_id,) in questions_ids_tuple:\n question_text = \"Question \" + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_25.setItem(row, col, question_item)\n row += 1\n\n @classmethod\n def get_question_id_to_mark(cls):\n question_item = cls.__ui_mainwindow.tableWidget_26.item(0,0)\n if (question_item == None):\n return None\n question_id_text = question_item.text()\n question_id_text_list = question_id_text.split(\" \")\n question_id = question_id_text_list.pop()\n return int(question_id)\n\n @classmethod\n def get_exam_id_on_marking_question_page(cls):\n exam_id_text = cls.__ui_mainwindow.label_62.text()\n exam_id_text_list = exam_id_text.split(\" \")\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def get_student_id_on_marking_question_page(cls):\n student_id_text = cls.__ui_mainwindow.label_63.text()\n student_id_text_list = student_id_text.split(\" \")\n student_id = student_id_text_list.pop()\n return int(student_id)\n\n @classmethod\n def setup_essay_question_ui_dialog_to_mark(cls, question_details):\n question_body = question_details[0]\n student_answer = question_details[1]\n available_points = question_details[2]\n cls.__dialog = QtWidgets.QDialog()\n cls.__ui_dialog = Ui_MarkingEssayQuestionDialog()\n cls.__ui_dialog.setupUi(cls.__dialog)\n cls.__ui_dialog.label_2.setText(question_body)\n cls.__ui_dialog.label_3.setText(student_answer)\n cls.__ui_dialog.label_4.setText(\"Total Available Points: \" + str(available_points))\n cls.__ui_dialog.pushButton.clicked.connect(cls.close_dialog)\n cls.__dialog.show()\n return cls.__ui_dialog\n\n @classmethod\n def get_essay_question_marked_points(cls):\n points_text = cls.__ui_dialog.lineEdit.text()\n return int(points_text)\n\n @classmethod\n def refresh_drop_question_to_mark_box(cls):\n cls.__ui_mainwindow.tableWidget_26.clear()\n\n @classmethod\n def refresh_mark_student_questions_answers_page(cls):\n cls.__ui_mainwindow.label_62.clear()\n cls.__ui_mainwindow.label_63.clear()\n cls.__ui_mainwindow.label_50.clear()\n\n @classmethod\n def display_no_more_questions_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText(\"No More Questions To Mark\")\n\n @classmethod\n def display_marked_exams(cls, marked_exams_ids):\n cls.__ui_mainwindow.tableWidget_18.clear()\n row = 0\n col = 0\n for (exam_id,) in marked_exams_ids:\n exam_text = \"Exam \" + str(exam_id)\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_18.setItem(row, col, exam_item)\n if (col >= 4):\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def display_no_question_selected_to_mark_message(cls):\n cls.__ui_mainwindow.label_66.setText(\"No Question Selected To Mark\")\n\n @classmethod\n def refresh_drop_student_to_mark_questions_box(cls):\n cls.__ui_mainwindow.tableWidget_19.clear()\n\n @classmethod\n def get_exam_id_to_release_result(cls):\n exam_item = cls.__ui_mainwindow.tableWidget_21.item(0,0)\n if (exam_item == None):\n return None\n exam_id_text = exam_item.text()\n exam_id_text_list = exam_id_text.split(\" \")\n exam_id = exam_id_text_list.pop()\n return int(exam_id)\n\n @classmethod\n def display_result_released_exams(cls, result_released_exams_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for (exam_id,) in result_released_exams_ids:\n exam_text = \"Exam \" + str(exam_id) + \" Result\"\n exam_item = QTableWidgetItem(exam_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_item)\n if (col >= 9):\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def refresh_drop_exam_to_release_result_box(cls):\n cls.__ui_mainwindow.tableWidget_21.clear()\n\n @classmethod\n def display_exam_results(cls, exam_results_ids):\n cls.__ui_mainwindow.tableWidget_11.clear()\n row = 0\n col = 0\n for (exam_result_id, ) in exam_results_ids:\n exam_result_text = \"Exam \" + str(exam_result_id) + \" Result\"\n exam_result_item = QTableWidgetItem(exam_result_text)\n cls.__ui_mainwindow.tableWidget_11.setItem(row, col, exam_result_item)\n if (col >= 9):\n row += 1\n col = 0\n else:\n col += 1\n\n @classmethod\n def get_exam_result_id_to_load_details(cls):\n exam_result_id_text = cls.__ui_mainwindow.lineEdit_22.text()\n return int(exam_result_id_text)\n\n @classmethod\n def display_school_classes_to_view_exam_result_details(cls, school_classes_ids):\n school_classes_ids_list = cls.make_string_to_list(school_classes_ids)\n cls.__ui_mainwindow.tableWidget_12.clear()\n row = 0\n col = 0\n for school_class_id in school_classes_ids_list:\n school_class_text = \"Class \" + str(school_class_id)\n school_class_item = QTableWidgetItem(school_class_text)\n cls.__ui_mainwindow.tableWidget_12.setItem(row, col, school_class_item)\n row += 1\n\n @classmethod\n def display_exam_result_id_on_view_exam_result_details_page(cls, exam_result_id):\n cls.__ui_mainwindow.label_33.setText(\"Exam Result ID: \" + str(exam_result_id))\n\n @classmethod\n def get_school_class_id_to_view_exam_result(cls):\n school_class_id_text = cls.__ui_mainwindow.lineEdit_23.text()\n try:\n school_class_id = int(school_class_id_text)\n except:\n return None\n return school_class_id\n\n @classmethod\n def display_students_full_names_to_view_exam_result(cls, students_full_names):\n cls.__ui_mainwindow.tableWidget_13.clear()\n row = 0\n col = 0\n for (student_full_name, ) in students_full_names:\n student_item = QTableWidgetItem(student_full_name)\n cls.__ui_mainwindow.tableWidget_13.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def get_student_full_name_to_view_exam_result(cls):\n student_item = cls.__ui_mainwindow.tableWidget_22.item(0, 0)\n student_name_text = student_item.text()\n return student_name_text\n\n @classmethod\n def get_exam_result_id_on_view_exam_result_page(cls):\n exam_result_id_text = cls.__ui_mainwindow.label_33.text()\n exam_result_id_text_list = exam_result_id_text.split(\" \")\n exam_result_id = exam_result_id_text_list.pop()\n try:\n exam_result_id_int = int(exam_result_id)\n return exam_result_id_int\n except:\n return None\n\n @classmethod\n def display_student_exam_result_details(cls, exam_result_details):\n student_id = exam_result_details[0]\n student_full_name = exam_result_details[1]\n date_of_birth = exam_result_details[2]\n school_class_id = exam_result_details[3]\n exam_id = exam_result_details[4]\n total_available_points = exam_result_details[5]\n total_points_gained = exam_result_details[6]\n average_percentage_mark = exam_result_details[7]\n cls.__ui_mainwindow.label_58.setText(str(student_id))\n cls.__ui_mainwindow.label_72.setText(str(student_full_name))\n cls.__ui_mainwindow.label_75.setText(str(date_of_birth))\n cls.__ui_mainwindow.label_76.setText(str(school_class_id))\n cls.__ui_mainwindow.label_77.setText(str(exam_id))\n cls.__ui_mainwindow.label_78.setText(str(total_available_points))\n cls.__ui_mainwindow.label_79.setText(str(total_points_gained))\n cls.__ui_mainwindow.label_80.setText(str(average_percentage_mark) + \" %\")\n\n @classmethod\n def get_exam_id_to_view_details(cls):\n exam_id_text = cls.__ui_mainwindow.lineEdit_14.text()\n if (exam_id_text == \"\"):\n return None\n try:\n exam_id = int(exam_id_text)\n return exam_id\n except:\n return None\n\n @classmethod\n def diaplay_exam_id_on_view_exam_details_page(cls, exam_id):\n cls.__ui_mainwindow.label_18.setText(\"Exam ID: \" + str(exam_id))\n\n @classmethod\n def display_questions_on_view_exam_details_page(cls, questions_ids):\n cls.__ui_mainwindow.tableWidget_7.clear()\n questions_ids_list = cls.make_string_to_list(questions_ids)\n row = 0\n col = 0\n for question_id in questions_ids_list:\n question_text = \"Question \" + str(question_id)\n question_item = QTableWidgetItem(question_text)\n cls.__ui_mainwindow.tableWidget_7.setItem(row, col, question_item)\n row += 1\n\n @classmethod\n def display_first_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names):\n cls.display_first_school_class_id_on_view_exam_details_page(school_class_id)\n cls.__ui_mainwindow.tableWidget_27.clear()\n row = 0\n col = 0\n for (student_name, ) in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_27.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_first_school_class_id_on_view_exam_details_page(cls, school_class_id):\n cls.__ui_mainwindow.label_67.setText(\"CLass \" + str(school_class_id))\n\n @classmethod\n def display_second_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names):\n cls.display_second_school_class_id_on_view_exam_details_page(school_class_id)\n cls.__ui_mainwindow.tableWidget_28.clear()\n row = 0\n col = 0\n for (student_name, ) in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_28.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_second_school_class_id_on_view_exam_details_page(cls, school_class_id):\n cls.__ui_mainwindow.label_68.setText(\"CLass \" + str(school_class_id))\n\n @classmethod\n def display_third_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names):\n cls.display_third_school_class_id_on_view_exam_details_page(school_class_id)\n cls.__ui_mainwindow.tableWidget_29.clear()\n row = 0\n col = 0\n for (student_name, ) in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_29.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_third_school_class_id_on_view_exam_details_page(cls, school_class_id):\n cls.__ui_mainwindow.label_69.setText(\"CLass \" + str(school_class_id))\n\n @classmethod\n def display_fourth_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names):\n cls.display_fourth_school_class_id_on_view_exam_details_page(school_class_id)\n cls.__ui_mainwindow.tableWidget_30.clear()\n row = 0\n col = 0\n for (student_name, ) in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_30.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fourth_school_class_id_on_view_exam_details_page(cls, school_class_id):\n cls.__ui_mainwindow.label_70.setText(\"CLass \" + str(school_class_id))\n\n @classmethod\n def display_fifth_school_class_details_on_view_exam_details_page(cls, school_class_id, students_full_names):\n cls.display_fifth_school_class_id_on_view_exam_details_page(school_class_id)\n cls.__ui_mainwindow.tableWidget_31.clear()\n row = 0\n col = 0\n for (student_name, ) in students_full_names:\n student_item = QTableWidgetItem(student_name)\n cls.__ui_mainwindow.tableWidget_31.setItem(row, col, student_item)\n row += 1\n\n @classmethod\n def display_fifth_school_class_id_on_view_exam_details_page(cls, school_class_id):\n cls.__ui_mainwindow.label_71.setText(\"CLass \" + str(school_class_id))\n\n @classmethod\n def make_string_to_list(cls, any_string):\n any_string = str(any_string)\n any_list = any_string.split(\" \")\n return any_list\n\n @classmethod\n def refresh_drop_student_to_view_exam_result_details_box(cls):\n cls.__ui_mainwindow.tableWidget_22.clear()\n\n @classmethod\n def display_exam_result_id_invalid_message(cls):\n cls.__ui_mainwindow.label_32.setText(\"Exam Result ID Invalid\")\n\n @classmethod\n def refresh_load_exam_result_details_page(cls):\n cls.__ui_mainwindow.label_33.clear()\n cls.__ui_mainwindow.tableWidget_12.clear()\n cls.__ui_mainwindow.lineEdit_23.clear()\n cls.__ui_mainwindow.tableWidget_13.clear()\n cls.__ui_mainwindow.tableWidget_22.clear()\n cls.__ui_mainwindow.label_58.clear()\n cls.__ui_mainwindow.label_72.clear()\n cls.__ui_mainwindow.label_75.clear()\n cls.__ui_mainwindow.label_76.clear()\n cls.__ui_mainwindow.label_77.clear()\n cls.__ui_mainwindow.label_78.clear()\n cls.__ui_mainwindow.label_79.clear()\n cls.__ui_mainwindow.label_80.clear()\n\n @classmethod\n def refresh_exam_result_id_validity_error_message(cls):\n cls.__ui_mainwindow.label_32.clear()\n\n @classmethod\n def display_school_class_id_invalid_to_view_result_message(cls):\n cls.__ui_mainwindow.label_81.setText(\"School Class ID Invalid To View\")\n\n @classmethod\n def refresh_school_class_details_table_on_view_exam_result_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n\n @classmethod\n def refresh_school_class_id_invalid_to_view_exam_result_error_label(cls):\n cls.__ui_mainwindow.label_81.clear()\n\n @classmethod\n def refresh_student_exam_result_details(cls):\n cls.__ui_mainwindow.label_58.clear()\n cls.__ui_mainwindow.label_72.clear()\n cls.__ui_mainwindow.label_75.clear()\n cls.__ui_mainwindow.label_76.clear()\n cls.__ui_mainwindow.label_77.clear()\n cls.__ui_mainwindow.label_78.clear()\n cls.__ui_mainwindow.label_79.clear()\n cls.__ui_mainwindow.label_80.clear()\n\n @classmethod\n def display_no_exam_result_id_selected_message(cls):\n cls.__ui_mainwindow.label_81.setText(\"No Exam Result ID Selected\")\n\n @classmethod\n def refresh_school_class_id_input_box_on_view_exam_result_details_page(cls):\n cls.__ui_mainwindow.lineEdit_23.clear()\n\n @classmethod\n def refresh_view_exam_details_by_id_page(cls):\n cls.__ui_mainwindow.label_18.setText(\"Exam ID : \")\n cls.__ui_mainwindow.tableWidget_7.clear()\n cls.__ui_mainwindow.label_67.clear()\n cls.__ui_mainwindow.label_68.clear()\n cls.__ui_mainwindow.label_69.clear()\n cls.__ui_mainwindow.label_70.clear()\n cls.__ui_mainwindow.label_71.clear()\n cls.__ui_mainwindow.tableWidget_27.clear()\n cls.__ui_mainwindow.tableWidget_28.clear()\n cls.__ui_mainwindow.tableWidget_29.clear()\n cls.__ui_mainwindow.tableWidget_30.clear()\n cls.__ui_mainwindow.tableWidget_31.clear()\n\n @classmethod\n def refresh_students_table_on_view_exam_result_details_page(cls):\n cls.__ui_mainwindow.tableWidget_13.clear()\n\n @classmethod\n def refresh_school_classes_table_on_view_exam_result_details_page(cls):\n cls.__ui_mainwindow.tableWidget_12.clear()\n\n\n\n\n\n def __str__(self):\n return (\"This is TeacherGUI Object\")", "step-ids": [ 100, 103, 113, 122, 132 ] }
[ 100, 103, 113, 122, 132 ]
from django.db import models # Create your models here. class GameGenre(models.Model): genreName = models.CharField(max_length=100) genreDescription = models.CharField(max_length=300) def __str__(self): return "%s" % (self.genreName) class Game(models.Model): gameName = models.CharField(max_length=100) genre = models.ForeignKey(GameGenre) def __str__(self): return "%s, %s" % (self.gameName, self.genre) class Players(models.Model): playerName = models.CharField(max_length=100) games = models.ManyToManyField(Game) def __str__(self): return "%s" % (self.playerName)
normal
{ "blob_id": "092242cdb231e09ccf3dd4dccfb6d786c3e4aad2", "index": 8036, "step-1": "<mask token>\n\n\nclass Game(models.Model):\n gameName = models.CharField(max_length=100)\n genre = models.ForeignKey(GameGenre)\n\n def __str__(self):\n return '%s, %s' % (self.gameName, self.genre)\n\n\nclass Players(models.Model):\n playerName = models.CharField(max_length=100)\n games = models.ManyToManyField(Game)\n\n def __str__(self):\n return '%s' % self.playerName\n", "step-2": "<mask token>\n\n\nclass GameGenre(models.Model):\n <mask token>\n <mask token>\n\n def __str__(self):\n return '%s' % self.genreName\n\n\nclass Game(models.Model):\n gameName = models.CharField(max_length=100)\n genre = models.ForeignKey(GameGenre)\n\n def __str__(self):\n return '%s, %s' % (self.gameName, self.genre)\n\n\nclass Players(models.Model):\n playerName = models.CharField(max_length=100)\n games = models.ManyToManyField(Game)\n\n def __str__(self):\n return '%s' % self.playerName\n", "step-3": "<mask token>\n\n\nclass GameGenre(models.Model):\n genreName = models.CharField(max_length=100)\n genreDescription = models.CharField(max_length=300)\n\n def __str__(self):\n return '%s' % self.genreName\n\n\nclass Game(models.Model):\n gameName = models.CharField(max_length=100)\n genre = models.ForeignKey(GameGenre)\n\n def __str__(self):\n return '%s, %s' % (self.gameName, self.genre)\n\n\nclass Players(models.Model):\n playerName = models.CharField(max_length=100)\n games = models.ManyToManyField(Game)\n\n def __str__(self):\n return '%s' % self.playerName\n", "step-4": "from django.db import models\n\n\nclass GameGenre(models.Model):\n genreName = models.CharField(max_length=100)\n genreDescription = models.CharField(max_length=300)\n\n def __str__(self):\n return '%s' % self.genreName\n\n\nclass Game(models.Model):\n gameName = models.CharField(max_length=100)\n genre = models.ForeignKey(GameGenre)\n\n def __str__(self):\n return '%s, %s' % (self.gameName, self.genre)\n\n\nclass Players(models.Model):\n playerName = models.CharField(max_length=100)\n games = models.ManyToManyField(Game)\n\n def __str__(self):\n return '%s' % self.playerName\n", "step-5": "from django.db import models\n\n# Create your models here.\n\n\nclass GameGenre(models.Model):\n\n genreName = models.CharField(max_length=100)\n genreDescription = models.CharField(max_length=300)\n\n def __str__(self):\n return \"%s\" % (self.genreName)\n\n\nclass Game(models.Model):\n\n gameName = models.CharField(max_length=100)\n genre = models.ForeignKey(GameGenre)\n\n def __str__(self):\n return \"%s, %s\" % (self.gameName, self.genre)\n\n\nclass Players(models.Model):\n\n playerName = models.CharField(max_length=100)\n games = models.ManyToManyField(Game)\n\n def __str__(self):\n return \"%s\" % (self.playerName)\n", "step-ids": [ 6, 8, 9, 10, 11 ] }
[ 6, 8, 9, 10, 11 ]
<|reserved_special_token_0|> def topological(above): """Topologically sort a DAG by removing a layer of sources until empty.""" result = [] while above: sources = set(above) - set(flatten(above.values())) result.extend(sources) for node in sources: del above[node] return result <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def topological(above): """Topologically sort a DAG by removing a layer of sources until empty.""" result = [] while above: sources = set(above) - set(flatten(above.values())) result.extend(sources) for node in sources: del above[node] return result <|reserved_special_token_0|> for edge in Array(Input(name))[1:]: above[edge[0]].append(edge[1]) above[edge[1]] print(rosalind_pretty(topological(above))) <|reserved_special_token_1|> <|reserved_special_token_0|> name = 'topological' def topological(above): """Topologically sort a DAG by removing a layer of sources until empty.""" result = [] while above: sources = set(above) - set(flatten(above.values())) result.extend(sources) for node in sources: del above[node] return result above = defaultdict(list) for edge in Array(Input(name))[1:]: above[edge[0]].append(edge[1]) above[edge[1]] print(rosalind_pretty(topological(above))) <|reserved_special_token_1|> from utils import * name = 'topological' def topological(above): """Topologically sort a DAG by removing a layer of sources until empty.""" result = [] while above: sources = set(above) - set(flatten(above.values())) result.extend(sources) for node in sources: del above[node] return result above = defaultdict(list) for edge in Array(Input(name))[1:]: above[edge[0]].append(edge[1]) above[edge[1]] print(rosalind_pretty(topological(above))) <|reserved_special_token_1|> from utils import * name = 'topological' def topological(above): "Topologically sort a DAG by removing a layer of sources until empty." result = [] while above: sources = set(above) - set(flatten(above.values())) result.extend(sources) for node in sources: del above[node] return result above = defaultdict(list) for edge in Array(Input(name))[1:]: above[edge[0]].append(edge[1]) above[edge[1]] print(rosalind_pretty(topological(above)))
flexible
{ "blob_id": "a8ea91797942616779ae0acc884db1e521c7ad28", "index": 3927, "step-1": "<mask token>\n\n\ndef topological(above):\n \"\"\"Topologically sort a DAG by removing a layer of sources until empty.\"\"\"\n result = []\n while above:\n sources = set(above) - set(flatten(above.values()))\n result.extend(sources)\n for node in sources:\n del above[node]\n return result\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef topological(above):\n \"\"\"Topologically sort a DAG by removing a layer of sources until empty.\"\"\"\n result = []\n while above:\n sources = set(above) - set(flatten(above.values()))\n result.extend(sources)\n for node in sources:\n del above[node]\n return result\n\n\n<mask token>\nfor edge in Array(Input(name))[1:]:\n above[edge[0]].append(edge[1])\n above[edge[1]]\nprint(rosalind_pretty(topological(above)))\n", "step-3": "<mask token>\nname = 'topological'\n\n\ndef topological(above):\n \"\"\"Topologically sort a DAG by removing a layer of sources until empty.\"\"\"\n result = []\n while above:\n sources = set(above) - set(flatten(above.values()))\n result.extend(sources)\n for node in sources:\n del above[node]\n return result\n\n\nabove = defaultdict(list)\nfor edge in Array(Input(name))[1:]:\n above[edge[0]].append(edge[1])\n above[edge[1]]\nprint(rosalind_pretty(topological(above)))\n", "step-4": "from utils import *\nname = 'topological'\n\n\ndef topological(above):\n \"\"\"Topologically sort a DAG by removing a layer of sources until empty.\"\"\"\n result = []\n while above:\n sources = set(above) - set(flatten(above.values()))\n result.extend(sources)\n for node in sources:\n del above[node]\n return result\n\n\nabove = defaultdict(list)\nfor edge in Array(Input(name))[1:]:\n above[edge[0]].append(edge[1])\n above[edge[1]]\nprint(rosalind_pretty(topological(above)))\n", "step-5": "from utils import *\n\nname = 'topological'\n\ndef topological(above):\n \"Topologically sort a DAG by removing a layer of sources until empty.\"\n result = []\n while above:\n sources = set(above) - set(flatten(above.values()))\n result.extend(sources)\n for node in sources:\n del above[node]\n return result\n\nabove = defaultdict(list)\nfor edge in Array(Input(name))[1:]:\n above[edge[0]].append(edge[1])\n above[edge[1]]\nprint(rosalind_pretty(topological(above)))\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
<|reserved_special_token_0|> def freqModAvgFunc(dirName): fullList = factorStatFileCreator.directoryFreq(dirName) UA = dirName.split('/')[1] avgList = [] sum = 0 i = 0 while i <= len(fullList) - 2: diff = factorStatFileCreator.diffFunc(fullList[i], fullList[i + 1]) if diff == None: i += 1 else: avgList.append(int(diff)) i += 1 for item in avgList: sum += item if len(avgList) != 0: if UA not in freqAgentDic.keys(): freqAgentDic[UA] = [sum / len(avgList)] else: agentList = freqAgentDic[UA] agentList.append(sum / len(avgList)) freqAgentDic[UA] = agentList <|reserved_special_token_0|> def printFreqDiff(): finalFreqFunc(dirName) finalFreqFunc(dirName2) for keys, vals in freqAgentDic.items(): if len(vals) > 1 and vals[1] > 0: score = vals[0] / vals[1] print('{:<15}: {:.2f}'.format(keys, score)) else: score = 'N/A' print('{:<15}: {}'.format(keys, score)) freqAgentDic[keys] = score return freqAgentDic <|reserved_special_token_0|> def finalLenFunc(dirName): for filename in os.listdir(dirName): file = dirName + filename avgModFunc(file) def printLenDiff(): finalLenFunc(dirName) finalLenFunc(dirName2) for keys, vals in lenAgentDic.items(): if len(vals) > 1 and vals[1] > 0: score = vals[1] / vals[0] print('{:<15}: {:.2f}'.format(keys, score)) else: score = 'N/A' print('{:<15}: {}'.format(keys, score)) lenAgentDic[keys] = score return lenAgentDic def directoryModCont(directory): contentSet = set() newSet = set() listHolder = [] numofReq = 0 UA = directory.split('/')[1] for filename in os.listdir(directory): file = directory + '/' + filename listHolder = factorStatFileCreator.contentCommand(file) newSet = listHolder[0] numofReq += len(listHolder[1]) contentSet = contentSet | newSet newSet = set() if UA not in contAgentDic.keys(): contAgentDic[UA] = [numofReq] else: agentList = contAgentDic[UA] agentList.append(numofReq) contAgentDic[UA] = agentList return contentSet, numofReq def finalContFunc(dirName): for filename in os.listdir(dirName): file = dirName + filename directoryModCont(file) def printContDiff(): finalContFunc(dirName) finalContFunc(dirName2) for keys, vals in contAgentDic.items(): if len(vals) > 1 and vals[1] > 0: score = vals[0] / vals[1] print('{:<15}: {:.2f}'.format(keys, score)) else: score = 'N/A' print('{:<15}: {}'.format(keys, score)) contAgentDic[keys] = score return contAgentDic <|reserved_special_token_1|> <|reserved_special_token_0|> def freqModAvgFunc(dirName): fullList = factorStatFileCreator.directoryFreq(dirName) UA = dirName.split('/')[1] avgList = [] sum = 0 i = 0 while i <= len(fullList) - 2: diff = factorStatFileCreator.diffFunc(fullList[i], fullList[i + 1]) if diff == None: i += 1 else: avgList.append(int(diff)) i += 1 for item in avgList: sum += item if len(avgList) != 0: if UA not in freqAgentDic.keys(): freqAgentDic[UA] = [sum / len(avgList)] else: agentList = freqAgentDic[UA] agentList.append(sum / len(avgList)) freqAgentDic[UA] = agentList def finalFreqFunc(dirName): for filename in os.listdir(dirName): file = dirName + filename freqModAvgFunc(file) def printFreqDiff(): finalFreqFunc(dirName) finalFreqFunc(dirName2) for keys, vals in freqAgentDic.items(): if len(vals) > 1 and vals[1] > 0: score = vals[0] / vals[1] print('{:<15}: {:.2f}'.format(keys, score)) else: score = 'N/A' print('{:<15}: {}'.format(keys, score)) freqAgentDic[keys] = score return freqAgentDic <|reserved_special_token_0|> def finalLenFunc(dirName): for filename in os.listdir(dirName): file = dirName + filename avgModFunc(file) def printLenDiff(): finalLenFunc(dirName) finalLenFunc(dirName2) for keys, vals in lenAgentDic.items(): if len(vals) > 1 and vals[1] > 0: score = vals[1] / vals[0] print('{:<15}: {:.2f}'.format(keys, score)) else: score = 'N/A' print('{:<15}: {}'.format(keys, score)) lenAgentDic[keys] = score return lenAgentDic def directoryModCont(directory): contentSet = set() newSet = set() listHolder = [] numofReq = 0 UA = directory.split('/')[1] for filename in os.listdir(directory): file = directory + '/' + filename listHolder = factorStatFileCreator.contentCommand(file) newSet = listHolder[0] numofReq += len(listHolder[1]) contentSet = contentSet | newSet newSet = set() if UA not in contAgentDic.keys(): contAgentDic[UA] = [numofReq] else: agentList = contAgentDic[UA] agentList.append(numofReq) contAgentDic[UA] = agentList return contentSet, numofReq def finalContFunc(dirName): for filename in os.listdir(dirName): file = dirName + filename directoryModCont(file) def printContDiff(): finalContFunc(dirName) finalContFunc(dirName2) for keys, vals in contAgentDic.items(): if len(vals) > 1 and vals[1] > 0: score = vals[0] / vals[1] print('{:<15}: {:.2f}'.format(keys, score)) else: score = 'N/A' print('{:<15}: {}'.format(keys, score)) contAgentDic[keys] = score return contAgentDic <|reserved_special_token_1|> <|reserved_special_token_0|> def freqModAvgFunc(dirName): fullList = factorStatFileCreator.directoryFreq(dirName) UA = dirName.split('/')[1] avgList = [] sum = 0 i = 0 while i <= len(fullList) - 2: diff = factorStatFileCreator.diffFunc(fullList[i], fullList[i + 1]) if diff == None: i += 1 else: avgList.append(int(diff)) i += 1 for item in avgList: sum += item if len(avgList) != 0: if UA not in freqAgentDic.keys(): freqAgentDic[UA] = [sum / len(avgList)] else: agentList = freqAgentDic[UA] agentList.append(sum / len(avgList)) freqAgentDic[UA] = agentList def finalFreqFunc(dirName): for filename in os.listdir(dirName): file = dirName + filename freqModAvgFunc(file) def printFreqDiff(): finalFreqFunc(dirName) finalFreqFunc(dirName2) for keys, vals in freqAgentDic.items(): if len(vals) > 1 and vals[1] > 0: score = vals[0] / vals[1] print('{:<15}: {:.2f}'.format(keys, score)) else: score = 'N/A' print('{:<15}: {}'.format(keys, score)) freqAgentDic[keys] = score return freqAgentDic def avgModFunc(directory): sum = 0 UA = directory.split('/')[1] byteList = factorStatFileCreator.directoryLen(directory) for item in byteList: sum += item if len(byteList) != 0: if UA not in lenAgentDic.keys(): lenAgentDic[UA] = [sum / len(byteList)] else: agentList = lenAgentDic[UA] agentList.append(sum / len(byteList)) lenAgentDic[UA] = agentList def finalLenFunc(dirName): for filename in os.listdir(dirName): file = dirName + filename avgModFunc(file) def printLenDiff(): finalLenFunc(dirName) finalLenFunc(dirName2) for keys, vals in lenAgentDic.items(): if len(vals) > 1 and vals[1] > 0: score = vals[1] / vals[0] print('{:<15}: {:.2f}'.format(keys, score)) else: score = 'N/A' print('{:<15}: {}'.format(keys, score)) lenAgentDic[keys] = score return lenAgentDic def directoryModCont(directory): contentSet = set() newSet = set() listHolder = [] numofReq = 0 UA = directory.split('/')[1] for filename in os.listdir(directory): file = directory + '/' + filename listHolder = factorStatFileCreator.contentCommand(file) newSet = listHolder[0] numofReq += len(listHolder[1]) contentSet = contentSet | newSet newSet = set() if UA not in contAgentDic.keys(): contAgentDic[UA] = [numofReq] else: agentList = contAgentDic[UA] agentList.append(numofReq) contAgentDic[UA] = agentList return contentSet, numofReq def finalContFunc(dirName): for filename in os.listdir(dirName): file = dirName + filename directoryModCont(file) def printContDiff(): finalContFunc(dirName) finalContFunc(dirName2) for keys, vals in contAgentDic.items(): if len(vals) > 1 and vals[1] > 0: score = vals[0] / vals[1] print('{:<15}: {:.2f}'.format(keys, score)) else: score = 'N/A' print('{:<15}: {}'.format(keys, score)) contAgentDic[keys] = score return contAgentDic <|reserved_special_token_1|> <|reserved_special_token_0|> dirName = 'NoPerms/' dirName2 = 'AllPerms/' freqAgentDic = dict() lenAgentDic = dict() contAgentDic = dict() def freqModAvgFunc(dirName): fullList = factorStatFileCreator.directoryFreq(dirName) UA = dirName.split('/')[1] avgList = [] sum = 0 i = 0 while i <= len(fullList) - 2: diff = factorStatFileCreator.diffFunc(fullList[i], fullList[i + 1]) if diff == None: i += 1 else: avgList.append(int(diff)) i += 1 for item in avgList: sum += item if len(avgList) != 0: if UA not in freqAgentDic.keys(): freqAgentDic[UA] = [sum / len(avgList)] else: agentList = freqAgentDic[UA] agentList.append(sum / len(avgList)) freqAgentDic[UA] = agentList def finalFreqFunc(dirName): for filename in os.listdir(dirName): file = dirName + filename freqModAvgFunc(file) def printFreqDiff(): finalFreqFunc(dirName) finalFreqFunc(dirName2) for keys, vals in freqAgentDic.items(): if len(vals) > 1 and vals[1] > 0: score = vals[0] / vals[1] print('{:<15}: {:.2f}'.format(keys, score)) else: score = 'N/A' print('{:<15}: {}'.format(keys, score)) freqAgentDic[keys] = score return freqAgentDic def avgModFunc(directory): sum = 0 UA = directory.split('/')[1] byteList = factorStatFileCreator.directoryLen(directory) for item in byteList: sum += item if len(byteList) != 0: if UA not in lenAgentDic.keys(): lenAgentDic[UA] = [sum / len(byteList)] else: agentList = lenAgentDic[UA] agentList.append(sum / len(byteList)) lenAgentDic[UA] = agentList def finalLenFunc(dirName): for filename in os.listdir(dirName): file = dirName + filename avgModFunc(file) def printLenDiff(): finalLenFunc(dirName) finalLenFunc(dirName2) for keys, vals in lenAgentDic.items(): if len(vals) > 1 and vals[1] > 0: score = vals[1] / vals[0] print('{:<15}: {:.2f}'.format(keys, score)) else: score = 'N/A' print('{:<15}: {}'.format(keys, score)) lenAgentDic[keys] = score return lenAgentDic def directoryModCont(directory): contentSet = set() newSet = set() listHolder = [] numofReq = 0 UA = directory.split('/')[1] for filename in os.listdir(directory): file = directory + '/' + filename listHolder = factorStatFileCreator.contentCommand(file) newSet = listHolder[0] numofReq += len(listHolder[1]) contentSet = contentSet | newSet newSet = set() if UA not in contAgentDic.keys(): contAgentDic[UA] = [numofReq] else: agentList = contAgentDic[UA] agentList.append(numofReq) contAgentDic[UA] = agentList return contentSet, numofReq def finalContFunc(dirName): for filename in os.listdir(dirName): file = dirName + filename directoryModCont(file) def printContDiff(): finalContFunc(dirName) finalContFunc(dirName2) for keys, vals in contAgentDic.items(): if len(vals) > 1 and vals[1] > 0: score = vals[0] / vals[1] print('{:<15}: {:.2f}'.format(keys, score)) else: score = 'N/A' print('{:<15}: {}'.format(keys, score)) contAgentDic[keys] = score return contAgentDic <|reserved_special_token_1|> import os import factorStatFileCreator dirName = 'NoPerms/' dirName2 = 'AllPerms/' freqAgentDic = dict() lenAgentDic = dict() contAgentDic = dict() def freqModAvgFunc(dirName): fullList = factorStatFileCreator.directoryFreq(dirName) UA = dirName.split("/")[1] avgList = [] sum = 0 i = 0 while i <= len(fullList) - 2: diff = factorStatFileCreator.diffFunc(fullList[i], fullList[i+1]) if diff == None: i+=1 else: avgList.append(int(diff)) i+=1 for item in avgList: sum += item if len(avgList) != 0: if UA not in freqAgentDic.keys(): freqAgentDic[UA] = [sum/len(avgList)] else: agentList = freqAgentDic[UA] agentList.append(sum/len(avgList)) freqAgentDic[UA] = agentList def finalFreqFunc(dirName): for filename in os.listdir(dirName): file = dirName + filename freqModAvgFunc(file) def printFreqDiff(): finalFreqFunc(dirName) finalFreqFunc(dirName2) #print (freqAgentDic) for keys, vals in freqAgentDic.items(): if len(vals) > 1 and vals[1] > 0: score = vals[0] / vals[1] print ("{:<15}: {:.2f}".format(keys,score)) else: score = "N/A" print ("{:<15}: {}".format(keys,score)) freqAgentDic[keys] = score return (freqAgentDic) def avgModFunc(directory): sum = 0 UA = directory.split("/")[1] byteList = factorStatFileCreator.directoryLen(directory) for item in byteList: sum += item if len(byteList) != 0: if UA not in lenAgentDic.keys(): lenAgentDic[UA] = [sum/len(byteList)] else: agentList = lenAgentDic[UA] agentList.append(sum/len(byteList)) lenAgentDic[UA] = agentList def finalLenFunc(dirName): for filename in os.listdir(dirName): file = dirName + filename avgModFunc(file) def printLenDiff(): finalLenFunc(dirName) finalLenFunc(dirName2) for keys, vals in lenAgentDic.items(): if len(vals) > 1 and vals[1] > 0: score = vals[1] / vals[0] print ("{:<15}: {:.2f}".format(keys,score)) else: score = "N/A" print ("{:<15}: {}".format(keys,score)) lenAgentDic[keys] = score return lenAgentDic def directoryModCont(directory): contentSet = set() newSet = set() listHolder = [] numofReq = 0 UA = directory.split("/")[1] for filename in os.listdir(directory): file = directory + '/' + filename listHolder = factorStatFileCreator.contentCommand(file) #print(newSet) newSet = listHolder[0] numofReq += len(listHolder[1]) contentSet = contentSet|newSet newSet = set() if UA not in contAgentDic.keys(): contAgentDic[UA] = [numofReq] else: agentList = contAgentDic[UA] agentList.append(numofReq) contAgentDic[UA] = agentList return contentSet, numofReq def finalContFunc(dirName): for filename in os.listdir(dirName): file = dirName + filename directoryModCont(file) def printContDiff(): finalContFunc(dirName) finalContFunc(dirName2) for keys, vals in contAgentDic.items(): if len(vals) > 1 and vals[1] > 0: score = vals[0] / vals[1] print ("{:<15}: {:.2f}".format(keys,score)) else: score = "N/A" print ("{:<15}: {}".format(keys,score)) contAgentDic[keys] = score return contAgentDic
flexible
{ "blob_id": "8ac84aa29e9e4f3b85f1b3c27819feb5f41e8d8e", "index": 598, "step-1": "<mask token>\n\n\ndef freqModAvgFunc(dirName):\n fullList = factorStatFileCreator.directoryFreq(dirName)\n UA = dirName.split('/')[1]\n avgList = []\n sum = 0\n i = 0\n while i <= len(fullList) - 2:\n diff = factorStatFileCreator.diffFunc(fullList[i], fullList[i + 1])\n if diff == None:\n i += 1\n else:\n avgList.append(int(diff))\n i += 1\n for item in avgList:\n sum += item\n if len(avgList) != 0:\n if UA not in freqAgentDic.keys():\n freqAgentDic[UA] = [sum / len(avgList)]\n else:\n agentList = freqAgentDic[UA]\n agentList.append(sum / len(avgList))\n freqAgentDic[UA] = agentList\n\n\n<mask token>\n\n\ndef printFreqDiff():\n finalFreqFunc(dirName)\n finalFreqFunc(dirName2)\n for keys, vals in freqAgentDic.items():\n if len(vals) > 1 and vals[1] > 0:\n score = vals[0] / vals[1]\n print('{:<15}: {:.2f}'.format(keys, score))\n else:\n score = 'N/A'\n print('{:<15}: {}'.format(keys, score))\n freqAgentDic[keys] = score\n return freqAgentDic\n\n\n<mask token>\n\n\ndef finalLenFunc(dirName):\n for filename in os.listdir(dirName):\n file = dirName + filename\n avgModFunc(file)\n\n\ndef printLenDiff():\n finalLenFunc(dirName)\n finalLenFunc(dirName2)\n for keys, vals in lenAgentDic.items():\n if len(vals) > 1 and vals[1] > 0:\n score = vals[1] / vals[0]\n print('{:<15}: {:.2f}'.format(keys, score))\n else:\n score = 'N/A'\n print('{:<15}: {}'.format(keys, score))\n lenAgentDic[keys] = score\n return lenAgentDic\n\n\ndef directoryModCont(directory):\n contentSet = set()\n newSet = set()\n listHolder = []\n numofReq = 0\n UA = directory.split('/')[1]\n for filename in os.listdir(directory):\n file = directory + '/' + filename\n listHolder = factorStatFileCreator.contentCommand(file)\n newSet = listHolder[0]\n numofReq += len(listHolder[1])\n contentSet = contentSet | newSet\n newSet = set()\n if UA not in contAgentDic.keys():\n contAgentDic[UA] = [numofReq]\n else:\n agentList = contAgentDic[UA]\n agentList.append(numofReq)\n contAgentDic[UA] = agentList\n return contentSet, numofReq\n\n\ndef finalContFunc(dirName):\n for filename in os.listdir(dirName):\n file = dirName + filename\n directoryModCont(file)\n\n\ndef printContDiff():\n finalContFunc(dirName)\n finalContFunc(dirName2)\n for keys, vals in contAgentDic.items():\n if len(vals) > 1 and vals[1] > 0:\n score = vals[0] / vals[1]\n print('{:<15}: {:.2f}'.format(keys, score))\n else:\n score = 'N/A'\n print('{:<15}: {}'.format(keys, score))\n contAgentDic[keys] = score\n return contAgentDic\n", "step-2": "<mask token>\n\n\ndef freqModAvgFunc(dirName):\n fullList = factorStatFileCreator.directoryFreq(dirName)\n UA = dirName.split('/')[1]\n avgList = []\n sum = 0\n i = 0\n while i <= len(fullList) - 2:\n diff = factorStatFileCreator.diffFunc(fullList[i], fullList[i + 1])\n if diff == None:\n i += 1\n else:\n avgList.append(int(diff))\n i += 1\n for item in avgList:\n sum += item\n if len(avgList) != 0:\n if UA not in freqAgentDic.keys():\n freqAgentDic[UA] = [sum / len(avgList)]\n else:\n agentList = freqAgentDic[UA]\n agentList.append(sum / len(avgList))\n freqAgentDic[UA] = agentList\n\n\ndef finalFreqFunc(dirName):\n for filename in os.listdir(dirName):\n file = dirName + filename\n freqModAvgFunc(file)\n\n\ndef printFreqDiff():\n finalFreqFunc(dirName)\n finalFreqFunc(dirName2)\n for keys, vals in freqAgentDic.items():\n if len(vals) > 1 and vals[1] > 0:\n score = vals[0] / vals[1]\n print('{:<15}: {:.2f}'.format(keys, score))\n else:\n score = 'N/A'\n print('{:<15}: {}'.format(keys, score))\n freqAgentDic[keys] = score\n return freqAgentDic\n\n\n<mask token>\n\n\ndef finalLenFunc(dirName):\n for filename in os.listdir(dirName):\n file = dirName + filename\n avgModFunc(file)\n\n\ndef printLenDiff():\n finalLenFunc(dirName)\n finalLenFunc(dirName2)\n for keys, vals in lenAgentDic.items():\n if len(vals) > 1 and vals[1] > 0:\n score = vals[1] / vals[0]\n print('{:<15}: {:.2f}'.format(keys, score))\n else:\n score = 'N/A'\n print('{:<15}: {}'.format(keys, score))\n lenAgentDic[keys] = score\n return lenAgentDic\n\n\ndef directoryModCont(directory):\n contentSet = set()\n newSet = set()\n listHolder = []\n numofReq = 0\n UA = directory.split('/')[1]\n for filename in os.listdir(directory):\n file = directory + '/' + filename\n listHolder = factorStatFileCreator.contentCommand(file)\n newSet = listHolder[0]\n numofReq += len(listHolder[1])\n contentSet = contentSet | newSet\n newSet = set()\n if UA not in contAgentDic.keys():\n contAgentDic[UA] = [numofReq]\n else:\n agentList = contAgentDic[UA]\n agentList.append(numofReq)\n contAgentDic[UA] = agentList\n return contentSet, numofReq\n\n\ndef finalContFunc(dirName):\n for filename in os.listdir(dirName):\n file = dirName + filename\n directoryModCont(file)\n\n\ndef printContDiff():\n finalContFunc(dirName)\n finalContFunc(dirName2)\n for keys, vals in contAgentDic.items():\n if len(vals) > 1 and vals[1] > 0:\n score = vals[0] / vals[1]\n print('{:<15}: {:.2f}'.format(keys, score))\n else:\n score = 'N/A'\n print('{:<15}: {}'.format(keys, score))\n contAgentDic[keys] = score\n return contAgentDic\n", "step-3": "<mask token>\n\n\ndef freqModAvgFunc(dirName):\n fullList = factorStatFileCreator.directoryFreq(dirName)\n UA = dirName.split('/')[1]\n avgList = []\n sum = 0\n i = 0\n while i <= len(fullList) - 2:\n diff = factorStatFileCreator.diffFunc(fullList[i], fullList[i + 1])\n if diff == None:\n i += 1\n else:\n avgList.append(int(diff))\n i += 1\n for item in avgList:\n sum += item\n if len(avgList) != 0:\n if UA not in freqAgentDic.keys():\n freqAgentDic[UA] = [sum / len(avgList)]\n else:\n agentList = freqAgentDic[UA]\n agentList.append(sum / len(avgList))\n freqAgentDic[UA] = agentList\n\n\ndef finalFreqFunc(dirName):\n for filename in os.listdir(dirName):\n file = dirName + filename\n freqModAvgFunc(file)\n\n\ndef printFreqDiff():\n finalFreqFunc(dirName)\n finalFreqFunc(dirName2)\n for keys, vals in freqAgentDic.items():\n if len(vals) > 1 and vals[1] > 0:\n score = vals[0] / vals[1]\n print('{:<15}: {:.2f}'.format(keys, score))\n else:\n score = 'N/A'\n print('{:<15}: {}'.format(keys, score))\n freqAgentDic[keys] = score\n return freqAgentDic\n\n\ndef avgModFunc(directory):\n sum = 0\n UA = directory.split('/')[1]\n byteList = factorStatFileCreator.directoryLen(directory)\n for item in byteList:\n sum += item\n if len(byteList) != 0:\n if UA not in lenAgentDic.keys():\n lenAgentDic[UA] = [sum / len(byteList)]\n else:\n agentList = lenAgentDic[UA]\n agentList.append(sum / len(byteList))\n lenAgentDic[UA] = agentList\n\n\ndef finalLenFunc(dirName):\n for filename in os.listdir(dirName):\n file = dirName + filename\n avgModFunc(file)\n\n\ndef printLenDiff():\n finalLenFunc(dirName)\n finalLenFunc(dirName2)\n for keys, vals in lenAgentDic.items():\n if len(vals) > 1 and vals[1] > 0:\n score = vals[1] / vals[0]\n print('{:<15}: {:.2f}'.format(keys, score))\n else:\n score = 'N/A'\n print('{:<15}: {}'.format(keys, score))\n lenAgentDic[keys] = score\n return lenAgentDic\n\n\ndef directoryModCont(directory):\n contentSet = set()\n newSet = set()\n listHolder = []\n numofReq = 0\n UA = directory.split('/')[1]\n for filename in os.listdir(directory):\n file = directory + '/' + filename\n listHolder = factorStatFileCreator.contentCommand(file)\n newSet = listHolder[0]\n numofReq += len(listHolder[1])\n contentSet = contentSet | newSet\n newSet = set()\n if UA not in contAgentDic.keys():\n contAgentDic[UA] = [numofReq]\n else:\n agentList = contAgentDic[UA]\n agentList.append(numofReq)\n contAgentDic[UA] = agentList\n return contentSet, numofReq\n\n\ndef finalContFunc(dirName):\n for filename in os.listdir(dirName):\n file = dirName + filename\n directoryModCont(file)\n\n\ndef printContDiff():\n finalContFunc(dirName)\n finalContFunc(dirName2)\n for keys, vals in contAgentDic.items():\n if len(vals) > 1 and vals[1] > 0:\n score = vals[0] / vals[1]\n print('{:<15}: {:.2f}'.format(keys, score))\n else:\n score = 'N/A'\n print('{:<15}: {}'.format(keys, score))\n contAgentDic[keys] = score\n return contAgentDic\n", "step-4": "<mask token>\ndirName = 'NoPerms/'\ndirName2 = 'AllPerms/'\nfreqAgentDic = dict()\nlenAgentDic = dict()\ncontAgentDic = dict()\n\n\ndef freqModAvgFunc(dirName):\n fullList = factorStatFileCreator.directoryFreq(dirName)\n UA = dirName.split('/')[1]\n avgList = []\n sum = 0\n i = 0\n while i <= len(fullList) - 2:\n diff = factorStatFileCreator.diffFunc(fullList[i], fullList[i + 1])\n if diff == None:\n i += 1\n else:\n avgList.append(int(diff))\n i += 1\n for item in avgList:\n sum += item\n if len(avgList) != 0:\n if UA not in freqAgentDic.keys():\n freqAgentDic[UA] = [sum / len(avgList)]\n else:\n agentList = freqAgentDic[UA]\n agentList.append(sum / len(avgList))\n freqAgentDic[UA] = agentList\n\n\ndef finalFreqFunc(dirName):\n for filename in os.listdir(dirName):\n file = dirName + filename\n freqModAvgFunc(file)\n\n\ndef printFreqDiff():\n finalFreqFunc(dirName)\n finalFreqFunc(dirName2)\n for keys, vals in freqAgentDic.items():\n if len(vals) > 1 and vals[1] > 0:\n score = vals[0] / vals[1]\n print('{:<15}: {:.2f}'.format(keys, score))\n else:\n score = 'N/A'\n print('{:<15}: {}'.format(keys, score))\n freqAgentDic[keys] = score\n return freqAgentDic\n\n\ndef avgModFunc(directory):\n sum = 0\n UA = directory.split('/')[1]\n byteList = factorStatFileCreator.directoryLen(directory)\n for item in byteList:\n sum += item\n if len(byteList) != 0:\n if UA not in lenAgentDic.keys():\n lenAgentDic[UA] = [sum / len(byteList)]\n else:\n agentList = lenAgentDic[UA]\n agentList.append(sum / len(byteList))\n lenAgentDic[UA] = agentList\n\n\ndef finalLenFunc(dirName):\n for filename in os.listdir(dirName):\n file = dirName + filename\n avgModFunc(file)\n\n\ndef printLenDiff():\n finalLenFunc(dirName)\n finalLenFunc(dirName2)\n for keys, vals in lenAgentDic.items():\n if len(vals) > 1 and vals[1] > 0:\n score = vals[1] / vals[0]\n print('{:<15}: {:.2f}'.format(keys, score))\n else:\n score = 'N/A'\n print('{:<15}: {}'.format(keys, score))\n lenAgentDic[keys] = score\n return lenAgentDic\n\n\ndef directoryModCont(directory):\n contentSet = set()\n newSet = set()\n listHolder = []\n numofReq = 0\n UA = directory.split('/')[1]\n for filename in os.listdir(directory):\n file = directory + '/' + filename\n listHolder = factorStatFileCreator.contentCommand(file)\n newSet = listHolder[0]\n numofReq += len(listHolder[1])\n contentSet = contentSet | newSet\n newSet = set()\n if UA not in contAgentDic.keys():\n contAgentDic[UA] = [numofReq]\n else:\n agentList = contAgentDic[UA]\n agentList.append(numofReq)\n contAgentDic[UA] = agentList\n return contentSet, numofReq\n\n\ndef finalContFunc(dirName):\n for filename in os.listdir(dirName):\n file = dirName + filename\n directoryModCont(file)\n\n\ndef printContDiff():\n finalContFunc(dirName)\n finalContFunc(dirName2)\n for keys, vals in contAgentDic.items():\n if len(vals) > 1 and vals[1] > 0:\n score = vals[0] / vals[1]\n print('{:<15}: {:.2f}'.format(keys, score))\n else:\n score = 'N/A'\n print('{:<15}: {}'.format(keys, score))\n contAgentDic[keys] = score\n return contAgentDic\n", "step-5": "import os\nimport factorStatFileCreator\n\ndirName = 'NoPerms/'\ndirName2 = 'AllPerms/'\n\nfreqAgentDic = dict()\nlenAgentDic = dict()\ncontAgentDic = dict()\n\ndef freqModAvgFunc(dirName):\n fullList = factorStatFileCreator.directoryFreq(dirName)\n UA = dirName.split(\"/\")[1]\n avgList = []\n sum = 0\n i = 0\n while i <= len(fullList) - 2:\n diff = factorStatFileCreator.diffFunc(fullList[i], fullList[i+1])\n if diff == None:\n i+=1\n else:\n avgList.append(int(diff))\n i+=1\n for item in avgList:\n sum += item\n if len(avgList) != 0:\n if UA not in freqAgentDic.keys():\n freqAgentDic[UA] = [sum/len(avgList)]\n else:\n agentList = freqAgentDic[UA]\n agentList.append(sum/len(avgList))\n freqAgentDic[UA] = agentList\n\ndef finalFreqFunc(dirName):\n for filename in os.listdir(dirName):\n file = dirName + filename\n freqModAvgFunc(file)\n\ndef printFreqDiff():\n finalFreqFunc(dirName)\n finalFreqFunc(dirName2)\n #print (freqAgentDic)\n for keys, vals in freqAgentDic.items():\n if len(vals) > 1 and vals[1] > 0:\n score = vals[0] / vals[1]\n print (\"{:<15}: {:.2f}\".format(keys,score))\n else:\n score = \"N/A\"\n print (\"{:<15}: {}\".format(keys,score))\n freqAgentDic[keys] = score\n return (freqAgentDic)\n\ndef avgModFunc(directory):\n sum = 0\n UA = directory.split(\"/\")[1]\n byteList = factorStatFileCreator.directoryLen(directory)\n for item in byteList:\n sum += item\n if len(byteList) != 0:\n if UA not in lenAgentDic.keys():\n lenAgentDic[UA] = [sum/len(byteList)]\n else:\n agentList = lenAgentDic[UA]\n agentList.append(sum/len(byteList))\n lenAgentDic[UA] = agentList\n\ndef finalLenFunc(dirName):\n for filename in os.listdir(dirName):\n file = dirName + filename\n avgModFunc(file)\n\ndef printLenDiff():\n finalLenFunc(dirName)\n finalLenFunc(dirName2)\n for keys, vals in lenAgentDic.items():\n if len(vals) > 1 and vals[1] > 0:\n score = vals[1] / vals[0]\n print (\"{:<15}: {:.2f}\".format(keys,score))\n else:\n score = \"N/A\"\n print (\"{:<15}: {}\".format(keys,score))\n lenAgentDic[keys] = score\n return lenAgentDic\n\ndef directoryModCont(directory):\n contentSet = set()\n newSet = set()\n listHolder = []\n numofReq = 0\n UA = directory.split(\"/\")[1]\n for filename in os.listdir(directory):\n file = directory + '/' + filename\n listHolder = factorStatFileCreator.contentCommand(file)\n #print(newSet)\n newSet = listHolder[0]\n numofReq += len(listHolder[1])\n contentSet = contentSet|newSet\n newSet = set()\n if UA not in contAgentDic.keys():\n contAgentDic[UA] = [numofReq]\n else:\n agentList = contAgentDic[UA]\n agentList.append(numofReq)\n contAgentDic[UA] = agentList\n return contentSet, numofReq\n\ndef finalContFunc(dirName):\n for filename in os.listdir(dirName):\n file = dirName + filename\n directoryModCont(file)\n\ndef printContDiff():\n finalContFunc(dirName)\n finalContFunc(dirName2)\n for keys, vals in contAgentDic.items():\n if len(vals) > 1 and vals[1] > 0:\n score = vals[0] / vals[1]\n print (\"{:<15}: {:.2f}\".format(keys,score))\n else:\n score = \"N/A\"\n print (\"{:<15}: {}\".format(keys,score))\n contAgentDic[keys] = score\n return contAgentDic\n", "step-ids": [ 7, 8, 9, 10, 12 ] }
[ 7, 8, 9, 10, 12 ]
import random import numpy as np import pandas as pd def linear_combination_plus_error(X, num_dependent_cols=5, parameter_mean=0, parameter_std=1, error_mean=0, error_std=1): """ Generate a column that is a random linear combination of X1, X2 and X3 plus some random error """ length = X.shape[0] param = np.random.normal(loc=parameter_mean, scale=parameter_std, size=(num_dependent_cols,)) error = np.random.normal(loc=error_mean, scale=error_std, size=(length,)) result = np.zeros(length,) for i in range(num_dependent_cols): result += param[i] * X[:, i] return result + error np.random.seed(472) num_data = 10100 num_independent_cols = 3 X = np.zeros((num_data, 1001)) # Generate 3 principal components for i in range(num_independent_cols): X[:, i] = np.random.normal(np.random.uniform(-5, 5), np.random.uniform(1, 5), size=(num_data,)) # Generate other columns for i in range(3, 1000): X[:, i] = linear_combination_plus_error(X, num_dependent_cols=num_independent_cols, parameter_std=2, error_std=1) # Randomly suffle the 1000 feature columns col_nums = list(range(1000)) np.random.shuffle(col_nums) X[:, list(range(1000))] = X[:, col_nums] # Randomly generate Y X[:, 1000] = linear_combination_plus_error(X, num_dependent_cols=num_independent_cols, parameter_mean=5, parameter_std=2) X[:, 1000] += abs(min(X[:, 1000])) + 5 # Take only three digits after decimal point X = np.floor(X * 1000) / 1000 # Split the data into 2 files X1 = X[:10000, :] X2 = X[10000:, :] X1_df = pd.DataFrame(X1) X1_df.to_csv("./sensors1.csv", header=None, index=None) X2_df = pd.DataFrame(X2) X2_df.to_csv("./sensors2.csv", header=None, index=None)
normal
{ "blob_id": "48f2cc5b6d53c7317ad882947cabbc367cda0fb7", "index": 905, "step-1": "<mask token>\n\n\ndef linear_combination_plus_error(X, num_dependent_cols=5, parameter_mean=0,\n parameter_std=1, error_mean=0, error_std=1):\n \"\"\"\n Generate a column that is a random linear combination of\n X1, X2 and X3 plus some random error\n \"\"\"\n length = X.shape[0]\n param = np.random.normal(loc=parameter_mean, scale=parameter_std, size=\n (num_dependent_cols,))\n error = np.random.normal(loc=error_mean, scale=error_std, size=(length,))\n result = np.zeros(length)\n for i in range(num_dependent_cols):\n result += param[i] * X[:, i]\n return result + error\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef linear_combination_plus_error(X, num_dependent_cols=5, parameter_mean=0,\n parameter_std=1, error_mean=0, error_std=1):\n \"\"\"\n Generate a column that is a random linear combination of\n X1, X2 and X3 plus some random error\n \"\"\"\n length = X.shape[0]\n param = np.random.normal(loc=parameter_mean, scale=parameter_std, size=\n (num_dependent_cols,))\n error = np.random.normal(loc=error_mean, scale=error_std, size=(length,))\n result = np.zeros(length)\n for i in range(num_dependent_cols):\n result += param[i] * X[:, i]\n return result + error\n\n\nnp.random.seed(472)\n<mask token>\nfor i in range(num_independent_cols):\n X[:, i] = np.random.normal(np.random.uniform(-5, 5), np.random.uniform(\n 1, 5), size=(num_data,))\nfor i in range(3, 1000):\n X[:, i] = linear_combination_plus_error(X, num_dependent_cols=\n num_independent_cols, parameter_std=2, error_std=1)\n<mask token>\nnp.random.shuffle(col_nums)\n<mask token>\nX[:, 1000] += abs(min(X[:, 1000])) + 5\n<mask token>\nX1_df.to_csv('./sensors1.csv', header=None, index=None)\n<mask token>\nX2_df.to_csv('./sensors2.csv', header=None, index=None)\n", "step-3": "<mask token>\n\n\ndef linear_combination_plus_error(X, num_dependent_cols=5, parameter_mean=0,\n parameter_std=1, error_mean=0, error_std=1):\n \"\"\"\n Generate a column that is a random linear combination of\n X1, X2 and X3 plus some random error\n \"\"\"\n length = X.shape[0]\n param = np.random.normal(loc=parameter_mean, scale=parameter_std, size=\n (num_dependent_cols,))\n error = np.random.normal(loc=error_mean, scale=error_std, size=(length,))\n result = np.zeros(length)\n for i in range(num_dependent_cols):\n result += param[i] * X[:, i]\n return result + error\n\n\nnp.random.seed(472)\nnum_data = 10100\nnum_independent_cols = 3\nX = np.zeros((num_data, 1001))\nfor i in range(num_independent_cols):\n X[:, i] = np.random.normal(np.random.uniform(-5, 5), np.random.uniform(\n 1, 5), size=(num_data,))\nfor i in range(3, 1000):\n X[:, i] = linear_combination_plus_error(X, num_dependent_cols=\n num_independent_cols, parameter_std=2, error_std=1)\ncol_nums = list(range(1000))\nnp.random.shuffle(col_nums)\nX[:, list(range(1000))] = X[:, col_nums]\nX[:, 1000] = linear_combination_plus_error(X, num_dependent_cols=\n num_independent_cols, parameter_mean=5, parameter_std=2)\nX[:, 1000] += abs(min(X[:, 1000])) + 5\nX = np.floor(X * 1000) / 1000\nX1 = X[:10000, :]\nX2 = X[10000:, :]\nX1_df = pd.DataFrame(X1)\nX1_df.to_csv('./sensors1.csv', header=None, index=None)\nX2_df = pd.DataFrame(X2)\nX2_df.to_csv('./sensors2.csv', header=None, index=None)\n", "step-4": "import random\nimport numpy as np\nimport pandas as pd\n\n\ndef linear_combination_plus_error(X, num_dependent_cols=5, parameter_mean=0,\n parameter_std=1, error_mean=0, error_std=1):\n \"\"\"\n Generate a column that is a random linear combination of\n X1, X2 and X3 plus some random error\n \"\"\"\n length = X.shape[0]\n param = np.random.normal(loc=parameter_mean, scale=parameter_std, size=\n (num_dependent_cols,))\n error = np.random.normal(loc=error_mean, scale=error_std, size=(length,))\n result = np.zeros(length)\n for i in range(num_dependent_cols):\n result += param[i] * X[:, i]\n return result + error\n\n\nnp.random.seed(472)\nnum_data = 10100\nnum_independent_cols = 3\nX = np.zeros((num_data, 1001))\nfor i in range(num_independent_cols):\n X[:, i] = np.random.normal(np.random.uniform(-5, 5), np.random.uniform(\n 1, 5), size=(num_data,))\nfor i in range(3, 1000):\n X[:, i] = linear_combination_plus_error(X, num_dependent_cols=\n num_independent_cols, parameter_std=2, error_std=1)\ncol_nums = list(range(1000))\nnp.random.shuffle(col_nums)\nX[:, list(range(1000))] = X[:, col_nums]\nX[:, 1000] = linear_combination_plus_error(X, num_dependent_cols=\n num_independent_cols, parameter_mean=5, parameter_std=2)\nX[:, 1000] += abs(min(X[:, 1000])) + 5\nX = np.floor(X * 1000) / 1000\nX1 = X[:10000, :]\nX2 = X[10000:, :]\nX1_df = pd.DataFrame(X1)\nX1_df.to_csv('./sensors1.csv', header=None, index=None)\nX2_df = pd.DataFrame(X2)\nX2_df.to_csv('./sensors2.csv', header=None, index=None)\n", "step-5": "import random\nimport numpy as np\nimport pandas as pd\n\ndef linear_combination_plus_error(X, num_dependent_cols=5, parameter_mean=0, parameter_std=1, error_mean=0, error_std=1):\n \"\"\"\n Generate a column that is a random linear combination of\n X1, X2 and X3 plus some random error\n \"\"\"\n length = X.shape[0]\n param = np.random.normal(loc=parameter_mean,\n scale=parameter_std,\n size=(num_dependent_cols,))\n error = np.random.normal(loc=error_mean,\n scale=error_std,\n size=(length,))\n result = np.zeros(length,)\n for i in range(num_dependent_cols):\n result += param[i] * X[:, i]\n return result + error\n \n\nnp.random.seed(472)\nnum_data = 10100\nnum_independent_cols = 3\n\nX = np.zeros((num_data, 1001))\n\n# Generate 3 principal components\nfor i in range(num_independent_cols):\n X[:, i] = np.random.normal(np.random.uniform(-5, 5), \n np.random.uniform(1, 5), size=(num_data,))\n\n\n# Generate other columns\nfor i in range(3, 1000):\n X[:, i] = linear_combination_plus_error(X, num_dependent_cols=num_independent_cols, parameter_std=2, error_std=1)\n\n# Randomly suffle the 1000 feature columns\ncol_nums = list(range(1000))\nnp.random.shuffle(col_nums)\nX[:, list(range(1000))] = X[:, col_nums]\n\n# Randomly generate Y\nX[:, 1000] = linear_combination_plus_error(X, num_dependent_cols=num_independent_cols, parameter_mean=5, parameter_std=2)\nX[:, 1000] += abs(min(X[:, 1000])) + 5\n\n\n# Take only three digits after decimal point\nX = np.floor(X * 1000) / 1000\n\n\n# Split the data into 2 files\nX1 = X[:10000, :]\nX2 = X[10000:, :]\nX1_df = pd.DataFrame(X1)\nX1_df.to_csv(\"./sensors1.csv\", header=None, index=None)\n\nX2_df = pd.DataFrame(X2)\nX2_df.to_csv(\"./sensors2.csv\", header=None, index=None)\n\n\n\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> print(np.dot(a, b)) <|reserved_special_token_1|> <|reserved_special_token_0|> n = int(input()) a = [list(map(int, input().split())) for _ in range(n)] b = [list(map(int, input().split())) for _ in range(n)] a = np.array(a) b = np.array(b) print(np.dot(a, b)) <|reserved_special_token_1|> import numpy as np n = int(input()) a = [list(map(int, input().split())) for _ in range(n)] b = [list(map(int, input().split())) for _ in range(n)] a = np.array(a) b = np.array(b) print(np.dot(a, b))
flexible
{ "blob_id": "17b8fec5583f2544bd02a2409528082fa1dc2a1e", "index": 4107, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(np.dot(a, b))\n", "step-3": "<mask token>\nn = int(input())\na = [list(map(int, input().split())) for _ in range(n)]\nb = [list(map(int, input().split())) for _ in range(n)]\na = np.array(a)\nb = np.array(b)\nprint(np.dot(a, b))\n", "step-4": "import numpy as np\nn = int(input())\na = [list(map(int, input().split())) for _ in range(n)]\nb = [list(map(int, input().split())) for _ in range(n)]\na = np.array(a)\nb = np.array(b)\nprint(np.dot(a, b))\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> print( 'Note: total_earnings values were scaled by multiplying by {:.10f} and adding {:.6f}' .format(scaler.scale_[8], scaler.min_[8])) <|reserved_special_token_0|> scaled_training_df.to_csv('sales_data_training_scaled.csv', index=False) scaled_training_df.to_csv('sales_data_test_scaled.csv', index=False) <|reserved_special_token_1|> <|reserved_special_token_0|> training_data_df = pd.read_csv('sales_data_training.csv') test_data_df = pd.read_csv('sales_data_test.csv') scaler = MinMaxScaler(feature_range=(0, 1)) scaled_training = scaler.fit_transform(training_data_df) scaled_testing = scaler.transform(test_data_df) print( 'Note: total_earnings values were scaled by multiplying by {:.10f} and adding {:.6f}' .format(scaler.scale_[8], scaler.min_[8])) scaled_training_df = pd.DataFrame(scaled_training, columns=training_data_df .columns.values) scaled_testing_df = pd.DataFrame(scaled_testing, columns=test_data_df. columns.values) scaled_training_df.to_csv('sales_data_training_scaled.csv', index=False) scaled_training_df.to_csv('sales_data_test_scaled.csv', index=False) <|reserved_special_token_1|> import pandas as pd from sklearn.preprocessing import MinMaxScaler training_data_df = pd.read_csv('sales_data_training.csv') test_data_df = pd.read_csv('sales_data_test.csv') scaler = MinMaxScaler(feature_range=(0, 1)) scaled_training = scaler.fit_transform(training_data_df) scaled_testing = scaler.transform(test_data_df) print( 'Note: total_earnings values were scaled by multiplying by {:.10f} and adding {:.6f}' .format(scaler.scale_[8], scaler.min_[8])) scaled_training_df = pd.DataFrame(scaled_training, columns=training_data_df .columns.values) scaled_testing_df = pd.DataFrame(scaled_testing, columns=test_data_df. columns.values) scaled_training_df.to_csv('sales_data_training_scaled.csv', index=False) scaled_training_df.to_csv('sales_data_test_scaled.csv', index=False) <|reserved_special_token_1|> import pandas as pd from sklearn.preprocessing import MinMaxScaler #loading data from CSV training_data_df = pd.read_csv("sales_data_training.csv") test_data_df = pd.read_csv("sales_data_test.csv") #scaler scaler = MinMaxScaler(feature_range=(0,1)) #scale both inputs and outputs scaled_training = scaler.fit_transform(training_data_df) scaled_testing = scaler.transform(test_data_df) #to bring it back to the original values print("Note: total_earnings values were scaled by multiplying by {:.10f} and adding {:.6f}".format(scaler.scale_[8], scaler.min_[8])) #create a new scaled dataframe object scaled_training_df = pd.DataFrame(scaled_training, columns=training_data_df.columns.values) scaled_testing_df = pd.DataFrame(scaled_testing, columns=test_data_df.columns.values) #save the scaled dataframe to new csv files scaled_training_df.to_csv("sales_data_training_scaled.csv", index=False) scaled_training_df.to_csv("sales_data_test_scaled.csv", index=False)
flexible
{ "blob_id": "050e2207ac7331444d39305869c4b25bcbc53907", "index": 244, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(\n 'Note: total_earnings values were scaled by multiplying by {:.10f} and adding {:.6f}'\n .format(scaler.scale_[8], scaler.min_[8]))\n<mask token>\nscaled_training_df.to_csv('sales_data_training_scaled.csv', index=False)\nscaled_training_df.to_csv('sales_data_test_scaled.csv', index=False)\n", "step-3": "<mask token>\ntraining_data_df = pd.read_csv('sales_data_training.csv')\ntest_data_df = pd.read_csv('sales_data_test.csv')\nscaler = MinMaxScaler(feature_range=(0, 1))\nscaled_training = scaler.fit_transform(training_data_df)\nscaled_testing = scaler.transform(test_data_df)\nprint(\n 'Note: total_earnings values were scaled by multiplying by {:.10f} and adding {:.6f}'\n .format(scaler.scale_[8], scaler.min_[8]))\nscaled_training_df = pd.DataFrame(scaled_training, columns=training_data_df\n .columns.values)\nscaled_testing_df = pd.DataFrame(scaled_testing, columns=test_data_df.\n columns.values)\nscaled_training_df.to_csv('sales_data_training_scaled.csv', index=False)\nscaled_training_df.to_csv('sales_data_test_scaled.csv', index=False)\n", "step-4": "import pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\ntraining_data_df = pd.read_csv('sales_data_training.csv')\ntest_data_df = pd.read_csv('sales_data_test.csv')\nscaler = MinMaxScaler(feature_range=(0, 1))\nscaled_training = scaler.fit_transform(training_data_df)\nscaled_testing = scaler.transform(test_data_df)\nprint(\n 'Note: total_earnings values were scaled by multiplying by {:.10f} and adding {:.6f}'\n .format(scaler.scale_[8], scaler.min_[8]))\nscaled_training_df = pd.DataFrame(scaled_training, columns=training_data_df\n .columns.values)\nscaled_testing_df = pd.DataFrame(scaled_testing, columns=test_data_df.\n columns.values)\nscaled_training_df.to_csv('sales_data_training_scaled.csv', index=False)\nscaled_training_df.to_csv('sales_data_test_scaled.csv', index=False)\n", "step-5": "import pandas as pd\nfrom sklearn.preprocessing import MinMaxScaler\n\n#loading data from CSV\ntraining_data_df = pd.read_csv(\"sales_data_training.csv\")\ntest_data_df = pd.read_csv(\"sales_data_test.csv\")\n\n#scaler\nscaler = MinMaxScaler(feature_range=(0,1))\n\n#scale both inputs and outputs\nscaled_training = scaler.fit_transform(training_data_df)\nscaled_testing = scaler.transform(test_data_df)\n\n#to bring it back to the original values\nprint(\"Note: total_earnings values were scaled by multiplying by {:.10f} and adding {:.6f}\".format(scaler.scale_[8], scaler.min_[8]))\n\n#create a new scaled dataframe object\nscaled_training_df = pd.DataFrame(scaled_training, columns=training_data_df.columns.values)\nscaled_testing_df = pd.DataFrame(scaled_testing, columns=test_data_df.columns.values)\n\n#save the scaled dataframe to new csv files\nscaled_training_df.to_csv(\"sales_data_training_scaled.csv\", index=False)\nscaled_training_df.to_csv(\"sales_data_test_scaled.csv\", index=False)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> class Graph: <|reserved_special_token_0|> def appendNode(self, node): if node.name in self.placeholderNames and node.isPlaceholder: raise Exception( 'Placeholder name "{}" is already in use in current graph'. format(node.name)) elif node.isPlaceholder: self.placeholderNames.append(node.name) self.nodes.append(node) def set_default(self): init() global _default_graph _default_graph = self def visualize_nodes(self, node): gv_file = 'graph "" \n{\n' global nodeCounter nodeCounter = 0 def recurse(nodes, gv_file, parent_node_str=None): global nodeCounter nodes_list = [] if isinstance(nodes, list): nodes_list.extend(nodes) else: nodes_list.append(nodes) for node in nodes_list: current_node_str = 'n' + str(nodeCounter) nodeCounter += 1 """ operation might contain non-node constants, hence need to make sure that they are converted to node""" if type(node) in (int, float): node = tinyTensor.Node.Node.variable(node) """creating the node labels""" if isinstance(node, tinyTensor.Operation.Operation): gv_file += (current_node_str + ' [label="{} ({})"] ;\n' .format(node.operator, node.value)) elif node.isPlaceholder: gv_file += (current_node_str + ' [label="{}({})"] ;\n'. format(node.name, node.value)) else: gv_file += (current_node_str + ' [label="{}({})"] ;\n'. format(node.name, node.value)) if parent_node_str != None: gv_file += (parent_node_str + ' -- ' + current_node_str + '; \n') if len(node.inputNodes) > 0: gv_file = recurse(node.inputNodes, gv_file, current_node_str) return gv_file gv_file = recurse(node, gv_file) gv_file += '}\n' with open('network.gv', 'w+') as file: file.writelines(gv_file) print(gv_file) def visualize_layers(self, layer_list): neuron_dict = {} gv_file = 'graph "" \n{\n' for node in layer_list[0].inputList: neuron_dict[node] = node.name gv_file += neuron_dict[node] + ' [label="{}({})"] ;\n'.format(node .name, node.value) for layer in layer_list: for neuron in layer.neuronList: neuron_dict[neuron] = '{}'.format(neuron.name) gv_file += neuron_dict[neuron ] + ' [label="{}({})"] ;\n'.format(neuron.name, neuron. value) for layer in layer_list: for neuron in layer.neuronList: for input_neuron in neuron.inputNeurons: gv_file += neuron_dict[neuron] + ' -- ' + neuron_dict[ input_neuron] + '; \n' gv_file += '}\n' with open('network.gv', 'w+') as file: file.writelines(gv_file) print(gv_file) <|reserved_special_token_1|> <|reserved_special_token_0|> def postOrder(node): nodes_postorder = [] def recurse(node): if isinstance(node, tinyTensor.Node.Node): for input_node in node.inputNodes: recurse(input_node) nodes_postorder.append(node) recurse(node) return nodes_postorder class Graph: def __init__(self): self.nodes = [] self.placeholderNames = [] def appendNode(self, node): if node.name in self.placeholderNames and node.isPlaceholder: raise Exception( 'Placeholder name "{}" is already in use in current graph'. format(node.name)) elif node.isPlaceholder: self.placeholderNames.append(node.name) self.nodes.append(node) def set_default(self): init() global _default_graph _default_graph = self def visualize_nodes(self, node): gv_file = 'graph "" \n{\n' global nodeCounter nodeCounter = 0 def recurse(nodes, gv_file, parent_node_str=None): global nodeCounter nodes_list = [] if isinstance(nodes, list): nodes_list.extend(nodes) else: nodes_list.append(nodes) for node in nodes_list: current_node_str = 'n' + str(nodeCounter) nodeCounter += 1 """ operation might contain non-node constants, hence need to make sure that they are converted to node""" if type(node) in (int, float): node = tinyTensor.Node.Node.variable(node) """creating the node labels""" if isinstance(node, tinyTensor.Operation.Operation): gv_file += (current_node_str + ' [label="{} ({})"] ;\n' .format(node.operator, node.value)) elif node.isPlaceholder: gv_file += (current_node_str + ' [label="{}({})"] ;\n'. format(node.name, node.value)) else: gv_file += (current_node_str + ' [label="{}({})"] ;\n'. format(node.name, node.value)) if parent_node_str != None: gv_file += (parent_node_str + ' -- ' + current_node_str + '; \n') if len(node.inputNodes) > 0: gv_file = recurse(node.inputNodes, gv_file, current_node_str) return gv_file gv_file = recurse(node, gv_file) gv_file += '}\n' with open('network.gv', 'w+') as file: file.writelines(gv_file) print(gv_file) def visualize_layers(self, layer_list): neuron_dict = {} gv_file = 'graph "" \n{\n' for node in layer_list[0].inputList: neuron_dict[node] = node.name gv_file += neuron_dict[node] + ' [label="{}({})"] ;\n'.format(node .name, node.value) for layer in layer_list: for neuron in layer.neuronList: neuron_dict[neuron] = '{}'.format(neuron.name) gv_file += neuron_dict[neuron ] + ' [label="{}({})"] ;\n'.format(neuron.name, neuron. value) for layer in layer_list: for neuron in layer.neuronList: for input_neuron in neuron.inputNeurons: gv_file += neuron_dict[neuron] + ' -- ' + neuron_dict[ input_neuron] + '; \n' gv_file += '}\n' with open('network.gv', 'w+') as file: file.writelines(gv_file) print(gv_file) <|reserved_special_token_1|> <|reserved_special_token_0|> def init(): global _default_graph _default_graph = None def postOrder(node): nodes_postorder = [] def recurse(node): if isinstance(node, tinyTensor.Node.Node): for input_node in node.inputNodes: recurse(input_node) nodes_postorder.append(node) recurse(node) return nodes_postorder class Graph: def __init__(self): self.nodes = [] self.placeholderNames = [] def appendNode(self, node): if node.name in self.placeholderNames and node.isPlaceholder: raise Exception( 'Placeholder name "{}" is already in use in current graph'. format(node.name)) elif node.isPlaceholder: self.placeholderNames.append(node.name) self.nodes.append(node) def set_default(self): init() global _default_graph _default_graph = self def visualize_nodes(self, node): gv_file = 'graph "" \n{\n' global nodeCounter nodeCounter = 0 def recurse(nodes, gv_file, parent_node_str=None): global nodeCounter nodes_list = [] if isinstance(nodes, list): nodes_list.extend(nodes) else: nodes_list.append(nodes) for node in nodes_list: current_node_str = 'n' + str(nodeCounter) nodeCounter += 1 """ operation might contain non-node constants, hence need to make sure that they are converted to node""" if type(node) in (int, float): node = tinyTensor.Node.Node.variable(node) """creating the node labels""" if isinstance(node, tinyTensor.Operation.Operation): gv_file += (current_node_str + ' [label="{} ({})"] ;\n' .format(node.operator, node.value)) elif node.isPlaceholder: gv_file += (current_node_str + ' [label="{}({})"] ;\n'. format(node.name, node.value)) else: gv_file += (current_node_str + ' [label="{}({})"] ;\n'. format(node.name, node.value)) if parent_node_str != None: gv_file += (parent_node_str + ' -- ' + current_node_str + '; \n') if len(node.inputNodes) > 0: gv_file = recurse(node.inputNodes, gv_file, current_node_str) return gv_file gv_file = recurse(node, gv_file) gv_file += '}\n' with open('network.gv', 'w+') as file: file.writelines(gv_file) print(gv_file) def visualize_layers(self, layer_list): neuron_dict = {} gv_file = 'graph "" \n{\n' for node in layer_list[0].inputList: neuron_dict[node] = node.name gv_file += neuron_dict[node] + ' [label="{}({})"] ;\n'.format(node .name, node.value) for layer in layer_list: for neuron in layer.neuronList: neuron_dict[neuron] = '{}'.format(neuron.name) gv_file += neuron_dict[neuron ] + ' [label="{}({})"] ;\n'.format(neuron.name, neuron. value) for layer in layer_list: for neuron in layer.neuronList: for input_neuron in neuron.inputNeurons: gv_file += neuron_dict[neuron] + ' -- ' + neuron_dict[ input_neuron] + '; \n' gv_file += '}\n' with open('network.gv', 'w+') as file: file.writelines(gv_file) print(gv_file) <|reserved_special_token_1|> import tinyTensor import plotly.plotly as py from graphviz import render def init(): global _default_graph _default_graph = None def postOrder(node): nodes_postorder = [] def recurse(node): if isinstance(node, tinyTensor.Node.Node): for input_node in node.inputNodes: recurse(input_node) nodes_postorder.append(node) recurse(node) return nodes_postorder class Graph: def __init__(self): self.nodes = [] self.placeholderNames = [] def appendNode(self, node): if node.name in self.placeholderNames and node.isPlaceholder: raise Exception( 'Placeholder name "{}" is already in use in current graph'. format(node.name)) elif node.isPlaceholder: self.placeholderNames.append(node.name) self.nodes.append(node) def set_default(self): init() global _default_graph _default_graph = self def visualize_nodes(self, node): gv_file = 'graph "" \n{\n' global nodeCounter nodeCounter = 0 def recurse(nodes, gv_file, parent_node_str=None): global nodeCounter nodes_list = [] if isinstance(nodes, list): nodes_list.extend(nodes) else: nodes_list.append(nodes) for node in nodes_list: current_node_str = 'n' + str(nodeCounter) nodeCounter += 1 """ operation might contain non-node constants, hence need to make sure that they are converted to node""" if type(node) in (int, float): node = tinyTensor.Node.Node.variable(node) """creating the node labels""" if isinstance(node, tinyTensor.Operation.Operation): gv_file += (current_node_str + ' [label="{} ({})"] ;\n' .format(node.operator, node.value)) elif node.isPlaceholder: gv_file += (current_node_str + ' [label="{}({})"] ;\n'. format(node.name, node.value)) else: gv_file += (current_node_str + ' [label="{}({})"] ;\n'. format(node.name, node.value)) if parent_node_str != None: gv_file += (parent_node_str + ' -- ' + current_node_str + '; \n') if len(node.inputNodes) > 0: gv_file = recurse(node.inputNodes, gv_file, current_node_str) return gv_file gv_file = recurse(node, gv_file) gv_file += '}\n' with open('network.gv', 'w+') as file: file.writelines(gv_file) print(gv_file) def visualize_layers(self, layer_list): neuron_dict = {} gv_file = 'graph "" \n{\n' for node in layer_list[0].inputList: neuron_dict[node] = node.name gv_file += neuron_dict[node] + ' [label="{}({})"] ;\n'.format(node .name, node.value) for layer in layer_list: for neuron in layer.neuronList: neuron_dict[neuron] = '{}'.format(neuron.name) gv_file += neuron_dict[neuron ] + ' [label="{}({})"] ;\n'.format(neuron.name, neuron. value) for layer in layer_list: for neuron in layer.neuronList: for input_neuron in neuron.inputNeurons: gv_file += neuron_dict[neuron] + ' -- ' + neuron_dict[ input_neuron] + '; \n' gv_file += '}\n' with open('network.gv', 'w+') as file: file.writelines(gv_file) print(gv_file) <|reserved_special_token_1|> #from tinyTensor.Node import Node import tinyTensor import plotly.plotly as py from graphviz import render #from tinyTensor.Operation import Operation def init(): global _default_graph _default_graph = None def postOrder(node): nodes_postorder = [] def recurse(node): if isinstance(node, tinyTensor.Node.Node): for input_node in node.inputNodes: recurse(input_node) nodes_postorder.append(node) recurse(node) return nodes_postorder class Graph(): def __init__(self): self.nodes = [] self.placeholderNames = [] def appendNode(self,node): if(node.name in self.placeholderNames and node.isPlaceholder): raise Exception("Placeholder name \"{}\" is already in use in current graph".format(node.name)) elif(node.isPlaceholder): self.placeholderNames.append(node.name) self.nodes.append(node) def set_default(self): init() global _default_graph _default_graph = self def visualize_nodes(self, node): # generating the .gv file gv_file = "graph \"\" \n{\n" global nodeCounter nodeCounter = 0 def recurse(nodes,gv_file,parent_node_str = None): global nodeCounter nodes_list = [] if(isinstance(nodes,list)): nodes_list.extend(nodes) else: nodes_list.append(nodes) for node in nodes_list: # node should add itself to the list current_node_str = "n" + str(nodeCounter) nodeCounter += 1 ''' operation might contain non-node constants, hence need to make sure that they are converted to node''' if(type(node) in (int,float)): node = tinyTensor.Node.Node.variable(node) # creating a variable node '''creating the node labels''' if(isinstance(node,tinyTensor.Operation.Operation)): gv_file += current_node_str + " [label=\"{} ({})\"] ;\n".format(node.operator,node.value) elif(node.isPlaceholder): gv_file += current_node_str + " [label=\"{}({})\"] ;\n".format(node.name,node.value) else: gv_file += current_node_str + " [label=\"{}({})\"] ;\n".format(node.name,node.value) # now creating connection line to parent(s) TODO: make it possible to have many parents, (nodes should have output nodes list) if(parent_node_str != None): gv_file += parent_node_str + " -- " + current_node_str + "; \n" # applying the same to the children of this node if(len(node.inputNodes) > 0): gv_file = recurse(node.inputNodes,gv_file,current_node_str) return gv_file gv_file = recurse(node,gv_file) gv_file += "}\n" with open("network.gv","w+") as file: file.writelines(gv_file) #render('dot','png','network.gv') print(gv_file) def visualize_layers(self,layer_list): neuron_dict = {} #generating dict of neurons gv_file = "graph \"\" \n{\n" #dealing with input nodes for node in layer_list[0].inputList: neuron_dict[node] = node.name gv_file += neuron_dict[node] + " [label=\"{}({})\"] ;\n".format(node.name,node.value) # creating dict for neurons for layer in layer_list: for neuron in layer.neuronList: neuron_dict[neuron] = "{}".format(neuron.name) gv_file += neuron_dict[neuron] + " [label=\"{}({})\"] ;\n".format(neuron.name,neuron.value) # drawing links between neurons for layer in layer_list: for neuron in layer.neuronList: for input_neuron in neuron.inputNeurons: gv_file += neuron_dict[neuron] + " -- " + neuron_dict[input_neuron] + "; \n" gv_file += "}\n" with open("network.gv","w+") as file: file.writelines(gv_file) print(gv_file)
flexible
{ "blob_id": "7bd2a29bff1e435cf813dd54109d7f4e17612425", "index": 474, "step-1": "<mask token>\n\n\nclass Graph:\n <mask token>\n\n def appendNode(self, node):\n if node.name in self.placeholderNames and node.isPlaceholder:\n raise Exception(\n 'Placeholder name \"{}\" is already in use in current graph'.\n format(node.name))\n elif node.isPlaceholder:\n self.placeholderNames.append(node.name)\n self.nodes.append(node)\n\n def set_default(self):\n init()\n global _default_graph\n _default_graph = self\n\n def visualize_nodes(self, node):\n gv_file = 'graph \"\" \\n{\\n'\n global nodeCounter\n nodeCounter = 0\n\n def recurse(nodes, gv_file, parent_node_str=None):\n global nodeCounter\n nodes_list = []\n if isinstance(nodes, list):\n nodes_list.extend(nodes)\n else:\n nodes_list.append(nodes)\n for node in nodes_list:\n current_node_str = 'n' + str(nodeCounter)\n nodeCounter += 1\n \"\"\" operation might contain non-node constants, hence need to make sure that they are converted to node\"\"\"\n if type(node) in (int, float):\n node = tinyTensor.Node.Node.variable(node)\n \"\"\"creating the node labels\"\"\"\n if isinstance(node, tinyTensor.Operation.Operation):\n gv_file += (current_node_str + ' [label=\"{} ({})\"] ;\\n'\n .format(node.operator, node.value))\n elif node.isPlaceholder:\n gv_file += (current_node_str + ' [label=\"{}({})\"] ;\\n'.\n format(node.name, node.value))\n else:\n gv_file += (current_node_str + ' [label=\"{}({})\"] ;\\n'.\n format(node.name, node.value))\n if parent_node_str != None:\n gv_file += (parent_node_str + ' -- ' + current_node_str +\n '; \\n')\n if len(node.inputNodes) > 0:\n gv_file = recurse(node.inputNodes, gv_file,\n current_node_str)\n return gv_file\n gv_file = recurse(node, gv_file)\n gv_file += '}\\n'\n with open('network.gv', 'w+') as file:\n file.writelines(gv_file)\n print(gv_file)\n\n def visualize_layers(self, layer_list):\n neuron_dict = {}\n gv_file = 'graph \"\" \\n{\\n'\n for node in layer_list[0].inputList:\n neuron_dict[node] = node.name\n gv_file += neuron_dict[node] + ' [label=\"{}({})\"] ;\\n'.format(node\n .name, node.value)\n for layer in layer_list:\n for neuron in layer.neuronList:\n neuron_dict[neuron] = '{}'.format(neuron.name)\n gv_file += neuron_dict[neuron\n ] + ' [label=\"{}({})\"] ;\\n'.format(neuron.name, neuron.\n value)\n for layer in layer_list:\n for neuron in layer.neuronList:\n for input_neuron in neuron.inputNeurons:\n gv_file += neuron_dict[neuron] + ' -- ' + neuron_dict[\n input_neuron] + '; \\n'\n gv_file += '}\\n'\n with open('network.gv', 'w+') as file:\n file.writelines(gv_file)\n print(gv_file)\n", "step-2": "<mask token>\n\n\ndef postOrder(node):\n nodes_postorder = []\n\n def recurse(node):\n if isinstance(node, tinyTensor.Node.Node):\n for input_node in node.inputNodes:\n recurse(input_node)\n nodes_postorder.append(node)\n recurse(node)\n return nodes_postorder\n\n\nclass Graph:\n\n def __init__(self):\n self.nodes = []\n self.placeholderNames = []\n\n def appendNode(self, node):\n if node.name in self.placeholderNames and node.isPlaceholder:\n raise Exception(\n 'Placeholder name \"{}\" is already in use in current graph'.\n format(node.name))\n elif node.isPlaceholder:\n self.placeholderNames.append(node.name)\n self.nodes.append(node)\n\n def set_default(self):\n init()\n global _default_graph\n _default_graph = self\n\n def visualize_nodes(self, node):\n gv_file = 'graph \"\" \\n{\\n'\n global nodeCounter\n nodeCounter = 0\n\n def recurse(nodes, gv_file, parent_node_str=None):\n global nodeCounter\n nodes_list = []\n if isinstance(nodes, list):\n nodes_list.extend(nodes)\n else:\n nodes_list.append(nodes)\n for node in nodes_list:\n current_node_str = 'n' + str(nodeCounter)\n nodeCounter += 1\n \"\"\" operation might contain non-node constants, hence need to make sure that they are converted to node\"\"\"\n if type(node) in (int, float):\n node = tinyTensor.Node.Node.variable(node)\n \"\"\"creating the node labels\"\"\"\n if isinstance(node, tinyTensor.Operation.Operation):\n gv_file += (current_node_str + ' [label=\"{} ({})\"] ;\\n'\n .format(node.operator, node.value))\n elif node.isPlaceholder:\n gv_file += (current_node_str + ' [label=\"{}({})\"] ;\\n'.\n format(node.name, node.value))\n else:\n gv_file += (current_node_str + ' [label=\"{}({})\"] ;\\n'.\n format(node.name, node.value))\n if parent_node_str != None:\n gv_file += (parent_node_str + ' -- ' + current_node_str +\n '; \\n')\n if len(node.inputNodes) > 0:\n gv_file = recurse(node.inputNodes, gv_file,\n current_node_str)\n return gv_file\n gv_file = recurse(node, gv_file)\n gv_file += '}\\n'\n with open('network.gv', 'w+') as file:\n file.writelines(gv_file)\n print(gv_file)\n\n def visualize_layers(self, layer_list):\n neuron_dict = {}\n gv_file = 'graph \"\" \\n{\\n'\n for node in layer_list[0].inputList:\n neuron_dict[node] = node.name\n gv_file += neuron_dict[node] + ' [label=\"{}({})\"] ;\\n'.format(node\n .name, node.value)\n for layer in layer_list:\n for neuron in layer.neuronList:\n neuron_dict[neuron] = '{}'.format(neuron.name)\n gv_file += neuron_dict[neuron\n ] + ' [label=\"{}({})\"] ;\\n'.format(neuron.name, neuron.\n value)\n for layer in layer_list:\n for neuron in layer.neuronList:\n for input_neuron in neuron.inputNeurons:\n gv_file += neuron_dict[neuron] + ' -- ' + neuron_dict[\n input_neuron] + '; \\n'\n gv_file += '}\\n'\n with open('network.gv', 'w+') as file:\n file.writelines(gv_file)\n print(gv_file)\n", "step-3": "<mask token>\n\n\ndef init():\n global _default_graph\n _default_graph = None\n\n\ndef postOrder(node):\n nodes_postorder = []\n\n def recurse(node):\n if isinstance(node, tinyTensor.Node.Node):\n for input_node in node.inputNodes:\n recurse(input_node)\n nodes_postorder.append(node)\n recurse(node)\n return nodes_postorder\n\n\nclass Graph:\n\n def __init__(self):\n self.nodes = []\n self.placeholderNames = []\n\n def appendNode(self, node):\n if node.name in self.placeholderNames and node.isPlaceholder:\n raise Exception(\n 'Placeholder name \"{}\" is already in use in current graph'.\n format(node.name))\n elif node.isPlaceholder:\n self.placeholderNames.append(node.name)\n self.nodes.append(node)\n\n def set_default(self):\n init()\n global _default_graph\n _default_graph = self\n\n def visualize_nodes(self, node):\n gv_file = 'graph \"\" \\n{\\n'\n global nodeCounter\n nodeCounter = 0\n\n def recurse(nodes, gv_file, parent_node_str=None):\n global nodeCounter\n nodes_list = []\n if isinstance(nodes, list):\n nodes_list.extend(nodes)\n else:\n nodes_list.append(nodes)\n for node in nodes_list:\n current_node_str = 'n' + str(nodeCounter)\n nodeCounter += 1\n \"\"\" operation might contain non-node constants, hence need to make sure that they are converted to node\"\"\"\n if type(node) in (int, float):\n node = tinyTensor.Node.Node.variable(node)\n \"\"\"creating the node labels\"\"\"\n if isinstance(node, tinyTensor.Operation.Operation):\n gv_file += (current_node_str + ' [label=\"{} ({})\"] ;\\n'\n .format(node.operator, node.value))\n elif node.isPlaceholder:\n gv_file += (current_node_str + ' [label=\"{}({})\"] ;\\n'.\n format(node.name, node.value))\n else:\n gv_file += (current_node_str + ' [label=\"{}({})\"] ;\\n'.\n format(node.name, node.value))\n if parent_node_str != None:\n gv_file += (parent_node_str + ' -- ' + current_node_str +\n '; \\n')\n if len(node.inputNodes) > 0:\n gv_file = recurse(node.inputNodes, gv_file,\n current_node_str)\n return gv_file\n gv_file = recurse(node, gv_file)\n gv_file += '}\\n'\n with open('network.gv', 'w+') as file:\n file.writelines(gv_file)\n print(gv_file)\n\n def visualize_layers(self, layer_list):\n neuron_dict = {}\n gv_file = 'graph \"\" \\n{\\n'\n for node in layer_list[0].inputList:\n neuron_dict[node] = node.name\n gv_file += neuron_dict[node] + ' [label=\"{}({})\"] ;\\n'.format(node\n .name, node.value)\n for layer in layer_list:\n for neuron in layer.neuronList:\n neuron_dict[neuron] = '{}'.format(neuron.name)\n gv_file += neuron_dict[neuron\n ] + ' [label=\"{}({})\"] ;\\n'.format(neuron.name, neuron.\n value)\n for layer in layer_list:\n for neuron in layer.neuronList:\n for input_neuron in neuron.inputNeurons:\n gv_file += neuron_dict[neuron] + ' -- ' + neuron_dict[\n input_neuron] + '; \\n'\n gv_file += '}\\n'\n with open('network.gv', 'w+') as file:\n file.writelines(gv_file)\n print(gv_file)\n", "step-4": "import tinyTensor\nimport plotly.plotly as py\nfrom graphviz import render\n\n\ndef init():\n global _default_graph\n _default_graph = None\n\n\ndef postOrder(node):\n nodes_postorder = []\n\n def recurse(node):\n if isinstance(node, tinyTensor.Node.Node):\n for input_node in node.inputNodes:\n recurse(input_node)\n nodes_postorder.append(node)\n recurse(node)\n return nodes_postorder\n\n\nclass Graph:\n\n def __init__(self):\n self.nodes = []\n self.placeholderNames = []\n\n def appendNode(self, node):\n if node.name in self.placeholderNames and node.isPlaceholder:\n raise Exception(\n 'Placeholder name \"{}\" is already in use in current graph'.\n format(node.name))\n elif node.isPlaceholder:\n self.placeholderNames.append(node.name)\n self.nodes.append(node)\n\n def set_default(self):\n init()\n global _default_graph\n _default_graph = self\n\n def visualize_nodes(self, node):\n gv_file = 'graph \"\" \\n{\\n'\n global nodeCounter\n nodeCounter = 0\n\n def recurse(nodes, gv_file, parent_node_str=None):\n global nodeCounter\n nodes_list = []\n if isinstance(nodes, list):\n nodes_list.extend(nodes)\n else:\n nodes_list.append(nodes)\n for node in nodes_list:\n current_node_str = 'n' + str(nodeCounter)\n nodeCounter += 1\n \"\"\" operation might contain non-node constants, hence need to make sure that they are converted to node\"\"\"\n if type(node) in (int, float):\n node = tinyTensor.Node.Node.variable(node)\n \"\"\"creating the node labels\"\"\"\n if isinstance(node, tinyTensor.Operation.Operation):\n gv_file += (current_node_str + ' [label=\"{} ({})\"] ;\\n'\n .format(node.operator, node.value))\n elif node.isPlaceholder:\n gv_file += (current_node_str + ' [label=\"{}({})\"] ;\\n'.\n format(node.name, node.value))\n else:\n gv_file += (current_node_str + ' [label=\"{}({})\"] ;\\n'.\n format(node.name, node.value))\n if parent_node_str != None:\n gv_file += (parent_node_str + ' -- ' + current_node_str +\n '; \\n')\n if len(node.inputNodes) > 0:\n gv_file = recurse(node.inputNodes, gv_file,\n current_node_str)\n return gv_file\n gv_file = recurse(node, gv_file)\n gv_file += '}\\n'\n with open('network.gv', 'w+') as file:\n file.writelines(gv_file)\n print(gv_file)\n\n def visualize_layers(self, layer_list):\n neuron_dict = {}\n gv_file = 'graph \"\" \\n{\\n'\n for node in layer_list[0].inputList:\n neuron_dict[node] = node.name\n gv_file += neuron_dict[node] + ' [label=\"{}({})\"] ;\\n'.format(node\n .name, node.value)\n for layer in layer_list:\n for neuron in layer.neuronList:\n neuron_dict[neuron] = '{}'.format(neuron.name)\n gv_file += neuron_dict[neuron\n ] + ' [label=\"{}({})\"] ;\\n'.format(neuron.name, neuron.\n value)\n for layer in layer_list:\n for neuron in layer.neuronList:\n for input_neuron in neuron.inputNeurons:\n gv_file += neuron_dict[neuron] + ' -- ' + neuron_dict[\n input_neuron] + '; \\n'\n gv_file += '}\\n'\n with open('network.gv', 'w+') as file:\n file.writelines(gv_file)\n print(gv_file)\n", "step-5": "#from tinyTensor.Node import Node\r\nimport tinyTensor\r\nimport plotly.plotly as py\r\nfrom graphviz import render\r\n#from tinyTensor.Operation import Operation\r\n\r\n\r\ndef init():\r\n global _default_graph\r\n _default_graph = None\r\n\r\ndef postOrder(node):\r\n nodes_postorder = []\r\n def recurse(node):\r\n if isinstance(node, tinyTensor.Node.Node):\r\n for input_node in node.inputNodes:\r\n recurse(input_node)\r\n nodes_postorder.append(node)\r\n recurse(node)\r\n return nodes_postorder\r\n\r\nclass Graph():\r\n\r\n def __init__(self):\r\n self.nodes = []\r\n self.placeholderNames = []\r\n\r\n def appendNode(self,node):\r\n if(node.name in self.placeholderNames and node.isPlaceholder):\r\n raise Exception(\"Placeholder name \\\"{}\\\" is already in use in current graph\".format(node.name))\r\n elif(node.isPlaceholder):\r\n self.placeholderNames.append(node.name)\r\n self.nodes.append(node)\r\n\r\n def set_default(self):\r\n init()\r\n global _default_graph\r\n _default_graph = self\r\n\r\n def visualize_nodes(self, node):\r\n # generating the .gv file\r\n gv_file = \"graph \\\"\\\" \\n{\\n\"\r\n global nodeCounter\r\n nodeCounter = 0\r\n def recurse(nodes,gv_file,parent_node_str = None):\r\n global nodeCounter\r\n nodes_list = []\r\n if(isinstance(nodes,list)):\r\n nodes_list.extend(nodes)\r\n else:\r\n nodes_list.append(nodes)\r\n for node in nodes_list:\r\n # node should add itself to the list\r\n current_node_str = \"n\" + str(nodeCounter)\r\n nodeCounter += 1\r\n ''' operation might contain non-node constants, hence need to make sure that they are converted to node'''\r\n if(type(node) in (int,float)):\r\n node = tinyTensor.Node.Node.variable(node) # creating a variable node\r\n '''creating the node labels'''\r\n if(isinstance(node,tinyTensor.Operation.Operation)):\r\n gv_file += current_node_str + \" [label=\\\"{} ({})\\\"] ;\\n\".format(node.operator,node.value)\r\n elif(node.isPlaceholder):\r\n gv_file += current_node_str + \" [label=\\\"{}({})\\\"] ;\\n\".format(node.name,node.value)\r\n else:\r\n gv_file += current_node_str + \" [label=\\\"{}({})\\\"] ;\\n\".format(node.name,node.value)\r\n # now creating connection line to parent(s) TODO: make it possible to have many parents, (nodes should have output nodes list)\r\n if(parent_node_str != None):\r\n gv_file += parent_node_str + \" -- \" + current_node_str + \"; \\n\"\r\n # applying the same to the children of this node\r\n if(len(node.inputNodes) > 0):\r\n gv_file = recurse(node.inputNodes,gv_file,current_node_str)\r\n return gv_file\r\n gv_file = recurse(node,gv_file)\r\n gv_file += \"}\\n\"\r\n with open(\"network.gv\",\"w+\") as file:\r\n file.writelines(gv_file)\r\n #render('dot','png','network.gv')\r\n print(gv_file)\r\n\r\n def visualize_layers(self,layer_list):\r\n neuron_dict = {}\r\n #generating dict of neurons\r\n gv_file = \"graph \\\"\\\" \\n{\\n\"\r\n #dealing with input nodes\r\n for node in layer_list[0].inputList:\r\n neuron_dict[node] = node.name\r\n gv_file += neuron_dict[node] + \" [label=\\\"{}({})\\\"] ;\\n\".format(node.name,node.value)\r\n # creating dict for neurons\r\n for layer in layer_list:\r\n for neuron in layer.neuronList:\r\n neuron_dict[neuron] = \"{}\".format(neuron.name)\r\n gv_file += neuron_dict[neuron] + \" [label=\\\"{}({})\\\"] ;\\n\".format(neuron.name,neuron.value)\r\n # drawing links between neurons\r\n for layer in layer_list:\r\n for neuron in layer.neuronList:\r\n for input_neuron in neuron.inputNeurons:\r\n gv_file += neuron_dict[neuron] + \" -- \" + neuron_dict[input_neuron] + \"; \\n\"\r\n gv_file += \"}\\n\"\r\n with open(\"network.gv\",\"w+\") as file:\r\n file.writelines(gv_file)\r\n print(gv_file)\r\n\r\n\r\n\r\n\r\n", "step-ids": [ 5, 7, 8, 9, 10 ] }
[ 5, 7, 8, 9, 10 ]
contador_pares = 0 contador_impares = 0 for i in range(100): numero = int(input('Digite um valor:')) if numero % 2 == 0: contador_pares += 1 else: contador_impares += 1 print('A quantidade de números pares é igual a:', contador_pares) print('A quantidade de números ímpares é igual a:', contador_impares)
normal
{ "blob_id": "03aa33861def30a46de85c5b309878a1180a760f", "index": 5211, "step-1": "<mask token>\n", "step-2": "<mask token>\nfor i in range(100):\n numero = int(input('Digite um valor:'))\n if numero % 2 == 0:\n contador_pares += 1\n else:\n contador_impares += 1\nprint('A quantidade de números pares é igual a:', contador_pares)\nprint('A quantidade de números ímpares é igual a:', contador_impares)\n", "step-3": "contador_pares = 0\ncontador_impares = 0\nfor i in range(100):\n numero = int(input('Digite um valor:'))\n if numero % 2 == 0:\n contador_pares += 1\n else:\n contador_impares += 1\nprint('A quantidade de números pares é igual a:', contador_pares)\nprint('A quantidade de números ímpares é igual a:', contador_impares)\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def generate(env): def remove_doctype(target, source, env): f = open(str(target[0])) output = [] for line in f.readlines(): output.append(re.sub('^<!DOCTYPE .*', '', line)) f.close() f = open(str(target[0]), 'wb') for line in output: f.write(line) f.close() def buildDocBook(env, source): db_env = env.Clone() db_env['XMLCATALOGS'] = [db_env['DOCBOOK_XML']] fo = db_env.XSLT(os.path.splitext(source)[0] + '.fo', source, XSLTSTYLESHEET=db_env['DOCBOOK_XSL_FO']) pdf = db_env.FO(fo) db_env.XSLT(os.path.splitext(source)[0] + '.html', source, XSLTSTYLESHEET=db_env['DOCBOOK_XSL_HTML']) wp_params = [('wordpress.dir', env.get('DOCBOOK_WP_DIR', '../../wordpress'))] wp_pdf_url = env.get('DOCBOOK_WP_PDF_URL', pdf[0].name) if len(wp_pdf_url) > 0: wp_params.append(('pdf.url', wp_pdf_url)) wp_params.append(('pdf.icon', env.get('DOCBOOK_WP_PDF_ICON', '/icons/pdf.png'))) wp = db_env.XSLT(os.path.splitext(source)[0] + '.wp.php', source, XSLTSTYLESHEET=db_env['DOCBOOK_XSL_WP'], XSLTPARAMS=wp_params + env.get('XSLTPARAMS', [])) db_env.AddPostAction(wp, SCons.Action.Action(remove_doctype, cmdstr ='$FIXCOMSTR')) env.AddMethod(buildDocBook, 'DocBook') <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def generate(env): def remove_doctype(target, source, env): f = open(str(target[0])) output = [] for line in f.readlines(): output.append(re.sub('^<!DOCTYPE .*', '', line)) f.close() f = open(str(target[0]), 'wb') for line in output: f.write(line) f.close() def buildDocBook(env, source): db_env = env.Clone() db_env['XMLCATALOGS'] = [db_env['DOCBOOK_XML']] fo = db_env.XSLT(os.path.splitext(source)[0] + '.fo', source, XSLTSTYLESHEET=db_env['DOCBOOK_XSL_FO']) pdf = db_env.FO(fo) db_env.XSLT(os.path.splitext(source)[0] + '.html', source, XSLTSTYLESHEET=db_env['DOCBOOK_XSL_HTML']) wp_params = [('wordpress.dir', env.get('DOCBOOK_WP_DIR', '../../wordpress'))] wp_pdf_url = env.get('DOCBOOK_WP_PDF_URL', pdf[0].name) if len(wp_pdf_url) > 0: wp_params.append(('pdf.url', wp_pdf_url)) wp_params.append(('pdf.icon', env.get('DOCBOOK_WP_PDF_ICON', '/icons/pdf.png'))) wp = db_env.XSLT(os.path.splitext(source)[0] + '.wp.php', source, XSLTSTYLESHEET=db_env['DOCBOOK_XSL_WP'], XSLTPARAMS=wp_params + env.get('XSLTPARAMS', [])) db_env.AddPostAction(wp, SCons.Action.Action(remove_doctype, cmdstr ='$FIXCOMSTR')) env.AddMethod(buildDocBook, 'DocBook') def exists(env): return True <|reserved_special_token_1|> import SCons.Util import xml.dom.minidom, re, os.path def generate(env): def remove_doctype(target, source, env): f = open(str(target[0])) output = [] for line in f.readlines(): output.append(re.sub('^<!DOCTYPE .*', '', line)) f.close() f = open(str(target[0]), 'wb') for line in output: f.write(line) f.close() def buildDocBook(env, source): db_env = env.Clone() db_env['XMLCATALOGS'] = [db_env['DOCBOOK_XML']] fo = db_env.XSLT(os.path.splitext(source)[0] + '.fo', source, XSLTSTYLESHEET=db_env['DOCBOOK_XSL_FO']) pdf = db_env.FO(fo) db_env.XSLT(os.path.splitext(source)[0] + '.html', source, XSLTSTYLESHEET=db_env['DOCBOOK_XSL_HTML']) wp_params = [('wordpress.dir', env.get('DOCBOOK_WP_DIR', '../../wordpress'))] wp_pdf_url = env.get('DOCBOOK_WP_PDF_URL', pdf[0].name) if len(wp_pdf_url) > 0: wp_params.append(('pdf.url', wp_pdf_url)) wp_params.append(('pdf.icon', env.get('DOCBOOK_WP_PDF_ICON', '/icons/pdf.png'))) wp = db_env.XSLT(os.path.splitext(source)[0] + '.wp.php', source, XSLTSTYLESHEET=db_env['DOCBOOK_XSL_WP'], XSLTPARAMS=wp_params + env.get('XSLTPARAMS', [])) db_env.AddPostAction(wp, SCons.Action.Action(remove_doctype, cmdstr ='$FIXCOMSTR')) env.AddMethod(buildDocBook, 'DocBook') def exists(env): return True <|reserved_special_token_1|> import SCons.Util import xml.dom.minidom, re, os.path ################################################################################ # DocBook pseudobuilder # TODO: Only generate the output formats that are known ################################################################################ def generate(env) : def remove_doctype(target, source, env) : f = open(str(target[0])) output = [] for line in f.readlines() : output.append(re.sub("^<!DOCTYPE .*", "", line)) f.close() f = open(str(target[0]), 'wb') for line in output : f.write(line) f.close() def buildDocBook(env, source) : db_env = env.Clone() db_env["XMLCATALOGS"] = [db_env["DOCBOOK_XML"]] # PDF generation fo = db_env.XSLT(os.path.splitext(source)[0] + ".fo", source, XSLTSTYLESHEET = db_env["DOCBOOK_XSL_FO"]) pdf = db_env.FO(fo) # HTML generation db_env.XSLT(os.path.splitext(source)[0] + ".html", source, XSLTSTYLESHEET = db_env["DOCBOOK_XSL_HTML"]) # WordPress generation wp_params = [("wordpress.dir", env.get("DOCBOOK_WP_DIR", "../../wordpress"))] wp_pdf_url = env.get("DOCBOOK_WP_PDF_URL", pdf[0].name) if len(wp_pdf_url) > 0 : wp_params.append(("pdf.url", wp_pdf_url)) wp_params.append(("pdf.icon", env.get("DOCBOOK_WP_PDF_ICON", "/icons/pdf.png"))) wp = db_env.XSLT(os.path.splitext(source)[0] + ".wp.php", source, XSLTSTYLESHEET = db_env["DOCBOOK_XSL_WP"], XSLTPARAMS = wp_params + env.get("XSLTPARAMS", [])) db_env.AddPostAction(wp, SCons.Action.Action(remove_doctype, cmdstr = "$FIXCOMSTR")) env.AddMethod(buildDocBook, "DocBook") def exists(env) : return True
flexible
{ "blob_id": "cae49da8dd436fc51b472c4a88703d8bc6c79bda", "index": 427, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef generate(env):\n\n def remove_doctype(target, source, env):\n f = open(str(target[0]))\n output = []\n for line in f.readlines():\n output.append(re.sub('^<!DOCTYPE .*', '', line))\n f.close()\n f = open(str(target[0]), 'wb')\n for line in output:\n f.write(line)\n f.close()\n\n def buildDocBook(env, source):\n db_env = env.Clone()\n db_env['XMLCATALOGS'] = [db_env['DOCBOOK_XML']]\n fo = db_env.XSLT(os.path.splitext(source)[0] + '.fo', source,\n XSLTSTYLESHEET=db_env['DOCBOOK_XSL_FO'])\n pdf = db_env.FO(fo)\n db_env.XSLT(os.path.splitext(source)[0] + '.html', source,\n XSLTSTYLESHEET=db_env['DOCBOOK_XSL_HTML'])\n wp_params = [('wordpress.dir', env.get('DOCBOOK_WP_DIR',\n '../../wordpress'))]\n wp_pdf_url = env.get('DOCBOOK_WP_PDF_URL', pdf[0].name)\n if len(wp_pdf_url) > 0:\n wp_params.append(('pdf.url', wp_pdf_url))\n wp_params.append(('pdf.icon', env.get('DOCBOOK_WP_PDF_ICON',\n '/icons/pdf.png')))\n wp = db_env.XSLT(os.path.splitext(source)[0] + '.wp.php', source,\n XSLTSTYLESHEET=db_env['DOCBOOK_XSL_WP'], XSLTPARAMS=wp_params +\n env.get('XSLTPARAMS', []))\n db_env.AddPostAction(wp, SCons.Action.Action(remove_doctype, cmdstr\n ='$FIXCOMSTR'))\n env.AddMethod(buildDocBook, 'DocBook')\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef generate(env):\n\n def remove_doctype(target, source, env):\n f = open(str(target[0]))\n output = []\n for line in f.readlines():\n output.append(re.sub('^<!DOCTYPE .*', '', line))\n f.close()\n f = open(str(target[0]), 'wb')\n for line in output:\n f.write(line)\n f.close()\n\n def buildDocBook(env, source):\n db_env = env.Clone()\n db_env['XMLCATALOGS'] = [db_env['DOCBOOK_XML']]\n fo = db_env.XSLT(os.path.splitext(source)[0] + '.fo', source,\n XSLTSTYLESHEET=db_env['DOCBOOK_XSL_FO'])\n pdf = db_env.FO(fo)\n db_env.XSLT(os.path.splitext(source)[0] + '.html', source,\n XSLTSTYLESHEET=db_env['DOCBOOK_XSL_HTML'])\n wp_params = [('wordpress.dir', env.get('DOCBOOK_WP_DIR',\n '../../wordpress'))]\n wp_pdf_url = env.get('DOCBOOK_WP_PDF_URL', pdf[0].name)\n if len(wp_pdf_url) > 0:\n wp_params.append(('pdf.url', wp_pdf_url))\n wp_params.append(('pdf.icon', env.get('DOCBOOK_WP_PDF_ICON',\n '/icons/pdf.png')))\n wp = db_env.XSLT(os.path.splitext(source)[0] + '.wp.php', source,\n XSLTSTYLESHEET=db_env['DOCBOOK_XSL_WP'], XSLTPARAMS=wp_params +\n env.get('XSLTPARAMS', []))\n db_env.AddPostAction(wp, SCons.Action.Action(remove_doctype, cmdstr\n ='$FIXCOMSTR'))\n env.AddMethod(buildDocBook, 'DocBook')\n\n\ndef exists(env):\n return True\n", "step-4": "import SCons.Util\nimport xml.dom.minidom, re, os.path\n\n\ndef generate(env):\n\n def remove_doctype(target, source, env):\n f = open(str(target[0]))\n output = []\n for line in f.readlines():\n output.append(re.sub('^<!DOCTYPE .*', '', line))\n f.close()\n f = open(str(target[0]), 'wb')\n for line in output:\n f.write(line)\n f.close()\n\n def buildDocBook(env, source):\n db_env = env.Clone()\n db_env['XMLCATALOGS'] = [db_env['DOCBOOK_XML']]\n fo = db_env.XSLT(os.path.splitext(source)[0] + '.fo', source,\n XSLTSTYLESHEET=db_env['DOCBOOK_XSL_FO'])\n pdf = db_env.FO(fo)\n db_env.XSLT(os.path.splitext(source)[0] + '.html', source,\n XSLTSTYLESHEET=db_env['DOCBOOK_XSL_HTML'])\n wp_params = [('wordpress.dir', env.get('DOCBOOK_WP_DIR',\n '../../wordpress'))]\n wp_pdf_url = env.get('DOCBOOK_WP_PDF_URL', pdf[0].name)\n if len(wp_pdf_url) > 0:\n wp_params.append(('pdf.url', wp_pdf_url))\n wp_params.append(('pdf.icon', env.get('DOCBOOK_WP_PDF_ICON',\n '/icons/pdf.png')))\n wp = db_env.XSLT(os.path.splitext(source)[0] + '.wp.php', source,\n XSLTSTYLESHEET=db_env['DOCBOOK_XSL_WP'], XSLTPARAMS=wp_params +\n env.get('XSLTPARAMS', []))\n db_env.AddPostAction(wp, SCons.Action.Action(remove_doctype, cmdstr\n ='$FIXCOMSTR'))\n env.AddMethod(buildDocBook, 'DocBook')\n\n\ndef exists(env):\n return True\n", "step-5": "import SCons.Util\nimport xml.dom.minidom, re, os.path\n\n################################################################################\n# DocBook pseudobuilder\n# TODO: Only generate the output formats that are known\n################################################################################\n\ndef generate(env) :\n def remove_doctype(target, source, env) :\n f = open(str(target[0]))\n output = []\n for line in f.readlines() :\n output.append(re.sub(\"^<!DOCTYPE .*\", \"\", line))\n f.close()\n f = open(str(target[0]), 'wb')\n for line in output :\n f.write(line)\n f.close()\n\n def buildDocBook(env, source) :\n db_env = env.Clone()\n db_env[\"XMLCATALOGS\"] = [db_env[\"DOCBOOK_XML\"]]\n\n # PDF generation\n fo = db_env.XSLT(os.path.splitext(source)[0] + \".fo\", source, \n XSLTSTYLESHEET = db_env[\"DOCBOOK_XSL_FO\"])\n pdf = db_env.FO(fo)\n\n # HTML generation\n db_env.XSLT(os.path.splitext(source)[0] + \".html\", source, \n XSLTSTYLESHEET = db_env[\"DOCBOOK_XSL_HTML\"])\n\n # WordPress generation\n wp_params = [(\"wordpress.dir\", env.get(\"DOCBOOK_WP_DIR\", \"../../wordpress\"))]\n wp_pdf_url = env.get(\"DOCBOOK_WP_PDF_URL\", pdf[0].name)\n if len(wp_pdf_url) > 0 :\n wp_params.append((\"pdf.url\", wp_pdf_url))\n wp_params.append((\"pdf.icon\", env.get(\"DOCBOOK_WP_PDF_ICON\", \"/icons/pdf.png\")))\n wp = db_env.XSLT(os.path.splitext(source)[0] + \".wp.php\", source, \n XSLTSTYLESHEET = db_env[\"DOCBOOK_XSL_WP\"],\n XSLTPARAMS = wp_params + env.get(\"XSLTPARAMS\", []))\n db_env.AddPostAction(wp, SCons.Action.Action(remove_doctype, cmdstr = \"$FIXCOMSTR\"))\n\n env.AddMethod(buildDocBook, \"DocBook\")\n \ndef exists(env) :\n return True\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> class DataFrameCreatorBase: <|reserved_special_token_0|> <|reserved_special_token_0|> def __init__(self, input_file): self._input_file = input_file self.df = self._read_raw_csv() self._clean_df() <|reserved_special_token_0|> def _read_raw_csv(self): try: return pd.read_csv(f'files/input/{self._input_file}') except Exception as e: Logger.log_message(Logger.ERROR, f'Failed to convert csv file {self._input_file} to dataframe: {e}' ) sys.exit(1) def _clean_df(self): pass <|reserved_special_token_1|> <|reserved_special_token_0|> class DataFrameCreatorBase: <|reserved_special_token_0|> START_DATE = '03/16/2020' def __init__(self, input_file): self._input_file = input_file self.df = self._read_raw_csv() self._clean_df() def __new__(cls, *args, **kwargs): if not hasattr(cls, 'instance'): cls.instance = super().__new__(cls) return cls.instance def _read_raw_csv(self): try: return pd.read_csv(f'files/input/{self._input_file}') except Exception as e: Logger.log_message(Logger.ERROR, f'Failed to convert csv file {self._input_file} to dataframe: {e}' ) sys.exit(1) def _clean_df(self): pass <|reserved_special_token_1|> <|reserved_special_token_0|> class DataFrameCreatorBase: """ DataFrameCreatorBase """ START_DATE = '03/16/2020' def __init__(self, input_file): self._input_file = input_file self.df = self._read_raw_csv() self._clean_df() def __new__(cls, *args, **kwargs): if not hasattr(cls, 'instance'): cls.instance = super().__new__(cls) return cls.instance def _read_raw_csv(self): try: return pd.read_csv(f'files/input/{self._input_file}') except Exception as e: Logger.log_message(Logger.ERROR, f'Failed to convert csv file {self._input_file} to dataframe: {e}' ) sys.exit(1) def _clean_df(self): pass <|reserved_special_token_1|> import sys import pandas as pd from components.helpers.Logger import Logger class DataFrameCreatorBase: """ DataFrameCreatorBase """ START_DATE = '03/16/2020' def __init__(self, input_file): self._input_file = input_file self.df = self._read_raw_csv() self._clean_df() def __new__(cls, *args, **kwargs): if not hasattr(cls, 'instance'): cls.instance = super().__new__(cls) return cls.instance def _read_raw_csv(self): try: return pd.read_csv(f'files/input/{self._input_file}') except Exception as e: Logger.log_message(Logger.ERROR, f'Failed to convert csv file {self._input_file} to dataframe: {e}' ) sys.exit(1) def _clean_df(self): pass <|reserved_special_token_1|> import sys import pandas as pd from components.helpers.Logger import Logger class DataFrameCreatorBase: """ DataFrameCreatorBase """ START_DATE = "03/16/2020" def __init__(self, input_file): self._input_file = input_file self.df = self._read_raw_csv() self._clean_df() def __new__(cls, *args, **kwargs): if not hasattr(cls, 'instance'): cls.instance = super().__new__(cls) return cls.instance def _read_raw_csv(self): try: return pd.read_csv(f'files/input/{self._input_file}') except Exception as e: Logger.log_message( Logger.ERROR, f"Failed to convert csv file {self._input_file} to dataframe: {e}" ) sys.exit(1) def _clean_df(self): pass
flexible
{ "blob_id": "f4fa7563d2cce5ee28198d4974a4276d9f71f20b", "index": 4329, "step-1": "<mask token>\n\n\nclass DataFrameCreatorBase:\n <mask token>\n <mask token>\n\n def __init__(self, input_file):\n self._input_file = input_file\n self.df = self._read_raw_csv()\n self._clean_df()\n <mask token>\n\n def _read_raw_csv(self):\n try:\n return pd.read_csv(f'files/input/{self._input_file}')\n except Exception as e:\n Logger.log_message(Logger.ERROR,\n f'Failed to convert csv file {self._input_file} to dataframe: {e}'\n )\n sys.exit(1)\n\n def _clean_df(self):\n pass\n", "step-2": "<mask token>\n\n\nclass DataFrameCreatorBase:\n <mask token>\n START_DATE = '03/16/2020'\n\n def __init__(self, input_file):\n self._input_file = input_file\n self.df = self._read_raw_csv()\n self._clean_df()\n\n def __new__(cls, *args, **kwargs):\n if not hasattr(cls, 'instance'):\n cls.instance = super().__new__(cls)\n return cls.instance\n\n def _read_raw_csv(self):\n try:\n return pd.read_csv(f'files/input/{self._input_file}')\n except Exception as e:\n Logger.log_message(Logger.ERROR,\n f'Failed to convert csv file {self._input_file} to dataframe: {e}'\n )\n sys.exit(1)\n\n def _clean_df(self):\n pass\n", "step-3": "<mask token>\n\n\nclass DataFrameCreatorBase:\n \"\"\"\n DataFrameCreatorBase\n \"\"\"\n START_DATE = '03/16/2020'\n\n def __init__(self, input_file):\n self._input_file = input_file\n self.df = self._read_raw_csv()\n self._clean_df()\n\n def __new__(cls, *args, **kwargs):\n if not hasattr(cls, 'instance'):\n cls.instance = super().__new__(cls)\n return cls.instance\n\n def _read_raw_csv(self):\n try:\n return pd.read_csv(f'files/input/{self._input_file}')\n except Exception as e:\n Logger.log_message(Logger.ERROR,\n f'Failed to convert csv file {self._input_file} to dataframe: {e}'\n )\n sys.exit(1)\n\n def _clean_df(self):\n pass\n", "step-4": "import sys\nimport pandas as pd\nfrom components.helpers.Logger import Logger\n\n\nclass DataFrameCreatorBase:\n \"\"\"\n DataFrameCreatorBase\n \"\"\"\n START_DATE = '03/16/2020'\n\n def __init__(self, input_file):\n self._input_file = input_file\n self.df = self._read_raw_csv()\n self._clean_df()\n\n def __new__(cls, *args, **kwargs):\n if not hasattr(cls, 'instance'):\n cls.instance = super().__new__(cls)\n return cls.instance\n\n def _read_raw_csv(self):\n try:\n return pd.read_csv(f'files/input/{self._input_file}')\n except Exception as e:\n Logger.log_message(Logger.ERROR,\n f'Failed to convert csv file {self._input_file} to dataframe: {e}'\n )\n sys.exit(1)\n\n def _clean_df(self):\n pass\n", "step-5": "import sys\nimport pandas as pd\nfrom components.helpers.Logger import Logger\n\n\nclass DataFrameCreatorBase:\n \"\"\"\n DataFrameCreatorBase\n \"\"\"\n\n START_DATE = \"03/16/2020\"\n\n\n def __init__(self, input_file):\n self._input_file = input_file\n self.df = self._read_raw_csv()\n self._clean_df()\n\n def __new__(cls, *args, **kwargs):\n if not hasattr(cls, 'instance'):\n cls.instance = super().__new__(cls)\n return cls.instance\n\n\n def _read_raw_csv(self):\n try:\n return pd.read_csv(f'files/input/{self._input_file}')\n except Exception as e:\n Logger.log_message(\n Logger.ERROR,\n f\"Failed to convert csv file {self._input_file} to dataframe: {e}\"\n )\n sys.exit(1)\n\n\n def _clean_df(self):\n pass", "step-ids": [ 4, 6, 7, 8, 9 ] }
[ 4, 6, 7, 8, 9 ]
from PyQt5.QtWidgets import QPushButton,QWidget,QApplication,QGridLayout,QListWidget,QLineEdit,QVBoxLayout,QLabel import pyqtgraph as pg import sys import numpy as np from tools import DataModel,HoldPositions from load_sina import LoadNet import time from get_day_histroy import history import pandas as pd from volume import Volume from PyQt5.QtCore import QThread, pyqtSignal, QDateTime class addItemThread(QThread): update_qvix = pyqtSignal(pd.DataFrame) update_north = pyqtSignal(pd.DataFrame) update_vol = pyqtSignal(pd.Series,pd.Series) update_month = pyqtSignal(pd.DataFrame) update_iv =pyqtSignal(pd.DataFrame,pd.DataFrame) update_greek = pyqtSignal(list) def __init__(self,*args, **kwargs): super(addItemThread, self).__init__(*args, **kwargs) self.data_model =DataModel() self.num = 0 def run(self, *args, **kwargs): while True: df =LoadNet().get_QVIX() self.update_qvix.emit(df) df_north =LoadNet().get_north() self.update_north.emit(df_north) df_vol ,cha= Volume().update() data ,last = LoadNet().get_50_163() ser = (data['current']-last)/last self.update_vol.emit(df_vol,ser) if not self.data_model.df_op.empty: df_month = self.data_model.iv_month_50300() self.update_month.emit(df_month) df_iv50,df_iv300 = self.data_model.get_iv() self.update_iv.emit(df_iv50,df_iv300) hp = HoldPositions() greek = hp.update(self.data_model.df_op) self.update_greek.emit(greek) time.sleep(3) class Example(QWidget): def __init__(self): super(Example, self).__init__() mthread = addItemThread() mthread.update_qvix.connect(self.update_qvix) mthread.update_north.connect(self.update_north) mthread.update_vol.connect(self.update_volume) mthread.update_month.connect(self.update_month) mthread.update_iv.connect(self.update_iv) mthread.update_greek.connect(self.update_greek) mthread.start() self.initUI() def initUI(self): self.setGeometry(400,400,1200,620) self.setWindowTitle("不被仓位左右思想,没找到弱点不要重仓") self.gridLayout = QGridLayout(self) self.plot() ''' buttom ''' self.label_greek = QLabel('label_greek') self.label_greek.setStyleSheet("background-color:rgb(250,250,250)") self.gridLayout.addWidget(self.label_greek, 2, 0,1,3) ''' right ''' # wight_r = QWidget(self) # layout_r = QVBoxLayout() # wight_r.setLayout(layout_r) # btn_calculated = QPushButton('计算收益') # layout_r.addWidget(btn_calculated) # self.gridLayout.addWidget(wight_r, 0, 3,2,1) def plot(self): pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') pw_iv50 = pg.PlotWidget(title='50-IV') self.plt_iv50_1 = pw_iv50.plot(symbol="o",pen=pg.mkPen("r",width=1),symbolSize=12,symbolBrush=(0,255,0)) self.plt_iv50_2 = pw_iv50.plot(symbol="o",pen=pg.mkPen("g",width=1),symbolSize=12,symbolBrush=(0,255,0)) self.plt_iv50_3 = pw_iv50.plot(symbol="o",pen=pg.mkPen("r",width=1),symbolSize=10,symbolBrush=(0,170,0)) self.plt_iv50_4 = pw_iv50.plot(symbol="o",pen=pg.mkPen("g",width=1),symbolSize=10,symbolBrush=(0,170,0)) self.plt_iv50_5 = pw_iv50.plot(symbol="o",pen=pg.mkPen("r",width=1),symbolSize=8,symbolBrush=(0,85,0)) self.plt_iv50_6 = pw_iv50.plot(symbol="o",pen=pg.mkPen("g",width=1),symbolSize=8,symbolBrush=(0,85,0)) self.plt_iv50_7 = pw_iv50.plot(symbol="o",pen=pg.mkPen("r",width=1),symbolSize=6,symbolBrush=(0,0,0)) self.plt_iv50_8 = pw_iv50.plot(symbol="o",pen=pg.mkPen("g",width=1),symbolSize=6,symbolBrush=(0,0,0)) self.gridLayout.addWidget(pw_iv50, 0, 0) plt300 = pg.PlotWidget(title='300-IV') self.plt_iv300_1 = plt300.plot(symbol="o",pen=pg.mkPen("r",width=1),symbolSize=12,symbolBrush=(0,255,0)) self.plt_iv300_2 = plt300.plot(symbol="o",pen=pg.mkPen("g",width=1),symbolSize=12,symbolBrush=(0,255,0)) self.plt_iv300_3 = plt300.plot(symbol="o",pen=pg.mkPen("r",width=1),symbolSize=10,symbolBrush=(0,170,0)) self.plt_iv300_4 = plt300.plot(symbol="o",pen=pg.mkPen("g",width=1),symbolSize=10,symbolBrush=(0,170,0)) self.plt_iv300_5 = plt300.plot(symbol="o",pen=pg.mkPen("r",width=1),symbolSize=8,symbolBrush=(0,85,0)) self.plt_iv300_6 = plt300.plot(symbol="o",pen=pg.mkPen("g",width=1),symbolSize=8,symbolBrush=(0,85,0)) self.plt_iv300_7 = plt300.plot(symbol="o",pen=pg.mkPen("r",width=1),symbolSize=6,symbolBrush=(0,0,0)) self.plt_iv300_8 = plt300.plot(symbol="o",pen=pg.mkPen("g",width=1),symbolSize=6,symbolBrush=(0,0,0)) self.gridLayout.addWidget(plt300, 0, 1) pw_month = pg.PlotWidget(title='MONTH-50-300-MONTH') pw_month.showGrid(x=False,y=True) pw_month.addLegend(offset=(30, 100)) self.plt_month50 = pw_month.plot(name="50") self.plt_month300 = pw_month.plot(name="300") self.gridLayout.addWidget(pw_month, 0, 2) pw_qvix = pg.PlotWidget( title='QVIX') pw_qvix.showGrid(x=True,y=True) pw_qvix.addLegend() self.plt_qvix = pw_qvix.plot(pen=pg.mkPen("d",width=4),name="iv") self.gridLayout.addWidget(pw_qvix, 1, 0) pw_north = pg.PlotWidget( title='NORTH') pw_north.showGrid(x=False,y=True) pw_north.addLegend() self.plt_north_hgt =pw_north.plot(pen=pg.mkPen("b",width=2),name="hgt") self.plt_north_sgt =pw_north.plot(pen=pg.mkPen("g",width=1),name="sgt") self.plt_north_all =pw_north.plot(pen=pg.mkPen("d",width=1),name="all") self.gridLayout.addWidget(pw_north, 1, 1) pw_volume = pg.PlotWidget( title='VOLUME') pw_volume.showGrid(x=False,y=True) self.plt_volume =pw_volume.plot(name="volume") self.stock_50 =pw_volume.plot(name="stock_50") self.gridLayout.addWidget(pw_volume, 1, 2) def update_qvix(self,df): df = df.drop(['Pre','max','min'],axis=1) self.plt_qvix.setData(df.index.values, df['QVIX']) def update_north(self,df): self.plt_north_hgt.setData( df['hgt'].astype(float)/10000) self.plt_north_sgt.setData( df['sgt'].astype(float)/10000) self.plt_north_all.setData(df['all'].astype(float)/10000) def update_volume(self,data,ser): self.plt_volume.setPen(pg.mkPen("b",width=3)) self.plt_volume.setData(data.values) self.stock_50.setData(ser) def update_month(self,data): data.columns=['data','50iv','data2','300iv'] self.plt_month50.setData(data['50iv']) self.plt_month50.setPen(pg.mkPen("r",width=2)) self.plt_month300.setData(data['300iv']) self.plt_month300.setPen(pg.mkPen("b",width=1)) def update_iv(self,data50,data300): data50.sort_index(inplace=True) data50 = data50.astype(float) data50[data50<1]=np.nan self.plt_iv50_1.setData(data50.iloc[:,0]) self.plt_iv50_2.setData(data50.iloc[:,5]) self.plt_iv50_3.setData(data50.iloc[:,1]) self.plt_iv50_4.setData(data50.iloc[:,6]) self.plt_iv50_5.setData(data50.iloc[:,2]) self.plt_iv50_6.setData(data50.iloc[:,7]) self.plt_iv50_7.setData(data50.iloc[:,3]) self.plt_iv50_8.setData(data50.iloc[:,8]) data300.sort_index(inplace=True) data300 = data300.astype(float) data300[data300<1]=np.nan self.plt_iv300_1.setData(data300.iloc[:,0]) self.plt_iv300_2.setData(data300.iloc[:,5]) self.plt_iv300_3.setData(data300.iloc[:,1]) self.plt_iv300_4.setData(data300.iloc[:,6]) self.plt_iv300_5.setData(data300.iloc[:,2]) self.plt_iv300_6.setData(data300.iloc[:,7]) self.plt_iv300_7.setData(data300.iloc[:,3]) self.plt_iv300_8.setData(data300.iloc[:,8]) def update_greek(self,gk): text = 'DELTA:{}GAMMA:{}VEGA:{}THETA:{}'.format(gk[0],gk[1],gk[2],gk[3]) self.label_greek.setText(text) if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() ex.show() sys.exit(app.exec_())
normal
{ "blob_id": "8ddb7abb480ea8ee674c59719c0946f133ef0a4b", "index": 1303, "step-1": "<mask token>\n\n\nclass addItemThread(QThread):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Example(QWidget):\n\n def __init__(self):\n super(Example, self).__init__()\n mthread = addItemThread()\n mthread.update_qvix.connect(self.update_qvix)\n mthread.update_north.connect(self.update_north)\n mthread.update_vol.connect(self.update_volume)\n mthread.update_month.connect(self.update_month)\n mthread.update_iv.connect(self.update_iv)\n mthread.update_greek.connect(self.update_greek)\n mthread.start()\n self.initUI()\n\n def initUI(self):\n self.setGeometry(400, 400, 1200, 620)\n self.setWindowTitle('不被仓位左右思想,没找到弱点不要重仓')\n self.gridLayout = QGridLayout(self)\n self.plot()\n \"\"\"\n buttom\n \"\"\"\n self.label_greek = QLabel('label_greek')\n self.label_greek.setStyleSheet('background-color:rgb(250,250,250)')\n self.gridLayout.addWidget(self.label_greek, 2, 0, 1, 3)\n \"\"\"\n right\n \"\"\"\n\n def plot(self):\n pg.setConfigOption('background', 'w')\n pg.setConfigOption('foreground', 'k')\n pw_iv50 = pg.PlotWidget(title='50-IV')\n self.plt_iv50_1 = pw_iv50.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=12, symbolBrush=(0, 255, 0))\n self.plt_iv50_2 = pw_iv50.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=12, symbolBrush=(0, 255, 0))\n self.plt_iv50_3 = pw_iv50.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=10, symbolBrush=(0, 170, 0))\n self.plt_iv50_4 = pw_iv50.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=10, symbolBrush=(0, 170, 0))\n self.plt_iv50_5 = pw_iv50.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=8, symbolBrush=(0, 85, 0))\n self.plt_iv50_6 = pw_iv50.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=8, symbolBrush=(0, 85, 0))\n self.plt_iv50_7 = pw_iv50.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=6, symbolBrush=(0, 0, 0))\n self.plt_iv50_8 = pw_iv50.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=6, symbolBrush=(0, 0, 0))\n self.gridLayout.addWidget(pw_iv50, 0, 0)\n plt300 = pg.PlotWidget(title='300-IV')\n self.plt_iv300_1 = plt300.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=12, symbolBrush=(0, 255, 0))\n self.plt_iv300_2 = plt300.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=12, symbolBrush=(0, 255, 0))\n self.plt_iv300_3 = plt300.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=10, symbolBrush=(0, 170, 0))\n self.plt_iv300_4 = plt300.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=10, symbolBrush=(0, 170, 0))\n self.plt_iv300_5 = plt300.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=8, symbolBrush=(0, 85, 0))\n self.plt_iv300_6 = plt300.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=8, symbolBrush=(0, 85, 0))\n self.plt_iv300_7 = plt300.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=6, symbolBrush=(0, 0, 0))\n self.plt_iv300_8 = plt300.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=6, symbolBrush=(0, 0, 0))\n self.gridLayout.addWidget(plt300, 0, 1)\n pw_month = pg.PlotWidget(title='MONTH-50-300-MONTH')\n pw_month.showGrid(x=False, y=True)\n pw_month.addLegend(offset=(30, 100))\n self.plt_month50 = pw_month.plot(name='50')\n self.plt_month300 = pw_month.plot(name='300')\n self.gridLayout.addWidget(pw_month, 0, 2)\n pw_qvix = pg.PlotWidget(title='QVIX')\n pw_qvix.showGrid(x=True, y=True)\n pw_qvix.addLegend()\n self.plt_qvix = pw_qvix.plot(pen=pg.mkPen('d', width=4), name='iv')\n self.gridLayout.addWidget(pw_qvix, 1, 0)\n pw_north = pg.PlotWidget(title='NORTH')\n pw_north.showGrid(x=False, y=True)\n pw_north.addLegend()\n self.plt_north_hgt = pw_north.plot(pen=pg.mkPen('b', width=2), name\n ='hgt')\n self.plt_north_sgt = pw_north.plot(pen=pg.mkPen('g', width=1), name\n ='sgt')\n self.plt_north_all = pw_north.plot(pen=pg.mkPen('d', width=1), name\n ='all')\n self.gridLayout.addWidget(pw_north, 1, 1)\n pw_volume = pg.PlotWidget(title='VOLUME')\n pw_volume.showGrid(x=False, y=True)\n self.plt_volume = pw_volume.plot(name='volume')\n self.stock_50 = pw_volume.plot(name='stock_50')\n self.gridLayout.addWidget(pw_volume, 1, 2)\n\n def update_qvix(self, df):\n df = df.drop(['Pre', 'max', 'min'], axis=1)\n self.plt_qvix.setData(df.index.values, df['QVIX'])\n\n def update_north(self, df):\n self.plt_north_hgt.setData(df['hgt'].astype(float) / 10000)\n self.plt_north_sgt.setData(df['sgt'].astype(float) / 10000)\n self.plt_north_all.setData(df['all'].astype(float) / 10000)\n\n def update_volume(self, data, ser):\n self.plt_volume.setPen(pg.mkPen('b', width=3))\n self.plt_volume.setData(data.values)\n self.stock_50.setData(ser)\n\n def update_month(self, data):\n data.columns = ['data', '50iv', 'data2', '300iv']\n self.plt_month50.setData(data['50iv'])\n self.plt_month50.setPen(pg.mkPen('r', width=2))\n self.plt_month300.setData(data['300iv'])\n self.plt_month300.setPen(pg.mkPen('b', width=1))\n\n def update_iv(self, data50, data300):\n data50.sort_index(inplace=True)\n data50 = data50.astype(float)\n data50[data50 < 1] = np.nan\n self.plt_iv50_1.setData(data50.iloc[:, 0])\n self.plt_iv50_2.setData(data50.iloc[:, 5])\n self.plt_iv50_3.setData(data50.iloc[:, 1])\n self.plt_iv50_4.setData(data50.iloc[:, 6])\n self.plt_iv50_5.setData(data50.iloc[:, 2])\n self.plt_iv50_6.setData(data50.iloc[:, 7])\n self.plt_iv50_7.setData(data50.iloc[:, 3])\n self.plt_iv50_8.setData(data50.iloc[:, 8])\n data300.sort_index(inplace=True)\n data300 = data300.astype(float)\n data300[data300 < 1] = np.nan\n self.plt_iv300_1.setData(data300.iloc[:, 0])\n self.plt_iv300_2.setData(data300.iloc[:, 5])\n self.plt_iv300_3.setData(data300.iloc[:, 1])\n self.plt_iv300_4.setData(data300.iloc[:, 6])\n self.plt_iv300_5.setData(data300.iloc[:, 2])\n self.plt_iv300_6.setData(data300.iloc[:, 7])\n self.plt_iv300_7.setData(data300.iloc[:, 3])\n self.plt_iv300_8.setData(data300.iloc[:, 8])\n\n def update_greek(self, gk):\n text = 'DELTA:{}GAMMA:{}VEGA:{}THETA:{}'.format(gk[0], gk[1], gk[2],\n gk[3])\n self.label_greek.setText(text)\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass addItemThread(QThread):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, *args, **kwargs):\n super(addItemThread, self).__init__(*args, **kwargs)\n self.data_model = DataModel()\n self.num = 0\n <mask token>\n\n\nclass Example(QWidget):\n\n def __init__(self):\n super(Example, self).__init__()\n mthread = addItemThread()\n mthread.update_qvix.connect(self.update_qvix)\n mthread.update_north.connect(self.update_north)\n mthread.update_vol.connect(self.update_volume)\n mthread.update_month.connect(self.update_month)\n mthread.update_iv.connect(self.update_iv)\n mthread.update_greek.connect(self.update_greek)\n mthread.start()\n self.initUI()\n\n def initUI(self):\n self.setGeometry(400, 400, 1200, 620)\n self.setWindowTitle('不被仓位左右思想,没找到弱点不要重仓')\n self.gridLayout = QGridLayout(self)\n self.plot()\n \"\"\"\n buttom\n \"\"\"\n self.label_greek = QLabel('label_greek')\n self.label_greek.setStyleSheet('background-color:rgb(250,250,250)')\n self.gridLayout.addWidget(self.label_greek, 2, 0, 1, 3)\n \"\"\"\n right\n \"\"\"\n\n def plot(self):\n pg.setConfigOption('background', 'w')\n pg.setConfigOption('foreground', 'k')\n pw_iv50 = pg.PlotWidget(title='50-IV')\n self.plt_iv50_1 = pw_iv50.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=12, symbolBrush=(0, 255, 0))\n self.plt_iv50_2 = pw_iv50.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=12, symbolBrush=(0, 255, 0))\n self.plt_iv50_3 = pw_iv50.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=10, symbolBrush=(0, 170, 0))\n self.plt_iv50_4 = pw_iv50.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=10, symbolBrush=(0, 170, 0))\n self.plt_iv50_5 = pw_iv50.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=8, symbolBrush=(0, 85, 0))\n self.plt_iv50_6 = pw_iv50.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=8, symbolBrush=(0, 85, 0))\n self.plt_iv50_7 = pw_iv50.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=6, symbolBrush=(0, 0, 0))\n self.plt_iv50_8 = pw_iv50.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=6, symbolBrush=(0, 0, 0))\n self.gridLayout.addWidget(pw_iv50, 0, 0)\n plt300 = pg.PlotWidget(title='300-IV')\n self.plt_iv300_1 = plt300.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=12, symbolBrush=(0, 255, 0))\n self.plt_iv300_2 = plt300.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=12, symbolBrush=(0, 255, 0))\n self.plt_iv300_3 = plt300.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=10, symbolBrush=(0, 170, 0))\n self.plt_iv300_4 = plt300.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=10, symbolBrush=(0, 170, 0))\n self.plt_iv300_5 = plt300.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=8, symbolBrush=(0, 85, 0))\n self.plt_iv300_6 = plt300.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=8, symbolBrush=(0, 85, 0))\n self.plt_iv300_7 = plt300.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=6, symbolBrush=(0, 0, 0))\n self.plt_iv300_8 = plt300.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=6, symbolBrush=(0, 0, 0))\n self.gridLayout.addWidget(plt300, 0, 1)\n pw_month = pg.PlotWidget(title='MONTH-50-300-MONTH')\n pw_month.showGrid(x=False, y=True)\n pw_month.addLegend(offset=(30, 100))\n self.plt_month50 = pw_month.plot(name='50')\n self.plt_month300 = pw_month.plot(name='300')\n self.gridLayout.addWidget(pw_month, 0, 2)\n pw_qvix = pg.PlotWidget(title='QVIX')\n pw_qvix.showGrid(x=True, y=True)\n pw_qvix.addLegend()\n self.plt_qvix = pw_qvix.plot(pen=pg.mkPen('d', width=4), name='iv')\n self.gridLayout.addWidget(pw_qvix, 1, 0)\n pw_north = pg.PlotWidget(title='NORTH')\n pw_north.showGrid(x=False, y=True)\n pw_north.addLegend()\n self.plt_north_hgt = pw_north.plot(pen=pg.mkPen('b', width=2), name\n ='hgt')\n self.plt_north_sgt = pw_north.plot(pen=pg.mkPen('g', width=1), name\n ='sgt')\n self.plt_north_all = pw_north.plot(pen=pg.mkPen('d', width=1), name\n ='all')\n self.gridLayout.addWidget(pw_north, 1, 1)\n pw_volume = pg.PlotWidget(title='VOLUME')\n pw_volume.showGrid(x=False, y=True)\n self.plt_volume = pw_volume.plot(name='volume')\n self.stock_50 = pw_volume.plot(name='stock_50')\n self.gridLayout.addWidget(pw_volume, 1, 2)\n\n def update_qvix(self, df):\n df = df.drop(['Pre', 'max', 'min'], axis=1)\n self.plt_qvix.setData(df.index.values, df['QVIX'])\n\n def update_north(self, df):\n self.plt_north_hgt.setData(df['hgt'].astype(float) / 10000)\n self.plt_north_sgt.setData(df['sgt'].astype(float) / 10000)\n self.plt_north_all.setData(df['all'].astype(float) / 10000)\n\n def update_volume(self, data, ser):\n self.plt_volume.setPen(pg.mkPen('b', width=3))\n self.plt_volume.setData(data.values)\n self.stock_50.setData(ser)\n\n def update_month(self, data):\n data.columns = ['data', '50iv', 'data2', '300iv']\n self.plt_month50.setData(data['50iv'])\n self.plt_month50.setPen(pg.mkPen('r', width=2))\n self.plt_month300.setData(data['300iv'])\n self.plt_month300.setPen(pg.mkPen('b', width=1))\n\n def update_iv(self, data50, data300):\n data50.sort_index(inplace=True)\n data50 = data50.astype(float)\n data50[data50 < 1] = np.nan\n self.plt_iv50_1.setData(data50.iloc[:, 0])\n self.plt_iv50_2.setData(data50.iloc[:, 5])\n self.plt_iv50_3.setData(data50.iloc[:, 1])\n self.plt_iv50_4.setData(data50.iloc[:, 6])\n self.plt_iv50_5.setData(data50.iloc[:, 2])\n self.plt_iv50_6.setData(data50.iloc[:, 7])\n self.plt_iv50_7.setData(data50.iloc[:, 3])\n self.plt_iv50_8.setData(data50.iloc[:, 8])\n data300.sort_index(inplace=True)\n data300 = data300.astype(float)\n data300[data300 < 1] = np.nan\n self.plt_iv300_1.setData(data300.iloc[:, 0])\n self.plt_iv300_2.setData(data300.iloc[:, 5])\n self.plt_iv300_3.setData(data300.iloc[:, 1])\n self.plt_iv300_4.setData(data300.iloc[:, 6])\n self.plt_iv300_5.setData(data300.iloc[:, 2])\n self.plt_iv300_6.setData(data300.iloc[:, 7])\n self.plt_iv300_7.setData(data300.iloc[:, 3])\n self.plt_iv300_8.setData(data300.iloc[:, 8])\n\n def update_greek(self, gk):\n text = 'DELTA:{}GAMMA:{}VEGA:{}THETA:{}'.format(gk[0], gk[1], gk[2],\n gk[3])\n self.label_greek.setText(text)\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\nclass addItemThread(QThread):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __init__(self, *args, **kwargs):\n super(addItemThread, self).__init__(*args, **kwargs)\n self.data_model = DataModel()\n self.num = 0\n\n def run(self, *args, **kwargs):\n while True:\n df = LoadNet().get_QVIX()\n self.update_qvix.emit(df)\n df_north = LoadNet().get_north()\n self.update_north.emit(df_north)\n df_vol, cha = Volume().update()\n data, last = LoadNet().get_50_163()\n ser = (data['current'] - last) / last\n self.update_vol.emit(df_vol, ser)\n if not self.data_model.df_op.empty:\n df_month = self.data_model.iv_month_50300()\n self.update_month.emit(df_month)\n df_iv50, df_iv300 = self.data_model.get_iv()\n self.update_iv.emit(df_iv50, df_iv300)\n hp = HoldPositions()\n greek = hp.update(self.data_model.df_op)\n self.update_greek.emit(greek)\n time.sleep(3)\n\n\nclass Example(QWidget):\n\n def __init__(self):\n super(Example, self).__init__()\n mthread = addItemThread()\n mthread.update_qvix.connect(self.update_qvix)\n mthread.update_north.connect(self.update_north)\n mthread.update_vol.connect(self.update_volume)\n mthread.update_month.connect(self.update_month)\n mthread.update_iv.connect(self.update_iv)\n mthread.update_greek.connect(self.update_greek)\n mthread.start()\n self.initUI()\n\n def initUI(self):\n self.setGeometry(400, 400, 1200, 620)\n self.setWindowTitle('不被仓位左右思想,没找到弱点不要重仓')\n self.gridLayout = QGridLayout(self)\n self.plot()\n \"\"\"\n buttom\n \"\"\"\n self.label_greek = QLabel('label_greek')\n self.label_greek.setStyleSheet('background-color:rgb(250,250,250)')\n self.gridLayout.addWidget(self.label_greek, 2, 0, 1, 3)\n \"\"\"\n right\n \"\"\"\n\n def plot(self):\n pg.setConfigOption('background', 'w')\n pg.setConfigOption('foreground', 'k')\n pw_iv50 = pg.PlotWidget(title='50-IV')\n self.plt_iv50_1 = pw_iv50.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=12, symbolBrush=(0, 255, 0))\n self.plt_iv50_2 = pw_iv50.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=12, symbolBrush=(0, 255, 0))\n self.plt_iv50_3 = pw_iv50.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=10, symbolBrush=(0, 170, 0))\n self.plt_iv50_4 = pw_iv50.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=10, symbolBrush=(0, 170, 0))\n self.plt_iv50_5 = pw_iv50.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=8, symbolBrush=(0, 85, 0))\n self.plt_iv50_6 = pw_iv50.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=8, symbolBrush=(0, 85, 0))\n self.plt_iv50_7 = pw_iv50.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=6, symbolBrush=(0, 0, 0))\n self.plt_iv50_8 = pw_iv50.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=6, symbolBrush=(0, 0, 0))\n self.gridLayout.addWidget(pw_iv50, 0, 0)\n plt300 = pg.PlotWidget(title='300-IV')\n self.plt_iv300_1 = plt300.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=12, symbolBrush=(0, 255, 0))\n self.plt_iv300_2 = plt300.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=12, symbolBrush=(0, 255, 0))\n self.plt_iv300_3 = plt300.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=10, symbolBrush=(0, 170, 0))\n self.plt_iv300_4 = plt300.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=10, symbolBrush=(0, 170, 0))\n self.plt_iv300_5 = plt300.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=8, symbolBrush=(0, 85, 0))\n self.plt_iv300_6 = plt300.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=8, symbolBrush=(0, 85, 0))\n self.plt_iv300_7 = plt300.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=6, symbolBrush=(0, 0, 0))\n self.plt_iv300_8 = plt300.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=6, symbolBrush=(0, 0, 0))\n self.gridLayout.addWidget(plt300, 0, 1)\n pw_month = pg.PlotWidget(title='MONTH-50-300-MONTH')\n pw_month.showGrid(x=False, y=True)\n pw_month.addLegend(offset=(30, 100))\n self.plt_month50 = pw_month.plot(name='50')\n self.plt_month300 = pw_month.plot(name='300')\n self.gridLayout.addWidget(pw_month, 0, 2)\n pw_qvix = pg.PlotWidget(title='QVIX')\n pw_qvix.showGrid(x=True, y=True)\n pw_qvix.addLegend()\n self.plt_qvix = pw_qvix.plot(pen=pg.mkPen('d', width=4), name='iv')\n self.gridLayout.addWidget(pw_qvix, 1, 0)\n pw_north = pg.PlotWidget(title='NORTH')\n pw_north.showGrid(x=False, y=True)\n pw_north.addLegend()\n self.plt_north_hgt = pw_north.plot(pen=pg.mkPen('b', width=2), name\n ='hgt')\n self.plt_north_sgt = pw_north.plot(pen=pg.mkPen('g', width=1), name\n ='sgt')\n self.plt_north_all = pw_north.plot(pen=pg.mkPen('d', width=1), name\n ='all')\n self.gridLayout.addWidget(pw_north, 1, 1)\n pw_volume = pg.PlotWidget(title='VOLUME')\n pw_volume.showGrid(x=False, y=True)\n self.plt_volume = pw_volume.plot(name='volume')\n self.stock_50 = pw_volume.plot(name='stock_50')\n self.gridLayout.addWidget(pw_volume, 1, 2)\n\n def update_qvix(self, df):\n df = df.drop(['Pre', 'max', 'min'], axis=1)\n self.plt_qvix.setData(df.index.values, df['QVIX'])\n\n def update_north(self, df):\n self.plt_north_hgt.setData(df['hgt'].astype(float) / 10000)\n self.plt_north_sgt.setData(df['sgt'].astype(float) / 10000)\n self.plt_north_all.setData(df['all'].astype(float) / 10000)\n\n def update_volume(self, data, ser):\n self.plt_volume.setPen(pg.mkPen('b', width=3))\n self.plt_volume.setData(data.values)\n self.stock_50.setData(ser)\n\n def update_month(self, data):\n data.columns = ['data', '50iv', 'data2', '300iv']\n self.plt_month50.setData(data['50iv'])\n self.plt_month50.setPen(pg.mkPen('r', width=2))\n self.plt_month300.setData(data['300iv'])\n self.plt_month300.setPen(pg.mkPen('b', width=1))\n\n def update_iv(self, data50, data300):\n data50.sort_index(inplace=True)\n data50 = data50.astype(float)\n data50[data50 < 1] = np.nan\n self.plt_iv50_1.setData(data50.iloc[:, 0])\n self.plt_iv50_2.setData(data50.iloc[:, 5])\n self.plt_iv50_3.setData(data50.iloc[:, 1])\n self.plt_iv50_4.setData(data50.iloc[:, 6])\n self.plt_iv50_5.setData(data50.iloc[:, 2])\n self.plt_iv50_6.setData(data50.iloc[:, 7])\n self.plt_iv50_7.setData(data50.iloc[:, 3])\n self.plt_iv50_8.setData(data50.iloc[:, 8])\n data300.sort_index(inplace=True)\n data300 = data300.astype(float)\n data300[data300 < 1] = np.nan\n self.plt_iv300_1.setData(data300.iloc[:, 0])\n self.plt_iv300_2.setData(data300.iloc[:, 5])\n self.plt_iv300_3.setData(data300.iloc[:, 1])\n self.plt_iv300_4.setData(data300.iloc[:, 6])\n self.plt_iv300_5.setData(data300.iloc[:, 2])\n self.plt_iv300_6.setData(data300.iloc[:, 7])\n self.plt_iv300_7.setData(data300.iloc[:, 3])\n self.plt_iv300_8.setData(data300.iloc[:, 8])\n\n def update_greek(self, gk):\n text = 'DELTA:{}GAMMA:{}VEGA:{}THETA:{}'.format(gk[0], gk[1], gk[2],\n gk[3])\n self.label_greek.setText(text)\n\n\n<mask token>\n", "step-4": "<mask token>\n\n\nclass addItemThread(QThread):\n update_qvix = pyqtSignal(pd.DataFrame)\n update_north = pyqtSignal(pd.DataFrame)\n update_vol = pyqtSignal(pd.Series, pd.Series)\n update_month = pyqtSignal(pd.DataFrame)\n update_iv = pyqtSignal(pd.DataFrame, pd.DataFrame)\n update_greek = pyqtSignal(list)\n\n def __init__(self, *args, **kwargs):\n super(addItemThread, self).__init__(*args, **kwargs)\n self.data_model = DataModel()\n self.num = 0\n\n def run(self, *args, **kwargs):\n while True:\n df = LoadNet().get_QVIX()\n self.update_qvix.emit(df)\n df_north = LoadNet().get_north()\n self.update_north.emit(df_north)\n df_vol, cha = Volume().update()\n data, last = LoadNet().get_50_163()\n ser = (data['current'] - last) / last\n self.update_vol.emit(df_vol, ser)\n if not self.data_model.df_op.empty:\n df_month = self.data_model.iv_month_50300()\n self.update_month.emit(df_month)\n df_iv50, df_iv300 = self.data_model.get_iv()\n self.update_iv.emit(df_iv50, df_iv300)\n hp = HoldPositions()\n greek = hp.update(self.data_model.df_op)\n self.update_greek.emit(greek)\n time.sleep(3)\n\n\nclass Example(QWidget):\n\n def __init__(self):\n super(Example, self).__init__()\n mthread = addItemThread()\n mthread.update_qvix.connect(self.update_qvix)\n mthread.update_north.connect(self.update_north)\n mthread.update_vol.connect(self.update_volume)\n mthread.update_month.connect(self.update_month)\n mthread.update_iv.connect(self.update_iv)\n mthread.update_greek.connect(self.update_greek)\n mthread.start()\n self.initUI()\n\n def initUI(self):\n self.setGeometry(400, 400, 1200, 620)\n self.setWindowTitle('不被仓位左右思想,没找到弱点不要重仓')\n self.gridLayout = QGridLayout(self)\n self.plot()\n \"\"\"\n buttom\n \"\"\"\n self.label_greek = QLabel('label_greek')\n self.label_greek.setStyleSheet('background-color:rgb(250,250,250)')\n self.gridLayout.addWidget(self.label_greek, 2, 0, 1, 3)\n \"\"\"\n right\n \"\"\"\n\n def plot(self):\n pg.setConfigOption('background', 'w')\n pg.setConfigOption('foreground', 'k')\n pw_iv50 = pg.PlotWidget(title='50-IV')\n self.plt_iv50_1 = pw_iv50.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=12, symbolBrush=(0, 255, 0))\n self.plt_iv50_2 = pw_iv50.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=12, symbolBrush=(0, 255, 0))\n self.plt_iv50_3 = pw_iv50.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=10, symbolBrush=(0, 170, 0))\n self.plt_iv50_4 = pw_iv50.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=10, symbolBrush=(0, 170, 0))\n self.plt_iv50_5 = pw_iv50.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=8, symbolBrush=(0, 85, 0))\n self.plt_iv50_6 = pw_iv50.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=8, symbolBrush=(0, 85, 0))\n self.plt_iv50_7 = pw_iv50.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=6, symbolBrush=(0, 0, 0))\n self.plt_iv50_8 = pw_iv50.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=6, symbolBrush=(0, 0, 0))\n self.gridLayout.addWidget(pw_iv50, 0, 0)\n plt300 = pg.PlotWidget(title='300-IV')\n self.plt_iv300_1 = plt300.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=12, symbolBrush=(0, 255, 0))\n self.plt_iv300_2 = plt300.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=12, symbolBrush=(0, 255, 0))\n self.plt_iv300_3 = plt300.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=10, symbolBrush=(0, 170, 0))\n self.plt_iv300_4 = plt300.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=10, symbolBrush=(0, 170, 0))\n self.plt_iv300_5 = plt300.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=8, symbolBrush=(0, 85, 0))\n self.plt_iv300_6 = plt300.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=8, symbolBrush=(0, 85, 0))\n self.plt_iv300_7 = plt300.plot(symbol='o', pen=pg.mkPen('r', width=\n 1), symbolSize=6, symbolBrush=(0, 0, 0))\n self.plt_iv300_8 = plt300.plot(symbol='o', pen=pg.mkPen('g', width=\n 1), symbolSize=6, symbolBrush=(0, 0, 0))\n self.gridLayout.addWidget(plt300, 0, 1)\n pw_month = pg.PlotWidget(title='MONTH-50-300-MONTH')\n pw_month.showGrid(x=False, y=True)\n pw_month.addLegend(offset=(30, 100))\n self.plt_month50 = pw_month.plot(name='50')\n self.plt_month300 = pw_month.plot(name='300')\n self.gridLayout.addWidget(pw_month, 0, 2)\n pw_qvix = pg.PlotWidget(title='QVIX')\n pw_qvix.showGrid(x=True, y=True)\n pw_qvix.addLegend()\n self.plt_qvix = pw_qvix.plot(pen=pg.mkPen('d', width=4), name='iv')\n self.gridLayout.addWidget(pw_qvix, 1, 0)\n pw_north = pg.PlotWidget(title='NORTH')\n pw_north.showGrid(x=False, y=True)\n pw_north.addLegend()\n self.plt_north_hgt = pw_north.plot(pen=pg.mkPen('b', width=2), name\n ='hgt')\n self.plt_north_sgt = pw_north.plot(pen=pg.mkPen('g', width=1), name\n ='sgt')\n self.plt_north_all = pw_north.plot(pen=pg.mkPen('d', width=1), name\n ='all')\n self.gridLayout.addWidget(pw_north, 1, 1)\n pw_volume = pg.PlotWidget(title='VOLUME')\n pw_volume.showGrid(x=False, y=True)\n self.plt_volume = pw_volume.plot(name='volume')\n self.stock_50 = pw_volume.plot(name='stock_50')\n self.gridLayout.addWidget(pw_volume, 1, 2)\n\n def update_qvix(self, df):\n df = df.drop(['Pre', 'max', 'min'], axis=1)\n self.plt_qvix.setData(df.index.values, df['QVIX'])\n\n def update_north(self, df):\n self.plt_north_hgt.setData(df['hgt'].astype(float) / 10000)\n self.plt_north_sgt.setData(df['sgt'].astype(float) / 10000)\n self.plt_north_all.setData(df['all'].astype(float) / 10000)\n\n def update_volume(self, data, ser):\n self.plt_volume.setPen(pg.mkPen('b', width=3))\n self.plt_volume.setData(data.values)\n self.stock_50.setData(ser)\n\n def update_month(self, data):\n data.columns = ['data', '50iv', 'data2', '300iv']\n self.plt_month50.setData(data['50iv'])\n self.plt_month50.setPen(pg.mkPen('r', width=2))\n self.plt_month300.setData(data['300iv'])\n self.plt_month300.setPen(pg.mkPen('b', width=1))\n\n def update_iv(self, data50, data300):\n data50.sort_index(inplace=True)\n data50 = data50.astype(float)\n data50[data50 < 1] = np.nan\n self.plt_iv50_1.setData(data50.iloc[:, 0])\n self.plt_iv50_2.setData(data50.iloc[:, 5])\n self.plt_iv50_3.setData(data50.iloc[:, 1])\n self.plt_iv50_4.setData(data50.iloc[:, 6])\n self.plt_iv50_5.setData(data50.iloc[:, 2])\n self.plt_iv50_6.setData(data50.iloc[:, 7])\n self.plt_iv50_7.setData(data50.iloc[:, 3])\n self.plt_iv50_8.setData(data50.iloc[:, 8])\n data300.sort_index(inplace=True)\n data300 = data300.astype(float)\n data300[data300 < 1] = np.nan\n self.plt_iv300_1.setData(data300.iloc[:, 0])\n self.plt_iv300_2.setData(data300.iloc[:, 5])\n self.plt_iv300_3.setData(data300.iloc[:, 1])\n self.plt_iv300_4.setData(data300.iloc[:, 6])\n self.plt_iv300_5.setData(data300.iloc[:, 2])\n self.plt_iv300_6.setData(data300.iloc[:, 7])\n self.plt_iv300_7.setData(data300.iloc[:, 3])\n self.plt_iv300_8.setData(data300.iloc[:, 8])\n\n def update_greek(self, gk):\n text = 'DELTA:{}GAMMA:{}VEGA:{}THETA:{}'.format(gk[0], gk[1], gk[2],\n gk[3])\n self.label_greek.setText(text)\n\n\n<mask token>\n", "step-5": "from PyQt5.QtWidgets import QPushButton,QWidget,QApplication,QGridLayout,QListWidget,QLineEdit,QVBoxLayout,QLabel\nimport pyqtgraph as pg\nimport sys\nimport numpy as np\nfrom tools import DataModel,HoldPositions\nfrom load_sina import LoadNet\nimport time\nfrom get_day_histroy import history\nimport pandas as pd \nfrom volume import Volume\nfrom PyQt5.QtCore import QThread, pyqtSignal, QDateTime\n\nclass addItemThread(QThread):\n update_qvix = pyqtSignal(pd.DataFrame)\n update_north = pyqtSignal(pd.DataFrame)\n update_vol = pyqtSignal(pd.Series,pd.Series)\n update_month = pyqtSignal(pd.DataFrame)\n update_iv =pyqtSignal(pd.DataFrame,pd.DataFrame)\n update_greek = pyqtSignal(list)\n \n def __init__(self,*args, **kwargs):\n super(addItemThread, self).__init__(*args, **kwargs)\n self.data_model =DataModel()\n self.num = 0\n \n def run(self, *args, **kwargs):\n while True:\n df =LoadNet().get_QVIX()\n self.update_qvix.emit(df)\n\n df_north =LoadNet().get_north()\n self.update_north.emit(df_north)\n\n df_vol ,cha= Volume().update()\n data ,last = LoadNet().get_50_163()\n ser = (data['current']-last)/last\n self.update_vol.emit(df_vol,ser)\n \n if not self.data_model.df_op.empty:\n df_month = self.data_model.iv_month_50300()\n self.update_month.emit(df_month)\n\n df_iv50,df_iv300 = self.data_model.get_iv()\n self.update_iv.emit(df_iv50,df_iv300)\n\n hp = HoldPositions()\n greek = hp.update(self.data_model.df_op)\n self.update_greek.emit(greek)\n\n time.sleep(3)\n\n\nclass Example(QWidget):\n def __init__(self):\n super(Example, self).__init__()\n mthread = addItemThread()\n mthread.update_qvix.connect(self.update_qvix)\n mthread.update_north.connect(self.update_north)\n mthread.update_vol.connect(self.update_volume)\n mthread.update_month.connect(self.update_month)\n mthread.update_iv.connect(self.update_iv)\n mthread.update_greek.connect(self.update_greek)\n mthread.start()\n self.initUI()\n \n\n def initUI(self):\n self.setGeometry(400,400,1200,620)\n self.setWindowTitle(\"不被仓位左右思想,没找到弱点不要重仓\")\n self.gridLayout = QGridLayout(self)\n self.plot()\n \n '''\n buttom\n '''\n self.label_greek = QLabel('label_greek')\n self.label_greek.setStyleSheet(\"background-color:rgb(250,250,250)\")\n self.gridLayout.addWidget(self.label_greek, 2, 0,1,3)\n '''\n right\n '''\n # wight_r = QWidget(self)\n # layout_r = QVBoxLayout()\n # wight_r.setLayout(layout_r)\n # btn_calculated = QPushButton('计算收益')\n # layout_r.addWidget(btn_calculated)\n # self.gridLayout.addWidget(wight_r, 0, 3,2,1)\n\n def plot(self):\n pg.setConfigOption('background', 'w')\n pg.setConfigOption('foreground', 'k')\n\n pw_iv50 = pg.PlotWidget(title='50-IV')\n self.plt_iv50_1 = pw_iv50.plot(symbol=\"o\",pen=pg.mkPen(\"r\",width=1),symbolSize=12,symbolBrush=(0,255,0))\n self.plt_iv50_2 = pw_iv50.plot(symbol=\"o\",pen=pg.mkPen(\"g\",width=1),symbolSize=12,symbolBrush=(0,255,0))\n self.plt_iv50_3 = pw_iv50.plot(symbol=\"o\",pen=pg.mkPen(\"r\",width=1),symbolSize=10,symbolBrush=(0,170,0))\n self.plt_iv50_4 = pw_iv50.plot(symbol=\"o\",pen=pg.mkPen(\"g\",width=1),symbolSize=10,symbolBrush=(0,170,0))\n self.plt_iv50_5 = pw_iv50.plot(symbol=\"o\",pen=pg.mkPen(\"r\",width=1),symbolSize=8,symbolBrush=(0,85,0))\n self.plt_iv50_6 = pw_iv50.plot(symbol=\"o\",pen=pg.mkPen(\"g\",width=1),symbolSize=8,symbolBrush=(0,85,0))\n self.plt_iv50_7 = pw_iv50.plot(symbol=\"o\",pen=pg.mkPen(\"r\",width=1),symbolSize=6,symbolBrush=(0,0,0))\n self.plt_iv50_8 = pw_iv50.plot(symbol=\"o\",pen=pg.mkPen(\"g\",width=1),symbolSize=6,symbolBrush=(0,0,0))\n self.gridLayout.addWidget(pw_iv50, 0, 0)\n \n\n plt300 = pg.PlotWidget(title='300-IV')\n self.plt_iv300_1 = plt300.plot(symbol=\"o\",pen=pg.mkPen(\"r\",width=1),symbolSize=12,symbolBrush=(0,255,0))\n self.plt_iv300_2 = plt300.plot(symbol=\"o\",pen=pg.mkPen(\"g\",width=1),symbolSize=12,symbolBrush=(0,255,0))\n self.plt_iv300_3 = plt300.plot(symbol=\"o\",pen=pg.mkPen(\"r\",width=1),symbolSize=10,symbolBrush=(0,170,0))\n self.plt_iv300_4 = plt300.plot(symbol=\"o\",pen=pg.mkPen(\"g\",width=1),symbolSize=10,symbolBrush=(0,170,0))\n self.plt_iv300_5 = plt300.plot(symbol=\"o\",pen=pg.mkPen(\"r\",width=1),symbolSize=8,symbolBrush=(0,85,0))\n self.plt_iv300_6 = plt300.plot(symbol=\"o\",pen=pg.mkPen(\"g\",width=1),symbolSize=8,symbolBrush=(0,85,0))\n self.plt_iv300_7 = plt300.plot(symbol=\"o\",pen=pg.mkPen(\"r\",width=1),symbolSize=6,symbolBrush=(0,0,0))\n self.plt_iv300_8 = plt300.plot(symbol=\"o\",pen=pg.mkPen(\"g\",width=1),symbolSize=6,symbolBrush=(0,0,0))\n self.gridLayout.addWidget(plt300, 0, 1)\n\n pw_month = pg.PlotWidget(title='MONTH-50-300-MONTH')\n pw_month.showGrid(x=False,y=True)\n pw_month.addLegend(offset=(30, 100))\n self.plt_month50 = pw_month.plot(name=\"50\")\n self.plt_month300 = pw_month.plot(name=\"300\")\n self.gridLayout.addWidget(pw_month, 0, 2)\n\n pw_qvix = pg.PlotWidget( title='QVIX')\n pw_qvix.showGrid(x=True,y=True)\n pw_qvix.addLegend()\n self.plt_qvix = pw_qvix.plot(pen=pg.mkPen(\"d\",width=4),name=\"iv\")\n self.gridLayout.addWidget(pw_qvix, 1, 0)\n\n pw_north = pg.PlotWidget( title='NORTH')\n pw_north.showGrid(x=False,y=True)\n pw_north.addLegend()\n self.plt_north_hgt =pw_north.plot(pen=pg.mkPen(\"b\",width=2),name=\"hgt\")\n self.plt_north_sgt =pw_north.plot(pen=pg.mkPen(\"g\",width=1),name=\"sgt\")\n self.plt_north_all =pw_north.plot(pen=pg.mkPen(\"d\",width=1),name=\"all\")\n self.gridLayout.addWidget(pw_north, 1, 1)\n\n pw_volume = pg.PlotWidget( title='VOLUME')\n pw_volume.showGrid(x=False,y=True)\n self.plt_volume =pw_volume.plot(name=\"volume\")\n self.stock_50 =pw_volume.plot(name=\"stock_50\")\n self.gridLayout.addWidget(pw_volume, 1, 2)\n\n def update_qvix(self,df):\n df = df.drop(['Pre','max','min'],axis=1)\n self.plt_qvix.setData(df.index.values, df['QVIX'])\n\n def update_north(self,df):\n self.plt_north_hgt.setData( df['hgt'].astype(float)/10000)\n self.plt_north_sgt.setData( df['sgt'].astype(float)/10000)\n self.plt_north_all.setData(df['all'].astype(float)/10000)\n\n def update_volume(self,data,ser):\n self.plt_volume.setPen(pg.mkPen(\"b\",width=3))\n self.plt_volume.setData(data.values)\n self.stock_50.setData(ser)\n\n def update_month(self,data):\n data.columns=['data','50iv','data2','300iv']\n self.plt_month50.setData(data['50iv'])\n self.plt_month50.setPen(pg.mkPen(\"r\",width=2))\n self.plt_month300.setData(data['300iv'])\n self.plt_month300.setPen(pg.mkPen(\"b\",width=1))\n\n def update_iv(self,data50,data300):\n data50.sort_index(inplace=True)\n data50 = data50.astype(float)\n data50[data50<1]=np.nan\n self.plt_iv50_1.setData(data50.iloc[:,0])\n self.plt_iv50_2.setData(data50.iloc[:,5])\n self.plt_iv50_3.setData(data50.iloc[:,1])\n self.plt_iv50_4.setData(data50.iloc[:,6])\n self.plt_iv50_5.setData(data50.iloc[:,2])\n self.plt_iv50_6.setData(data50.iloc[:,7])\n self.plt_iv50_7.setData(data50.iloc[:,3])\n self.plt_iv50_8.setData(data50.iloc[:,8])\n\n data300.sort_index(inplace=True)\n data300 = data300.astype(float)\n data300[data300<1]=np.nan\n self.plt_iv300_1.setData(data300.iloc[:,0])\n self.plt_iv300_2.setData(data300.iloc[:,5])\n self.plt_iv300_3.setData(data300.iloc[:,1])\n self.plt_iv300_4.setData(data300.iloc[:,6])\n self.plt_iv300_5.setData(data300.iloc[:,2])\n self.plt_iv300_6.setData(data300.iloc[:,7])\n self.plt_iv300_7.setData(data300.iloc[:,3])\n self.plt_iv300_8.setData(data300.iloc[:,8])\n \n def update_greek(self,gk):\n text = 'DELTA:{}GAMMA:{}VEGA:{}THETA:{}'.format(gk[0],gk[1],gk[2],gk[3])\n self.label_greek.setText(text)\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = Example()\n ex.show()\n sys.exit(app.exec_())", "step-ids": [ 11, 12, 13, 14, 17 ] }
[ 11, 12, 13, 14, 17 ]
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- """ # @Time : 20-6-9 上午11:47 # @Author : zhufa # @Software: PyCharm """ """ tensorflow version must below 1.15 """ import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # 返回带初始值的权重变量 def weight_variable(shape, name): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial, name=name) # 返回带初始值的偏置变量 def bias_variable(shape, name): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial, name=name) # 卷积:x为输入图像,W为卷积核,padding补0,步长为1,图像尺寸不变 def conv2d(x, W): return tf.nn.conv2d(x, W, [1, 1, 1, 1], padding='SAME') # 池化: def max_pool_2x2(x): return tf.nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME') # 第一层:卷积+池化 W_conv1 = weight_variable([5, 5, 1, 32], "W_conv1") # 5×5的卷积核,出入为1通道的图,输出为32,即32个卷积核 b_conv1 = bias_variable([32], "b_conv1") x = tf.placeholder("float", (None, 784), name='input_x') # 将x转化为28×28的图像矩阵/向量/张量,-1表示视原x的情况计算而出,最后的1表示通道,若为彩色图像则为3 reshaped_x = tf.reshape(x, [-1, 28, 28, 1]) h_conv1 = tf.nn.relu(conv2d(reshaped_x, W_conv1) + b_conv1) # 卷积后的图像尺寸不变 h_pool1 = max_pool_2x2(h_conv1) # 池化后的图像尺寸为14×14 # 第二层卷积+池化 W_conv2 = weight_variable([5, 5, 32, 64], "W_conv2") b_conv2 = bias_variable([64], "b_conv2") h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # 卷积后的图像尺寸不变 h_pool2 = max_pool_2x2(h_conv2) # 池化后的图像尺寸为7×7 # 密集连接层:1024个神经元(全连接) W_fc1 = weight_variable([7 * 7 * 64, 1024], "W_fc1") b_fc1 = bias_variable([1024], "b_fc1") reshaped_h_pool2 = tf.reshape(h_pool2, [-1, 7 * 7 * 64]) h_fc1 = tf.nn.relu(tf.matmul(reshaped_h_pool2, W_fc1) + b_fc1) # dropout keep_prob = tf.placeholder("float", name='keep_prob') h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) # 输出层 W_fc2 = weight_variable([1024, 10], "W_fc2") b_fc2 = bias_variable([10], "b_fc2") y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) # 损失函数及训练模型 y_ = tf.placeholder(tf.float32, [None, 10]) cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv)) train = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) # 准备训练,初始化所有变量 sess = tf.Session() sess.run(tf.initialize_all_variables()) # 测试模型准确率 correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) '''设置模型保存器''' m_saver = tf.train.Saver() # 训练20000次,每次随机抓取100对测试样本,每100次输出当前的准确率 for i in range(10000): batch_xs, batch_ys = mnist.train.next_batch(100) if i % 100 == 0: step_accuracy = accuracy.eval(session=sess, feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}) print "step %d test accuracy: %g" % (i, step_accuracy) sess.run(train, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.5}) # 保存模型参数,如何加载模型并使用参见 mnist_test.py # m_saver.save(sess, "model/mnist-model", global_step=10000) print "test accuracy: %g" % accuracy.eval(session=sess, feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})
normal
{ "blob_id": "779e7cd05edfd74c8e60eaf5ce8443aea5fdaaef", "index": 8028, "step-1": "#!/usr/bin/python2.7\n# -*- coding: utf-8 -*-\n\n\"\"\"\n# @Time : 20-6-9 上午11:47\n\n# @Author : zhufa\n\n# @Software: PyCharm\n\"\"\"\n\"\"\"\ntensorflow version must below 1.15\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n\n\n# 返回带初始值的权重变量\ndef weight_variable(shape, name):\n initial = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(initial, name=name)\n\n\n# 返回带初始值的偏置变量\ndef bias_variable(shape, name):\n initial = tf.constant(0.1, shape=shape)\n return tf.Variable(initial, name=name)\n\n\n# 卷积:x为输入图像,W为卷积核,padding补0,步长为1,图像尺寸不变\ndef conv2d(x, W):\n return tf.nn.conv2d(x, W, [1, 1, 1, 1], padding='SAME')\n\n\n# 池化:\ndef max_pool_2x2(x):\n return tf.nn.max_pool(x, [1, 2, 2, 1], [1, 2, 2, 1], padding='SAME')\n\n\n# 第一层:卷积+池化\nW_conv1 = weight_variable([5, 5, 1, 32], \"W_conv1\") # 5×5的卷积核,出入为1通道的图,输出为32,即32个卷积核\nb_conv1 = bias_variable([32], \"b_conv1\")\n\nx = tf.placeholder(\"float\", (None, 784), name='input_x')\n# 将x转化为28×28的图像矩阵/向量/张量,-1表示视原x的情况计算而出,最后的1表示通道,若为彩色图像则为3\nreshaped_x = tf.reshape(x, [-1, 28, 28, 1])\nh_conv1 = tf.nn.relu(conv2d(reshaped_x, W_conv1) + b_conv1) # 卷积后的图像尺寸不变\nh_pool1 = max_pool_2x2(h_conv1) # 池化后的图像尺寸为14×14\n\n# 第二层卷积+池化\nW_conv2 = weight_variable([5, 5, 32, 64], \"W_conv2\")\nb_conv2 = bias_variable([64], \"b_conv2\")\nh_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # 卷积后的图像尺寸不变\nh_pool2 = max_pool_2x2(h_conv2) # 池化后的图像尺寸为7×7\n\n# 密集连接层:1024个神经元(全连接)\nW_fc1 = weight_variable([7 * 7 * 64, 1024], \"W_fc1\")\nb_fc1 = bias_variable([1024], \"b_fc1\")\n\nreshaped_h_pool2 = tf.reshape(h_pool2, [-1, 7 * 7 * 64])\nh_fc1 = tf.nn.relu(tf.matmul(reshaped_h_pool2, W_fc1) + b_fc1)\n\n# dropout\nkeep_prob = tf.placeholder(\"float\", name='keep_prob')\nh_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n\n# 输出层\nW_fc2 = weight_variable([1024, 10], \"W_fc2\")\nb_fc2 = bias_variable([10], \"b_fc2\")\ny_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)\n\n# 损失函数及训练模型\ny_ = tf.placeholder(tf.float32, [None, 10])\ncross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))\ntrain = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\n\n# 准备训练,初始化所有变量\nsess = tf.Session()\nsess.run(tf.initialize_all_variables())\n\n# 测试模型准确率\ncorrect_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, \"float\"))\n\n'''设置模型保存器'''\nm_saver = tf.train.Saver()\n\n# 训练20000次,每次随机抓取100对测试样本,每100次输出当前的准确率\nfor i in range(10000):\n batch_xs, batch_ys = mnist.train.next_batch(100)\n if i % 100 == 0:\n step_accuracy = accuracy.eval(session=sess,\n feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})\n print \"step %d test accuracy: %g\" % (i, step_accuracy)\n sess.run(train, feed_dict={x: batch_xs, y_: batch_ys, keep_prob: 0.5})\n\n# 保存模型参数,如何加载模型并使用参见 mnist_test.py\n# m_saver.save(sess, \"model/mnist-model\", global_step=10000)\n\nprint \"test accuracy: %g\" % accuracy.eval(session=sess,\n feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})\n", "step-2": null, "step-3": null, "step-4": null, "step-5": null, "step-ids": [ 0 ] }
[ 0 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> print(incd_data.columns) <|reserved_special_token_1|> <|reserved_special_token_0|> incd_data = pd.read_csv('data/Cancer/incd.csv', usecols=['State', 'FIPS', 'Age-Adjusted Incidence Rate([rate note]) - cases per 100,000', 'Average Annual Count', 'Recent Trend']) print(incd_data.columns) <|reserved_special_token_1|> import numpy as np import pandas as pd incd_data = pd.read_csv('data/Cancer/incd.csv', usecols=['State', 'FIPS', 'Age-Adjusted Incidence Rate([rate note]) - cases per 100,000', 'Average Annual Count', 'Recent Trend']) print(incd_data.columns) <|reserved_special_token_1|> # Importing datasets wrangling libraries import numpy as np import pandas as pd incd_data = pd.read_csv('data/Cancer/incd.csv', usecols=['State', 'FIPS', 'Age-Adjusted Incidence Rate([rate note]) - cases per 100,000', 'Average Annual Count', 'Recent Trend']) print(incd_data.columns)
flexible
{ "blob_id": "1deab16d6c574bf532c561b8d6d88aac6e5d996c", "index": 8355, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(incd_data.columns)\n", "step-3": "<mask token>\nincd_data = pd.read_csv('data/Cancer/incd.csv', usecols=['State', 'FIPS',\n 'Age-Adjusted Incidence Rate([rate note]) - cases per 100,000',\n 'Average Annual Count', 'Recent Trend'])\nprint(incd_data.columns)\n", "step-4": "import numpy as np\nimport pandas as pd\nincd_data = pd.read_csv('data/Cancer/incd.csv', usecols=['State', 'FIPS',\n 'Age-Adjusted Incidence Rate([rate note]) - cases per 100,000',\n 'Average Annual Count', 'Recent Trend'])\nprint(incd_data.columns)\n", "step-5": "# Importing datasets wrangling libraries\nimport numpy as np\nimport pandas as pd\n\nincd_data = pd.read_csv('data/Cancer/incd.csv', usecols=['State', 'FIPS', 'Age-Adjusted Incidence Rate([rate note]) - cases per 100,000', 'Average Annual Count', 'Recent Trend'])\nprint(incd_data.columns)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
''' Created on Mar 27, 2019 @author: Iulia ''' from Graph import Graph from Controller import * from Iterators.Vertices import * from File import File from Iterators.EdgesIterator import EdgesIterator def test(): tup = File.readInput("file.txt") graph = tup[0] edgeData = tup[1] ctrl = Controller(graph, edgeData) vertices = ctrl.nrVertices() itv = verticesIterator(vertices) assert(itv.valid()) cont = 0 while (itv.valid()): cont += 1 e = itv.getCurrent() itv.next() e = itv.getCurrent() assert(ctrl.existsVertex(e)) assert(cont == ctrl.nrVertices()) itv.first() assert(itv.valid()) ################ ite = EdgesIterator(graph.getInbound(3)) assert(ite.valid()) assert(ite.getCurrent() == 1) ite.next() assert(ite.valid()) assert(ite.getCurrent() == 2) test()
normal
{ "blob_id": "b01ff71792895bb8839e09ae8c4a449405349990", "index": 7066, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef test():\n tup = File.readInput('file.txt')\n graph = tup[0]\n edgeData = tup[1]\n ctrl = Controller(graph, edgeData)\n vertices = ctrl.nrVertices()\n itv = verticesIterator(vertices)\n assert itv.valid()\n cont = 0\n while itv.valid():\n cont += 1\n e = itv.getCurrent()\n itv.next()\n e = itv.getCurrent()\n assert ctrl.existsVertex(e)\n assert cont == ctrl.nrVertices()\n itv.first()\n assert itv.valid()\n ite = EdgesIterator(graph.getInbound(3))\n assert ite.valid()\n assert ite.getCurrent() == 1\n ite.next()\n assert ite.valid()\n assert ite.getCurrent() == 2\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef test():\n tup = File.readInput('file.txt')\n graph = tup[0]\n edgeData = tup[1]\n ctrl = Controller(graph, edgeData)\n vertices = ctrl.nrVertices()\n itv = verticesIterator(vertices)\n assert itv.valid()\n cont = 0\n while itv.valid():\n cont += 1\n e = itv.getCurrent()\n itv.next()\n e = itv.getCurrent()\n assert ctrl.existsVertex(e)\n assert cont == ctrl.nrVertices()\n itv.first()\n assert itv.valid()\n ite = EdgesIterator(graph.getInbound(3))\n assert ite.valid()\n assert ite.getCurrent() == 1\n ite.next()\n assert ite.valid()\n assert ite.getCurrent() == 2\n\n\ntest()\n", "step-4": "<mask token>\nfrom Graph import Graph\nfrom Controller import *\nfrom Iterators.Vertices import *\nfrom File import File\nfrom Iterators.EdgesIterator import EdgesIterator\n\n\ndef test():\n tup = File.readInput('file.txt')\n graph = tup[0]\n edgeData = tup[1]\n ctrl = Controller(graph, edgeData)\n vertices = ctrl.nrVertices()\n itv = verticesIterator(vertices)\n assert itv.valid()\n cont = 0\n while itv.valid():\n cont += 1\n e = itv.getCurrent()\n itv.next()\n e = itv.getCurrent()\n assert ctrl.existsVertex(e)\n assert cont == ctrl.nrVertices()\n itv.first()\n assert itv.valid()\n ite = EdgesIterator(graph.getInbound(3))\n assert ite.valid()\n assert ite.getCurrent() == 1\n ite.next()\n assert ite.valid()\n assert ite.getCurrent() == 2\n\n\ntest()\n", "step-5": "'''\nCreated on Mar 27, 2019\n\n@author: Iulia\n'''\n\nfrom Graph import Graph\nfrom Controller import *\nfrom Iterators.Vertices import *\nfrom File import File\nfrom Iterators.EdgesIterator import EdgesIterator\n\ndef test():\n tup = File.readInput(\"file.txt\")\n graph = tup[0]\n edgeData = tup[1]\n ctrl = Controller(graph, edgeData)\n \n vertices = ctrl.nrVertices()\n \n itv = verticesIterator(vertices)\n assert(itv.valid())\n \n cont = 0\n while (itv.valid()):\n cont += 1\n e = itv.getCurrent()\n itv.next() \n e = itv.getCurrent()\n assert(ctrl.existsVertex(e))\n assert(cont == ctrl.nrVertices())\n itv.first()\n assert(itv.valid())\n \n ################\n ite = EdgesIterator(graph.getInbound(3))\n assert(ite.valid())\n assert(ite.getCurrent() == 1)\n ite.next()\n assert(ite.valid())\n assert(ite.getCurrent() == 2)\n \ntest()\n ", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
''' @author: Ken Venner @contact: ken@venerllc.com @version: 1.13 Read in a file of wine names and create consistent wine descriptions from these names. ''' import kvutil import kvcsv import re import sys import shutil # may comment out in the future import pprint pp = pprint.PrettyPrinter(indent=4) ppFlag = False # application variables optiondictconfig = { 'AppVersion' : { 'value' : '1.13', 'description' : 'defines the version number for the app', }, 'debug' : { 'value' : False, 'type' : 'bool', 'description' : 'defines if we are running in debug mode', }, 'verbose' : { 'value' : 1, 'type' : 'int', 'description' : 'defines the display level for print messages', }, 'setup_check' : { 'value' : False, 'type' : 'bool', 'description' : 'defines if we checking out setup', }, 'pprint' : { 'value' : False, 'type' : 'bool', 'description' : 'defines if we output with pretty print when debugging', }, 'csvfile_master_in' : { 'value' : 'wine_xref.csv', 'description' : 'defines the name of the master data input file', }, 'csvfile_update_in' : { 'value' : 'wineref.csv', 'description' : 'defines the name of the input file to updated', }, 'csvfile_update_out' : { 'value' : 'wineref2.csv', 'description' : 'defines the name of the updated output file', }, 'fldWine' : { 'value' : 'wine', 'description' : 'defines the name of the field that holds the Wine ', }, 'fldWineDescr' : { 'value' : 'winedescr', 'description' : 'defines the name of the field holding the wine description', }, 'fldWineDescrNew' : { 'value' : 'winedescrnew', 'description' : 'defines the name of the NEW field holding the new description ', }, 'fldWineDescrMatch' : { 'value' : None, 'description' : 'defines the name of the NEW field holding the results of comparison existing to new description ', }, 'fldWineMaster' : { 'value' : None, 'description' : 'defines the name of the field that holds the Wine when reading the master file ', }, 'fldWineDescrMaster' : { 'value' : None, 'description' : 'defines the name of the field holding the wine description when reading the master file', }, 'backupfile_ext' : { 'value' : '.bak', 'description' : 'defines the extension to use to copy the update input file to if we are replacing it with output', }, 'defaultnew' : { 'value' : None, 'description' : 'defines if we should take field fldWineDescrNew and set to a value if not set', }, } ### GLOBAL VARIABLES / LOOKUPS ######################################## # regex search for vintage in wine name vintageLookup = ( re.compile('\d\d\d\d\s+\d\d(\d\d)'), # two years together - get this one over early re.compile('^\d\d(\d\d)'), # four position start of line re.compile('\s\d\d(\d\d)$'), # four position end of line re.compile('\s\d\d(\d\d)\s'), # four position middle of line re.compile('XX\d\d(\d\d)\s'), # four position middle of line re.compile('\s\d\d(\d\d)\/'), # four position split re.compile('\s\'?(\d\d)\'?$|\s\'?(\d\d)\'?\s'), # two position date with optional apostrophe front or back ) # regex search for case in wine name reCase = re.compile(r'12\s*X\s*750\s*ML|\bcase\b|12\/750\s*ML',re.IGNORECASE) # regex to pick up qualifiers from the wine reQualLookup = ( (None, re.compile(r'\bWithout\s+Gift\b|\bNo\s+Gift', re.IGNORECASE)), # the none gift do them first ('Gift', re.compile(r'\bGift\b', re.IGNORECASE)), ('VAP', re.compile(r'\bVAP\b', re.IGNORECASE)), ('VAP', re.compile(r'\bGlassVAP\b', re.IGNORECASE)), ('Glass', re.compile(r'\bGlass\b', re.IGNORECASE)), ('Glass', re.compile(r'\bGlasses\b', re.IGNORECASE)), ('Etch', re.compile(r'\bEtch\b', re.IGNORECASE)), ('Basket', re.compile(r'\bBasket\b', re.IGNORECASE)), ) # regex search to define the size of the wine bottle sizeLookup = ( ('1.75L', re.compile(r'\b1\.75\s*Li?|\b1\.75$', re.IGNORECASE)), ('1.5L', re.compile(r'\b1\.5\s*L?\b|\bMagnum\b', re.IGNORECASE)), ('375mL', re.compile(r'Half\s+Bottle|375ml', re.IGNORECASE)), ('200mL', re.compile(r'\b200\s*ML|\(200\s*ML', re.IGNORECASE)), ('50mL', re.compile(r'\b50\s*ML|\(50\s*ML', re.IGNORECASE)), ('500mL', re.compile(r'\b500\s*ML|\(500\s*ML', re.IGNORECASE)), ('3L', re.compile(r'\b3\s*Li?', re.IGNORECASE)), ('6L', re.compile(r'\b6\s*Li?', re.IGNORECASE)), ('9L', re.compile(r'\b9\s*Li?', re.IGNORECASE)), ('1L', re.compile(r'\b1L\b|\b1\s+L$|\b1.0\s*L\b|\b1\s+Liter\b|\bOne\s+Liter\b|\bLITER\b|\b1\s*LTR', re.IGNORECASE)), ) # regex extract winery names from the wine field wineryLookup = ( ('Alban', re.compile(r'\bAlban\b', re.IGNORECASE)), ('Arrowood', re.compile(r'\bArrowood\b', re.IGNORECASE)), ('Atalon', re.compile(r'\bAtalon\b', re.IGNORECASE)), ('Attune', re.compile(r'\bAttune\b', re.IGNORECASE)), ('Auteur', re.compile(r'\bAuteur\b', re.IGNORECASE)), ('Austin Hope', re.compile(r'\bAustin\s+Hope\b', re.IGNORECASE)), ('Badge', re.compile(r'\bBadge\b', re.IGNORECASE)), ('Balletto', re.compile(r'\bBalletto\b', re.IGNORECASE)), ('Bell', re.compile(r'\bBell\s+Cellar', re.IGNORECASE)), ('BR Cohn', re.compile(r'\bB\.?\s?R\.?\s+Cohn\b', re.IGNORECASE)), ('Bremer', re.compile(r'\bBremer\b', re.IGNORECASE)), ('Brewer-Clifton', re.compile(r'\bBrewer[\s\-]Clifton\b', re.IGNORECASE)), ('BV', re.compile(r'\bBeaulieu\s+V|\bBV\b', re.IGNORECASE)), ('Belle Glos', re.compile(r'\bBelle\s+Glos\b', re.IGNORECASE)), ('Bennett Ln', re.compile(r'\bBennet+\sLane\b', re.IGNORECASE)), ('Benovia', re.compile(r'\bBenovia\b', re.IGNORECASE)), ('Beringer', re.compile(r'\bBeringer\b', re.IGNORECASE)), ('Blackstone', re.compile(r'\bBlackstone\b', re.IGNORECASE)), ('Brancott', re.compile(r'\bBrancott\b', re.IGNORECASE)), ('Cade', re.compile(r'\bCade\b', re.IGNORECASE)), ('Cain Five', re.compile(r'\bCain\s+Five\b|\bCain\s-\sFive\b|\bCain\s5\b|\bCainFive\b', re.IGNORECASE)), ('Cakebread', re.compile(r'\bCakebread\b', re.IGNORECASE)), ('Cardinale', re.compile(r'\bCardinale\b', re.IGNORECASE)), ('Caymus', re.compile(r'\bCaymus\b', re.IGNORECASE)), ('Chappellet', re.compile(r'\bChappellet\b', re.IGNORECASE)), ('Chalk Hill', re.compile(r'\bChalk\s+Hill\b', re.IGNORECASE)), ('Clos Du Bois', re.compile(r'\bClos\s+Du\s+Bois\b', re.IGNORECASE)), ('ClosDuVal', re.compile(r'\bClos\s+du\s+Val\b', re.IGNORECASE)), ('Colgin', re.compile(r'\bColgin\b', re.IGNORECASE)), ('Concha Don Melchor', re.compile(r'\bConcha\s.*Don\s+Melchor\b|Don\s+Melchor\b', re.IGNORECASE)), ('Continuum', re.compile(r'\bContinuum\b', re.IGNORECASE)), ('Corison', re.compile(r'\bCorison\b', re.IGNORECASE)), ('Cristal', re.compile(r'Roederer\s?.*Cristal\b|\bCristal\b.+Brut', re.IGNORECASE)), ('Curran', re.compile(r'\bCurran\b', re.IGNORECASE)), ('Darioush', re.compile(r'\bDarioush\b', re.IGNORECASE)), ('Darioush', re.compile(r'\bCaravan\b', re.IGNORECASE)), ('David Arthur', re.compile(r'\bDavid\s+Arthur\b', re.IGNORECASE)), ('David Bruce', re.compile(r'\bDavid\s+Bruce\b', re.IGNORECASE)), ('Davis Family', re.compile(r'\bDavis\s+Family\b', re.IGNORECASE)), ('Del Dotto', re.compile(r'\bDel\s+Dotto\b', re.IGNORECASE)), ('Dominus', re.compile(r'\bDominus\b', re.IGNORECASE)), ('Goldeneye', re.compile(r'\bGoldeneye\b', re.IGNORECASE)), # before duckhorn ('Paraduxx', re.compile(r'\bParaduxx\b', re.IGNORECASE)), # before duckhorn ('Domaine Carneros', re.compile(r'\bDomaine\s+Carneros\b', re.IGNORECASE)), ('Dominus', re.compile(r'\Dominus\b', re.IGNORECASE)), ('Drappier', re.compile(r'\bDrappier\b', re.IGNORECASE)), ('Duckhorn', re.compile(r'\bDuckhorn\b', re.IGNORECASE)), ('Dumol', re.compile(r'\bDumol\b', re.IGNORECASE)), ('Dunn', re.compile(r'\bDunn\b', re.IGNORECASE)), ('Ehlers', re.compile(r'\bEhlers\b', re.IGNORECASE)), ('Etude', re.compile(r'\bEtude\b', re.IGNORECASE)), ('Far Niente', re.compile(r'\bFar Niente\b', re.IGNORECASE)), ('Flora', re.compile(r'\bFlora\s+Springs\b', re.IGNORECASE)), ('Flowers', re.compile(r'\bFlowers\b', re.IGNORECASE)), ('Robert Foley', re.compile(r'\bRobert\s+\bFoley\b', re.IGNORECASE)), #before Foley ('Foley', re.compile(r'\bFoley\b', re.IGNORECASE)), ('Foxen', re.compile(r'\bFoxen\b', re.IGNORECASE)), ('Franciscan', re.compile(r'\bFranciscan\b', re.IGNORECASE)), ('Frank Family', re.compile(r'\bFrank Family\b', re.IGNORECASE)), ('Gary Farrell', re.compile(r'\bGary\s+Farrel+\b', re.IGNORECASE)), ('Ghost Block', re.compile(r'\bGhost\s+Block\b', re.IGNORECASE)), ('Grgich', re.compile(r'\bGrgich\b', re.IGNORECASE)), ('Groth', re.compile(r'\bGroth\b', re.IGNORECASE)), ('Gundlach', re.compile(r'\bGundlach\b', re.IGNORECASE)), ('Hansel', re.compile(r'\bHansel\b', re.IGNORECASE)), ('Hanzell', re.compile(r'\bHanzell\b', re.IGNORECASE)), ('Hess', re.compile(r'\bHess\b', re.IGNORECASE)), ('Hewitt', re.compile(r'\bHewitt\b', re.IGNORECASE)), ('Hobbs', re.compile(r'\bHobbs\b|\bcrossbarn\b', re.IGNORECASE)), ('Hundred Acre', re.compile(r'\bHundred\s+Acre\b', re.IGNORECASE)), ('Jordan', re.compile(r'\bJordan\b', re.IGNORECASE)), ('Justin', re.compile(r'\bJustin\b', re.IGNORECASE)), ('Kim Crawford', re.compile(r'\bKim\s+Crawford\b', re.IGNORECASE)), ('Kistler', re.compile(r'\bKistler\b', re.IGNORECASE)), ('Kosta', re.compile(r'\bKosta\s+Browne?\b', re.IGNORECASE)), ('Krug', re.compile(r'\bKrug\b', re.IGNORECASE)), ('Kunde', re.compile(r'\bKunde\b', re.IGNORECASE)), ('LaCrema', re.compile(r'\bLa\s?Crema\b', re.IGNORECASE)), ('Lewis', re.compile(r'\bLewis\b', re.IGNORECASE)), ('Lokoya', re.compile(r'\bLokoya\b', re.IGNORECASE)), ('Meiomi', re.compile(r'\bMeiomi\b', re.IGNORECASE)), ('Melville', re.compile(r'\bMelville\b', re.IGNORECASE)), ('Momento Mori', re.compile(r'\bMomento\s+Mori\b', re.IGNORECASE)), ('Mondavi', re.compile(r'\bMondavi\b', re.IGNORECASE)), ('Montelena', re.compile(r'\bMontelena\b', re.IGNORECASE)), ('Mt Veeder', re.compile(r'^Mount\s+Veeder\b|^Mt\.? Veeder\b|\d+\s+M[^t]*t\s+Veeder\b', re.IGNORECASE)), ('Newton', re.compile(r'\bNewton\b', re.IGNORECASE)), ('Nickel', re.compile(r'\bNickel\b', re.IGNORECASE)), ('Opus One', re.compile(r'\bOpus\s+One\b', re.IGNORECASE)), ('P Togni', re.compile(r'\bTogni\b', re.IGNORECASE)), ('Pahlmeyer Jayson', re.compile(r'\bJayson\b', re.IGNORECASE)), # this before pahlmeyer ('Pahlmeyer', re.compile(r'\bPahlmeyer\b(?!\s*Jay)', re.IGNORECASE)), ('Papillon', re.compile(r'\bPapillon\b', re.IGNORECASE)), ('Patz', re.compile(r'\bPatz\b', re.IGNORECASE)), ('Phelps', re.compile(r'\bPhelps\b', re.IGNORECASE)), ('Plumpjack', re.compile(r'\bPlumpjack\b', re.IGNORECASE)), ('Pride', re.compile(r'\bPride\b', re.IGNORECASE)), ('Prisoner', re.compile(r'\bPrisoner\b', re.IGNORECASE)), ('Provenance', re.compile(r'\bProvenance\b', re.IGNORECASE)), ('R Sinskey', re.compile(r'\bSinskey\b', re.IGNORECASE)), ('Ramey', re.compile(r'\bRamey\b', re.IGNORECASE)), ('Revana', re.compile(r'\bRevana\b', re.IGNORECASE)), ('Raptor', re.compile(r'\bRaptor\s+Ridge\b', re.IGNORECASE)), ('Revana', re.compile(r'\bRevana\b', re.IGNORECASE)), ('Ridge', re.compile(r'\bRidge\b', re.IGNORECASE)), ('Robert Foley', re.compile(r'\bRobert\s+Foley\b', re.IGNORECASE)), ('Rombauer', re.compile(r'\bRombauer\b', re.IGNORECASE)), ('Rudd', re.compile(r'\bRudd\b', re.IGNORECASE)), ('Scarecrow', re.compile(r'\bScarecrow\b', re.IGNORECASE)), ('Sea Smoke', re.compile(r'\bSea\s+Smoke\b', re.IGNORECASE)), ('Seghesio', re.compile(r'\bSeghesio\b', re.IGNORECASE)), ('Shafer', re.compile(r'\bShafer\b', re.IGNORECASE)), ('Sherwin', re.compile(r'\bSherwin\b', re.IGNORECASE)), ('Silver Oak', re.compile(r'\bSilver\s+Oak\b', re.IGNORECASE)), ('Silverado', re.compile(r'\bSilverado\b', re.IGNORECASE)), ('Simi', re.compile(r'\bSimi\b', re.IGNORECASE)), ('Sonoma Cutrer', re.compile(r'\bCutrer\b', re.IGNORECASE)), ('Spottswoode', re.compile(r'\bSpottswoode\b', re.IGNORECASE)), ('Stag Leap', re.compile(r'\bStag.*\sLeap\b', re.IGNORECASE)), ('Sullivan', re.compile(r'\bSullivan\b', re.IGNORECASE)), ('Summerland', re.compile(r'\bSummerland\b', re.IGNORECASE)), ('Summers', re.compile(r'\bSummers\b', re.IGNORECASE)), ('Tantara', re.compile(r'\bTantara\b', re.IGNORECASE)), ('Turnbull', re.compile(r'\bTurnbull\b', re.IGNORECASE)), ('Veuve', re.compile(r'\bVeuve\b', re.IGNORECASE)), ('Viader', re.compile(r'\bViader\b', re.IGNORECASE)), ('Waterstone', re.compile(r'\bWaterstone\b', re.IGNORECASE)), ('Whitehall', re.compile(r'\bWhitehall\b', re.IGNORECASE)), ('Wm Selyem', re.compile(r'\bWilliams\s*\-?Selyem\b', re.IGNORECASE)), ('ZD', re.compile(r'\bZD\b', re.IGNORECASE)), ('Zaca', re.compile(r'\bZaca\b', re.IGNORECASE)), ('zBourbon Woodford Res', re.compile(r'\bWoodford\s+Reserve\b', re.IGNORECASE)), ('zBourbon Woodford Res', re.compile(r'\bWoodford\s+Rsv\b', re.IGNORECASE)), ('zCognac Courvoisier', re.compile(r'\bCourvoisier\b', re.IGNORECASE)), ('zCognac Hennessy', re.compile(r'\bHennesse?y\b', re.IGNORECASE)), ('zCognac Remy', re.compile(r'\bRemy\s+Martin\b|\bRemy\s+Louis', re.IGNORECASE)), ('zCointreau', re.compile(r'\bCointreau\b', re.IGNORECASE)), ('zGin Hendrick', re.compile(r'\bHendrick', re.IGNORECASE)), ('zGin Tanqueray', re.compile(r'\bTanqueray\b', re.IGNORECASE)), ('zRum Mt Gay', re.compile(r'\bMount\s+Gay\b|\bMt\s+Gay', re.IGNORECASE)), ('zRum Ron Zacapa', re.compile(r'\bRon\s+Zacapa\b', re.IGNORECASE)), ('zRye Hayden', re.compile(r'\bBasil\s+Hayden\b', re.IGNORECASE)), ('zSambuca', re.compile(r'\bSambuca\b', re.IGNORECASE)), ('zScotch Glenmorangie', re.compile(r'\bGlenmorangie\b', re.IGNORECASE)), ('zScotch Hibiki Harmony', re.compile(r'\bHibiki\s.*Harmony\b', re.IGNORECASE)), ('zScotch Hibiki', re.compile(r'\bHibiki\b(?!\s*Har)', re.IGNORECASE)), ('zScotch Macallan', re.compile(r'\bMacallan\b', re.IGNORECASE)), ('zTeq Campo Azul', re.compile(r'\bCampo\s+Azul\b', re.IGNORECASE)), ('zTeq Casamigos', re.compile(r'\bCasamigos\b', re.IGNORECASE)), ('zTeq Casino Azul', re.compile(r'\bCasino\s+Azul\b', re.IGNORECASE)), ('zTeq Clase Azul', re.compile(r'\bClase\s+Azul\b', re.IGNORECASE)), ('zTeq Cuervo', re.compile(r'\bJose\s+Cuervo\b|^Cuervo\b', re.IGNORECASE)), ('zTeq Don Julio', re.compile(r'\bDon\s+Julio\b', re.IGNORECASE)), ('zTeq Dos Artes', re.compile(r'\bDos\s+Artes\b|^Cuervo\b', re.IGNORECASE)), ('zTeq Gran Cava', re.compile(r'\bGran\s+Cava\b', re.IGNORECASE)), ('zTeq Herradura', re.compile(r'\bHerradura\b', re.IGNORECASE)), ('zTeq Loma Azul', re.compile(r'\bLoma\s+Azul\b', re.IGNORECASE)), ('zTeq Padre Azul', re.compile(r'\bPadre\s+Azul\b', re.IGNORECASE)), ('zTeq Partida', re.compile(r'\bPartida\b', re.IGNORECASE)), ('zTeq Patron', re.compile(r'\bPatron\b', re.IGNORECASE)), ('zTripleSec Gr Marnier', re.compile(r'\bGrand\s+Marnier\b', re.IGNORECASE)), ('zTripleSec Dekuyper', re.compile(r'\bDekuyper\b', re.IGNORECASE)), ('zTripleSec Hiram', re.compile(r'\bHiram\b', re.IGNORECASE)), ('zVodka Absolut', re.compile(r'\bAbsolut\b', re.IGNORECASE)), ('zVodka Skyy', re.compile(r'\bSkyy\b', re.IGNORECASE)), ('zVodka Tito', re.compile(r'\bTito', re.IGNORECASE)), ('zWhiskey Balvenie', re.compile(r'\bBalvenie\b', re.IGNORECASE)), ('zWhiskey J Walker', re.compile(r'\bJohn+ie\s+Walker\b', re.IGNORECASE)), # ('', re.compile(r'\b\b', re.IGNORECASE)), ) # regex extract the grape from the wine fld grapeLookup = ( ('Cab Franc', re.compile(r'\bCabernet\s+Franc|\bCab\s+Franc', re.IGNORECASE)), # before cab ('Cab', re.compile(r'\bCabernet\b|\sCS\s|\sCS$|\bCab\b', re.IGNORECASE)), ('Claret', re.compile(r'\bClaret\b', re.IGNORECASE)), ('Rose Pinot', re.compile(r'\bRose\b.*\bPinot\b|\bPinot\b.*\bRose\b', re.IGNORECASE)), ('Pinot', re.compile(r'\bPinot\b|\bPN\b|\bP\s+Noir\b', re.IGNORECASE)), ('Merlot', re.compile(r'\bMerlot\b|\bME\b', re.IGNORECASE)), ('Sauv Blanc', re.compile(r'\bSauvignon\s+Blanc\b|\bSB\b', re.IGNORECASE)), ('Sauv Blanc', re.compile(r'\bSauvignon\/Fume\s+Blanc\b', re.IGNORECASE)), ('Meritage', re.compile(r'\bMeritage\b', re.IGNORECASE)), ('Fume', re.compile(r'\bFume\b|\bFum&#233;', re.IGNORECASE)), ('Champagne', re.compile(r'\bChampagne\b', re.IGNORECASE)), ('Chard', re.compile(r'\bChar+d|\bCH\b', re.IGNORECASE)), ('Shiraz', re.compile(r'\bShiraz\b', re.IGNORECASE)), ('Syrah', re.compile(r'\bSyrah\b|\bSY\b',re.IGNORECASE)), ('Zin', re.compile(r'\bZinfandel\b|\bZIN\b|\bZN\b', re.IGNORECASE)), ('Rose', re.compile(r'\bRose\b|\bRos&#233;', re.IGNORECASE)), ('Sangiovese', re.compile(r'\Sangiovese\b', re.IGNORECASE)), # ('Brandy', re.compile(r'\bBrandy\b', re.IGNORECASE)), ('Gewurzt', re.compile(r'\bGew.rztraminer\b|\bGew&#252;rzt', re.IGNORECASE)), ('Malbec', re.compile(r'\bMalbec\b', re.IGNORECASE)), ('Viognier', re.compile(r'\bViognier\b', re.IGNORECASE)), ('Roussanne', re.compile(r'\bRoussanne\b', re.IGNORECASE)), ('Charbono', re.compile(r'\bCharbono\b', re.IGNORECASE)), ('PSirah', re.compile(r'\bPetite Sirah\b', re.IGNORECASE)), ('Cuvee', re.compile(r'\bCuvee\b', re.IGNORECASE)), ('Red', re.compile(r'\bRed\b|\bBordeaux\s+Blend\b', re.IGNORECASE)), ('Syrah-Cab', re.compile(r'\bSyrcab\b|\bsyrah[-\s\/]+cab', re.IGNORECASE)), ('Grenache', re.compile(r'\bGrenache\b', re.IGNORECASE)), ('Tempranillo', re.compile(r'\bTempranillo\b', re.IGNORECASE)), ) # wineries that we don't want to look up the grape on ignoreGrapeLookup = { 'Cristal' : ['Rose', None], 'Domaine Carneros' : ['Brut', None], 'Dominus' : [None], 'Papillon' : None, 'Paraduxx' : None, 'Veuve' : None, 'zCointreau' : None, 'zGin Hendrick' : None, 'zGin Tanqueray' : ['Ten', None], 'zTripleSec Gr Marnier' : ['1880', '100th', 'Cent', 'Quin', None], 'zTripleSec Dekuyper' : None, 'zTripleSec Hiram' : None, 'zVodka Skyy' : ['Citrus', None], 'zVodka Tito' : None, # 'Prisoner' : ['Cuttings', 'Red', 'Derange', 'Saldo', 'Blindfold', None], } # winery to wine lookup when no grape is found in the wine name # # extract the wine name from a winery - when a field does not have a grape lookup for the row # the name looked up and found will be the name used noGrapeLookup = { 'Ehlers' : ['120-80'], # matches an abbreviations - and matches fldWineDescr 'Alban' : ['Pandora'], 'BV' : ['Tapestry', 'Latour'], 'Bennett Ln' : ['Maximus'], 'Bremer' : ['Austintatious'], 'Cain Five' : None, 'Colgin' : ['Cariad', 'IX'], 'Concha Don Melchor' : None, 'Continuum' : None, 'Darioush' : ['Duel', 'Darius'], 'Duckhorn' : ['Discussion'], 'Far Niente' : ['Dolce'], 'Flora' : ['Trilogy'], 'Franciscan' : ['Magnificat'], 'Grgich' : ['Violetta'], 'Gundlach' : ['Vintage Reserve'], 'Justin' : ['Isosceles'], 'Krug' : ['Generations'], 'Mondavi' : ['Maestro'], 'Newton' : ['Puzzle'], 'Opus One' : None, 'Phelps' : ['Insignia'], 'Prisoner' : ['Cuttings', 'Derange', 'Saldo', 'Blindfold'], 'Ridge' : ['Monte Bello'], 'Robert Foley' : ['Griffin'], 'Sullivan' : ['Coeur de Vigne'], 'Zaca' : ['ZThree', 'ZCuvee'], 'zCognac Courvoisier' : ['Napolean', 'VS', 'VSOP', 'XO'], 'zCognac Hennessy' : ['Paradis', 'Richard', 'VS', 'VSOP', 'XO', 'Master'], 'zCognac Remy' : ['1738', 'Louis XIII', 'VSOP', 'XO', 'VS'], 'zRum Ron Zacapa' : ['23', 'Negra', 'XO'], 'zRye Hayden' : ['Dark', 'Caribbean'], 'zScotch Hibiki Harmony' : None, # 'zScotch Hibiki' : ['Toki', '12', '17', '21', '30'], 'zTeq Campo Azul' : ['Extra Anejo', 'Anejo', 'Blanco', 'Reposado'], 'zTeq Casamigos' : ['Extra Anejo', 'Anejo', 'Blanco', 'Reposado'], 'zTeq Casino Azul' : ['Extra Anejo', 'Anejo', 'Blanco', 'Reposado', 'Silver'], 'zTeq Clase Azul' : ['Ultra', 'Extra Anejo', 'Anejo', 'Blanco', 'Reposado', 'Mezcal', 'Plata', 'Platino'], 'zTeq Dos Artes' : ['Extra Anejo'], 'zTeq Gran Cava' : ['Extra Anejo'], 'zTeq Loma Azul' : ['Extra Anejo', 'Anejo', 'Blanco', 'Reposado'], # 'zTeq Padre Azul' : ['Extra Anejo', 'Anejo', 'Blanco', 'Reposado'], 'zTeq Partida' : ['Blanco', 'Elegante'], 'zVodka Absolut' : ['Citron', 'Mandarin', 'Mandrin', 'Mango', 'Ruby', 'Vanilia', 'Raspberri', 'Grapevine', None], 'zWhiskey J Walker' : ['Double Black', 'Black', 'Blue', 'Gold', 'Green', 'Platinum', 'Red','Swing', 'White', '18', '21'], } # regex to use to determine if this is a liquor not a wine # # winery -> [ liquor, regex ] # if there is no grape, and no noGrapeLookup found, but the winery has a liquorLookup # use the list of lookups to find the additional infomratoin to add to the winery # liquorLookup = { 'zRum Mt Gay' : [ ('1703 Mst', re.compile(r'\b1703\b', re.IGNORECASE)), ('BB', re.compile(r'\bBlack Barrel\b', re.IGNORECASE)), ('Eclipse Silver', re.compile(r'\bEclipse\s+Silver\b', re.IGNORECASE)), ('Eclipse', re.compile(r'\bEclipse\b', re.IGNORECASE)), ('Old Peat', re.compile(r'\bOld Peat', re.IGNORECASE)), ('Old Pot', re.compile(r'\bPot\s+Still\b', re.IGNORECASE)), ('Old', re.compile(r'\bOld\b', re.IGNORECASE)), ('Silver', re.compile(r'\bSilver\b', re.IGNORECASE)), ('XO Peat', re.compile(r'\bXO\b', re.IGNORECASE)), ], 'zScotch Glenmorangie' : [ ('10', re.compile(r'\b10(YR)?\b', re.IGNORECASE)), ('14 Port', re.compile(r'14.+\bQuinta\b|14.+\bPort\b|\bQuinta\b.+14|\bPort\b.+14', re.IGNORECASE)), ('12 Bacalta', re.compile(r'\bBacalta\b', re.IGNORECASE)), ('12 Burgundy', re.compile(r'\bBurgundy\b', re.IGNORECASE)), ('12 Nectar', re.compile(r'\bNectar\b', re.IGNORECASE)), ('12 Port', re.compile(r'\bQuinta\b|\bPort\b', re.IGNORECASE)), ('12 Sherry', re.compile(r'\bLa\s?Santa\b|\bSherry\b', re.IGNORECASE)), ('12 Signet', re.compile(r'\bSignet\b', re.IGNORECASE)), ('15 Cadboll', re.compile(r'\bCadboll', re.IGNORECASE)), ('15', re.compile(r'\b15(YR)?\b', re.IGNORECASE)), ('18', re.compile(r'\b18(YR)?\b|\b18YEAR\b', re.IGNORECASE)), ('25 Astar', re.compile(r'\bAstar\b', re.IGNORECASE)), ('25', re.compile(r'\b25(YR)?\b', re.IGNORECASE)), ('Companta', re.compile(r'\bCompanta\b', re.IGNORECASE)), ('Finealta', re.compile(r'\bFinealta\b', re.IGNORECASE)), ('Milsean', re.compile(r'\bMilsean\b', re.IGNORECASE)), ('Sonnalta', re.compile(r'\bSonnalta\b', re.IGNORECASE)), ], 'zScotch Macallan' : [ ('10 Fine', re.compile(r'\bFine.*\b10\b|\b10.*Fine')), ('10', re.compile(r'\b10\b')), ('12 Double Gold', re.compile(r'\bDbl\b.*Gold|\bDouble\b.*Gold', re.IGNORECASE)), ('12 Double', re.compile(r'\bDouble\s.*12(YR)?\b', re.IGNORECASE)), ('12 Double', re.compile(r'\b12\s.*Double\b', re.IGNORECASE)), ('12 Double', re.compile(r'\bDbl\b|\bDouble\b', re.IGNORECASE)), ('12 Edition 1', re.compile(r'\bEdition\s.*1\b', re.IGNORECASE)), ('12 Edition 2', re.compile(r'\bEdition\s.*2\b', re.IGNORECASE)), ('12 Edition 3', re.compile(r'\bEdition\s.*3\b', re.IGNORECASE)), ('12 Edition 4', re.compile(r'\bEdition\s.*4\b', re.IGNORECASE)), ('12 Sherry', re.compile(r'\b12\s.*Sherry\b|\bSherry\b\s.*\b12', re.IGNORECASE)), ('12 Triple', re.compile(r'\b12(YR)?\s.*Triple\b', re.IGNORECASE)), ('12 Triple', re.compile(r'\bTriple\s.*12\b', re.IGNORECASE)), ('12', re.compile(r'\b12(YR)?\b', re.IGNORECASE)), ('15 Triple', re.compile(r'\b15(YR)?\s.*Triple\b|Triple.+\b15(YR)?\b', re.IGNORECASE)), ('15 Fine', re.compile(r'\b15(YR)?\b.*\bFine\b', re.IGNORECASE)), ('15', re.compile(r'\b15(YR)?\b', re.IGNORECASE)), ('17 Sherry', re.compile(r'\b17(YR)?\s.*Sherry\b', re.IGNORECASE)), ('17 Fine', re.compile(r'\b17(YR)?\b.*\bFine\b', re.IGNORECASE)), ('17', re.compile(r'\b17(YR)?\b', re.IGNORECASE)), ('18 Sherry', re.compile(r'\b18(YR)?\s.*Sherry\b|Sherry\b.*18', re.IGNORECASE)), ('18 Triple', re.compile(r'\b18(YR)?\s.*Triple\b|Triple.+\b18(YR)?\b', re.IGNORECASE)), ('18 Fine', re.compile(r'\b18(YR)?\b.*\bFine\b', re.IGNORECASE)), ('18 Gran', re.compile(r'Gran\b.*\b18', re.IGNORECASE)), ('18', re.compile(r'\b18(YR)?\b', re.IGNORECASE)), ('21 Fine', re.compile(r'\b21.*Fine\b', re.IGNORECASE)), ('21', re.compile(r'\b21(YR)?\b', re.IGNORECASE)), ('25 Sherry', re.compile(r'\b25\s.*Sherry\b', re.IGNORECASE)), ('25', re.compile(r'\b25(YR)?\b')), ('30 Sherry', re.compile(r'\b30\s.*Sherry', re.IGNORECASE)), ('30 Triple', re.compile(r'\b30(YR)?\s.*Triple\b|Triple.+\b30(YR)?\b', re.IGNORECASE)), ('30 Fine', re.compile(r'\b30(YR)?\b.*\bFine\b|Fine.*30', re.IGNORECASE)), ('30', re.compile(r'\b30(YR)?\b')), ('Rare', re.compile(r'\bRare\b', re.IGNORECASE)), ], 'zTeq Cuervo' : [ ('Especial Gold', re.compile(r'\bEspecial\b.*Gold\b|Gold.*Especial', re.IGNORECASE)), ('Especial Blue', re.compile(r'\bEspecial\b.*Blue\b', re.IGNORECASE)), ('Especial', re.compile(r'\bEspecial\b', re.IGNORECASE)), ('Familia Platino', re.compile(r'\bPlatino\b', re.IGNORECASE)), ('Familia Anejo', re.compile(r'\bFamilia\b|\bReserva\b', re.IGNORECASE)), ('Gold', re.compile(r'\bGold\b', re.IGNORECASE)), ('Reposado Lagavulin', re.compile(r'\bReposado.*Lagavulin', re.IGNORECASE)), ('Tradicional Anejo', re.compile(r'Tradicional.*Anejo|Anejo.*Tradicional', re.IGNORECASE)), ('Tradicional Reposado', re.compile(r'Tradicional.*Reposado|Reposado.*Tradicional', re.IGNORECASE)), ('Tradicional Silver', re.compile(r'\bTradicional\b', re.IGNORECASE)), ('Tradicional Silver', re.compile(r'\bTraditional\b', re.IGNORECASE)), ('Reposado', re.compile(r'\bReposado\b', re.IGNORECASE)), ('Silver', re.compile(r'\bSilver\b', re.IGNORECASE)), ], 'zTeq Don Julio' : [ ('1942', re.compile(r'\b1942\b', re.IGNORECASE)), ('Real', re.compile(r'\bReal\b', re.IGNORECASE)), ('Anejo Claro 70th', re.compile(r'\b70th\b', re.IGNORECASE)), ('Anejo Claro', re.compile(r'\bAnejo\b\s*Claro\b', re.IGNORECASE)), ('Anejo', re.compile(r'\bAnejo\b', re.IGNORECASE)), ('Blanco', re.compile(r'\bBlanco\b', re.IGNORECASE)), ('Reposado Lagavulin', re.compile(r'\bRepo.+Lagvulin\b', re.IGNORECASE)), ('Reposado Dbl', re.compile(r'\bReposado.+Double\b', re.IGNORECASE)), ('Reposado Dbl', re.compile(r'\bReposado.+Dbl\b', re.IGNORECASE)), ('Reposado Dbl', re.compile(r'\bDouble.+Reposado\b', re.IGNORECASE)), ('Reposado Private', re.compile(r'\bReposado.+Private\b', re.IGNORECASE)), ('Reposado', re.compile(r'\bReposado\b', re.IGNORECASE)), ('Silver', re.compile(r'\bSilver\b', re.IGNORECASE)), ], 'zTeq Herradura' : [ ('Ultra', re.compile(r'\bUltra\b', re.IGNORECASE)), ('Suprema', re.compile(r'\bSuprema\b', re.IGNORECASE)), ('Anejo', re.compile(r'\bAnejo\b', re.IGNORECASE)), ('Blanco', re.compile(r'\bBlanco\b', re.IGNORECASE)), ('Reposado Gold', re.compile(r'\bReposado\s+Gold\b|\bGold\s+Reposado\b', re.IGNORECASE)), ('Reposado Scotch', re.compile(r'\bReposado.+Scotch\b|\bScotch.+Reposado\b', re.IGNORECASE)), ('Reposado Port', re.compile(r'\bPort.+Reposado\b|\bReposado.+Port\b', re.IGNORECASE)), ('Reposado', re.compile(r'\bReposado\b', re.IGNORECASE)), ('Silver', re.compile(r'\bSilver\b', re.IGNORECASE)), ], 'zTeq Patron' : [ ('Gran Piedra', re.compile(r'\bPiedra\b', re.IGNORECASE)), ('DELETE Roca DELETE', re.compile(r'\bRoca\b', re.IGNORECASE)), ('Anejo Extra Lalique', re.compile(r'\bLalique\b', re.IGNORECASE)), ('Anejo Extra 7yr', re.compile(r'\b7YR\b|\b7 anos\b|\b7 year\b', re.IGNORECASE)), ('Anejo Extra 5yr', re.compile(r'\b5YR\b|\b5 anos\b|\b5 year\b', re.IGNORECASE)), ('Anejo Extra 10yr', re.compile(r'\b10\b.+\bExtra\b|\bExtra\b.+10', re.IGNORECASE)), ('Anejo Extra', re.compile(r'\bExtra\s+Anejo\b', re.IGNORECASE)), ('Gran Anejo', re.compile(r'\bGran\s+Anejo\b', re.IGNORECASE)), ('Gran Anejo', re.compile(r'\bBurdeos\b', re.IGNORECASE)), ('Gran Smoky', re.compile(r'\bGran\s+.*Smoky\b', re.IGNORECASE)), ('Anejo', re.compile(r'\bAnejo\b', re.IGNORECASE)), ('Gran Platinum', re.compile(r'\bPlatinum\b', re.IGNORECASE)), ('Reposado', re.compile(r'\bReposado\b', re.IGNORECASE)), ('Silver LTD', re.compile(r'\bSilver.*Limited\b|\bLimited.*Silver\b', re.IGNORECASE)), ('Silver Estate', re.compile(r'\bEstate.*Silver\b|\bSilver.*Estate\b', re.IGNORECASE)), ('Silver', re.compile(r'\bSilver\b', re.IGNORECASE)), ('Blanco', re.compile(r'\bBlanco\b', re.IGNORECASE)), # ('', re.compile(r'\b\b', re.IGNORECASE)), ], 'zTeq Padre Azul' : [ ('Blanco', re.compile(r'\bsilver\b', re.IGNORECASE)), ], 'zWhiskey Balvenie' : [ ('12 Double', re.compile(r'\bDouble.*12(YR)?\b', re.IGNORECASE)), ('12 Double', re.compile(r'\b12(YR)?\s.*Double', re.IGNORECASE)), ('12 First', re.compile(r'\b12(YR)?\s.*First', re.IGNORECASE)), ('12 USA', re.compile(r'\b12.*American|American.*12', re.IGNORECASE)), ('12 Toast', re.compile(r'\b12(YR)?\s.*Toast', re.IGNORECASE)), ('12', re.compile(r'\b12(YR)?\b', re.IGNORECASE)), ('14 Carib', re.compile(r'\b14(YR)?\s.*Carib', re.IGNORECASE)), ('14 Carib', re.compile(r'\b14(YR)?\s.*CB\s+Cask', re.IGNORECASE)), ('14 Carib', re.compile(r'\bCarr?ib', re.IGNORECASE)), ('14 Peat', re.compile(r'\b14(YR)?\s.*Peat', re.IGNORECASE)), ('15 Sherry', re.compile(r'\b15(YR)?\s.*Sherry\b', re.IGNORECASE)), ('15 Sherry', re.compile(r'\bSherry\s+.*15(YR)?\b', re.IGNORECASE)), ('15', re.compile(r'\b15(YR)?\b', re.IGNORECASE)), ('16 Triple', re.compile(r'\b16(YR)?\s.*Triple\b', re.IGNORECASE)), ('17 Sherry Double', re.compile(r'\b17(YR)?\s.*Sherry\s+Doub', re.IGNORECASE)), ('17 Sherry', re.compile(r'\b17(YR)?\s.*Sherry', re.IGNORECASE)), ('17 Double', re.compile(r'\b17(YR)?\s.*Double', re.IGNORECASE)), ('17 Double', re.compile(r'\bDouble.*17(YR)?\b', re.IGNORECASE)), # 17 Double Sherry # 17 Islay # 17 New Oak ('17 Peat', re.compile(r'\b17(YR)?\s.*Peat', re.IGNORECASE)), ('17 Peat', re.compile(r'\bPeat.*17(YR)?\b', re.IGNORECASE)), ('17', re.compile(r'\b17(YR)?\b', re.IGNORECASE)), ('21 Port', re.compile(r'\b21.*Port', re.IGNORECASE)), ('21 Port', re.compile(r'\bPort.*21\b', re.IGNORECASE)), ('21', re.compile(r'21', re.IGNORECASE)), ('25', re.compile(r'\b25(YR)?\b', re.IGNORECASE)), ('30', re.compile(r'\b30(YR)?\b', re.IGNORECASE)), ('40', re.compile(r'\b40(YR)?\b', re.IGNORECASE)), ], 'zBourbon Woodford Res' : [ ('Dbl', re.compile(r'\bDouble\b', re.IGNORECASE)), ('Derby', re.compile(r'\bDerby\b', re.IGNORECASE)), ('Rye Choc', re.compile(r'\bChocolate.*Rye\b', re.IGNORECASE)), ('Rye', re.compile(r'\bRye\b', re.IGNORECASE)), ('Brandy', re.compile(r'\bBrandy\b', re.IGNORECASE)), ('Batch', re.compile(r'\bBatch\b', re.IGNORECASE)), ('Barrel', re.compile(r'\bBarrel\b', re.IGNORECASE)), ('Master', re.compile(r'\bMasters?\b', re.IGNORECASE)), ('Malt', re.compile(r'\bMalt\b', re.IGNORECASE)), ('Maple', re.compile(r'\bMaple\b', re.IGNORECASE)), ('Wheat', re.compile(r'\bWheat\b', re.IGNORECASE)), ('', re.compile(r'\bWoodford\b', re.IGNORECASE)), ], 'zSambuca' : [ ('Romana Black', re.compile(r'\bRomana.*\bBlack\b|\bBlack\s+Romana\b', re.IGNORECASE)), ('Romana', re.compile(r'\bRomana\b', re.IGNORECASE)), ('Di Amore', re.compile(r'\bdi Amore\b', re.IGNORECASE)), ], 'zScotch Hibiki' : [ ('12', re.compile(r'\b12\s*YE?A?R\b', re.IGNORECASE)), ('17 Limited', re.compile(r'\b17\s*YE?A?R\b.+Limited', re.IGNORECASE)), ('17', re.compile(r'\b17\s*YE?A?R\b', re.IGNORECASE)), ('21 Limited', re.compile(r'\b21\s*YE?A?R\b.+Limited', re.IGNORECASE)), ('21', re.compile(r'\b21\s*YE?A?R\b', re.IGNORECASE)), ('30', re.compile(r'\b30\s*YE?A?R\b', re.IGNORECASE)), ] } # regex to expand out optional values in the optoinal values to find a match against wine fld wineAbbrLookup = { '120-80' : r'\bOne\s+Twenty\s+Over\s+Eighty\b', '3Amigos' : r'\bThree\s+Amigos\b', '3Palms' : r'\bThree\s+Palms\b', '3Sister' : r'\bThree\s+Sisters?\b', '4Barrell' : r'\b4[\-\s]Barrels?\b', 'Alex' : r'\bAlexander\b', 'And' : r'\bAnderson\b', 'Car' : r'\bCarneros\b', 'Carries' : r'\bCarrie', 'CC' : r'\bC\.?C\.?\s+Ranch\b', 'Clone4' : r'\bClone\s+4\b', 'Clone6' : r'\bClone\s+6\b', 'Crossbarn' : r'\bCross\s+Barn\b', 'Donna' : r'\bDonna', 'Est' : r'\bEstate\b', 'Estate' : r'\bEst\b', 'Gap' : r'\bGap|\s%27Gap', 'Gary' : r'\bGary', 'Julia' : r'\bJulia', 'Knights' : r'\bKnight', 'KistlerVnyd' : r'\bKistler (Vineyard|VYD|EST)\b', 'LP' : r'\bLes Pierres\b', 'Lyn' : r'\bLyndenhur?st\b', 'Mont' : r'\bMonterey\b', 'Mt' : r'\bMount\b|\bMt\.\b', 'Napa/Son' : r'\bNapa.*Son', 'Oak' : r'\bOakville\b', 'One-Pt-5' : r'\bOne\s+Point\s+Five\b', 'Pomm' : r'\bPommeraie\b', 'Priv' : r'\bPrivate\b', 'RR' : r'\bRussian\s+Rivers?\b|RRV', 'RRR' : r'\bRussian\s+Rivers?\b|RRV', 'Res' : r'\bReserve\b|\bRsv\b|\bResrv\b|\bReserv\b|\bReserve$', 'Rose' : r'\bRos&#233;|\bROS&EACUTE;|\bRos%E9', 'Ruth' : r'\bRutherford\b', 'Sandy' : r'\bSandy', 'Samanthas' : r'\bSamantha', 'SC' : r'\bSanta\s+Cruz\b', 'SLD' : r'\bStag.*Leap\b', 'SLH' : r'\bSanta\s+Lucia\b', 'SMV' : r'\bSanta\s+Maria|\bS\s+Maria', 'SRH' : r'\bSTA\.?|\bSANTA\s+Rita\b|\bSTA\sRITA\sHILLS|\bS\s+RITA\b', 'SS' : r'\bSpecial\s+\Selection\b', 'Stage' : r'\bStagecoach\b', 'Son' : r'\bSonoma\b', 'SYV' : r'\bSanta\s+Ynez\s+Valley\b', 'TD9' : r'\bTD\s+9\b|\bTD-9\b', 'Terraces' : r'\bTerrace', 'TheCutrer' : r'\bThe Cutrer\b|nnay Cutrer\b', 'Tok' : r'\bTo[\s\-]?Kolan|\bTo[\s\-]?Kalon', 'Turn4' : r'\bTurn\s+4\b', 'Vernas' : r'\bVerna', 'Vine' : r'\bVines\b', 'Yount' : r'\bYountville\b', 'ZThree' : r'\bZ.*\bThree\b', 'ZCuvee' : r'\bZ.*\bCuvee\b|\bCuvee Z\b', # misspellings 'Agustina' : r'\bAugustina\b', 'Durell' : r'\bDurrell\b', 'Benchland' : r'\bBenchlands\b', 'Pritchard' : r'\bPitchard\b', } # regex search - set the ships as reShipsAs = re.compile(r'\(ships?\s', re.IGNORECASE) # the order in which we pull multiple single match attributes defaultorderlist=[['Tok'], ['Oak'], ['Res'], ['RR'], ['Landslide'], ['Yount'], ['RRR'], ['Son'], ['Ruth'], ['Napa'], ['Helena'], ['SRH'], ['SLH'], ['SMV'], ['SLD'], ['Paso'], ['Alex'], ['Single'], ['Estate']] ### FUNCTIONS ############################################ ######################################################################################### def globalVariableCheck( debug=False ): # check for liquor definitions that are in noGrapeLookup # these will never execute for liquor in liquorLookup: if liquor in noGrapeLookup: print('WARNING:liquorLookup regexs will never execute - they are in noGrapeLookup:', liquor) if liquor in ignoreGrapeLookup: print('WARNING:liquorLookup regexs will never execute - they are in ignoreGrapeLookup:', liquor) for winery in ignoreGrapeLookup: if winery in noGrapeLookup: print('WARNING:ignoreGrapeLookup regexs will never execute - they are in noGrapeLookup:', winery) ######################################################################################### def setOptionDictMasterFldValues( optiondict, debug=False ): # default these fields to the fld values if they are not set # otherwise leave them alone for fld in ('fldWine', 'fldWineDescr'): if not optiondict[fld+'Master']: optiondict[fld+'Master'] = optiondict[fld] ######################################################################################### # having a list of names to look at and match on - see if this record has a match # nameLookup - list of names could have 'None' as the last value, or just the value of None # lookupStr - string to be searched # other - array of strings that will have the matching name removed from # msg - string defining who called this function # # returns: string - if a matching string is found # None - did not find a match # '' - valid match with "None" # def wineLookupByName( nameLookup, lookupStr, other, msg, wineAbbrLookup=None, debug=False ): # string for debugging messages funcname = 'wineLookupByName:' + msg + ':' # debugging if debug: print(funcname + 'nameLookup:', nameLookup) # if the value for this winery is None - than there is no additiona work we are done if nameLookup is None: # no additional processing # debugging if debug: print(funcname + 'match: value is none - continue on') # return empty string return '' # there are additional lookups for this winery - not using grape as part of the description # check each of the things to look up for name in nameLookup: # debugging if debug: print(funcname + 'match-name:', name) # special processing of a lookup value of none if name is None: # Lookup on none - means just use what we found # debugging if debug: print(funcname + 'name-matched: value is none - continue on:pass back blank') # stop iterating on nameLookup - by returning empty string return '' # we have not encountered 'None' - so build the regex based on the text provided reName = re.compile( r'\b'+name+r'\b', re.IGNORECASE) # check to see if we have a match with this regex if reName.search(lookupStr): # we have a match - so this is the additional attribute we are looking for # debugging if debug: print(funcname+'name-MATCHED:', name) # remove from other if it is in there for val in other: if reName.search(val): other.remove(val) # debugging if debug: print(funcname + 'name-remove-from-other:', val) # stop iterating on nameLookup - return what we found return name # 2nd check see if have a translation and this name is translatable if wineAbbrLookup and name in wineAbbrLookup: # build the regex with the look up value reName = re.compile(wineAbbrLookup[name], re.IGNORECASE) # debugging if debug: print(funcname + 'Abbr-match-name:', name) # check to see if we have a match with this regext if reName.search(lookupStr): # we have a match - so this is the additional attribute we are looking for # debugging if debug: print(funcname+'Abbr-name-MATCHED:', wineAbbrLookup[name]) # remove from other if it is in there for val in other: if reName.search(val): other.remove(val) # debugging if debug: print(funcname + 'name-remove-from-other:', val) # stop iterating on nameLookup - return what we found return name # checked all the namelookupd - and did not find any matches # debuging if debug: print(funcname + 'name match not found:set to blank') # return none meaning we did not find a match return None ######################################################################################### # find the qualifer like gift, etch, glass tied to this string # # # # returns: first qualifier or None # def findQualifier( wine, debug=False ): for (val, reSearch) in reQualLookup: if reSearch.search(wine): if debug: print('findQualifier:matched-returning:', val) return val if debug: print('findQualifier:no-match-returning:', None) return None ######################################################################################### # find the winery tied to the rec # # Global Variable Used: wineryLookup (an array of regex that define the winery) # # returns: (winery, reWinery) # def findWinery( rec, lastWinery, lastReWinery, fldWine, debug=False ): # if we had a prior winery - test for this match first if lastWinery: # debugging if debug: try: print('fw:new winery:', rec[fldWine]) except Exception as e: print('debug error8-continuing:', str(e)) print('rec[fldWine]:type:', type(rec[fldWine])) # print('fw:new winery:', rec[fldWine].decode('windows-1252')) print('fw:checking if this is lastWinery:', lastWinery) # check to see if the winery is a match again for this record if lastReWinery.search(rec[fldWine]): # debugging if debug: print('fw:this matches the last winery') # match again - return values return(lastWinery, lastReWinery) else: # not match - debugging if debug: print('fw:not last winery') # if we did not match lastWinery - lets look through the list # go through the list of wineries (global variable), # each row contains wineryName, wineryRegex # pulling out the tuple from the lookup for (winery, reWinery) in wineryLookup: # debugging if debug: print('fw:not lastWinery-checking winery:', winery) if fldWine not in rec: print('not a column in this record fldWine:', fldWine) print('rec:', rec) # check to see if this winery is a match if reWinery.search(rec[fldWine]): # debugging if debug: print('fw:winery match found:', winery) # this is a match - set the variables return (winery, reWinery) # for loop ends without a match # did not find a matching winery in the for loop - clear values return (None, None) ######################################################################################### # find the liquor tied to the rec, leveraging the winery # Global Variable Used: liquorLookup # # returns: (liquor, reLiquor) # def findLiquor( rec, winery, fldWine, debug=False ): # go through the list of liquors (global variable), pulling out the tuple from the lookup for (liquor, reLiquor) in liquorLookup[winery]: # debugging if debug: print('fl:checking liquor:', liquor) # check to see if this liquor is a match if reLiquor.search(rec[fldWine]): # debugging if debug: print('fl:liquor match found:', liquor) # this is a match - set the variables return (liquor, reLiquor) # for loop ends without a match # did not find a matching liquor in the for loop - clear values return (None, None) ######################################################################################### # find the grape tied to the rec by regex evaluation # # Global Variable Used: grapeLookup # # returns: (grape, reGrape) # def findGrapeByRegex( rec, fldWine, debug=False ): # go through the list of liquors (global variable), pulling out the tuple from the lookup for (grape, reGrape) in grapeLookup: # debugging if debug: print('fgbr:grape:', grape) # check to see if this liquor is a match if grape is not None and reGrape.search(rec[fldWine]): # debugging if debug: print('fgbr:grape match found:', grape) # this is a match - set the variables return (grape, reGrape) # for loop ends without a match # did not find a matching grape in the for loop - clear values return (None, None) ######################################################################################### # find a string in a field of a record using string match and # on match, return that it matched and the remainder of the string as an array # # returns: (findStr, other) # def findStrInRecReturnOther( rec, fldWineDescr, findStr, debug=False ): # find where in the string this findStr is positioned matchLoc = rec[fldWineDescr].find(findStr) # if we found a location if matchLoc > -1: # then strip everthing to the left of the findStr value and then split this to create other attributes other = rec[fldWineDescr][matchLoc+len(findStr)+1:].split() # debugging if debug: print('fsirro:findStr matched:', findStr) if debug: print('fsirro:findStr other:', other) # return what we found return (findStr, other) #no match found - debugging if debug: print('fsirro:findStr did not match using:', findStr) # did not find a matching findStr - return that fact return (None, []) ######################################################################################### # find the grape tied to the rec and the list of other attributes # to the right of the grape in that description # # Global Variable Used: grapeLookup # # returns: (grape, other) # def findGrapeByStr( rec, fldWineDescr, debug=False ): # find the grape and strip everything right of that from the fldWineDescr field for (grape,reGrape) in grapeLookup: # debugging if debug: print('fg:grape:', grape) # find where in the string this grape is positioned (grape, other) = findStrInRecReturnOther( rec, fldWineDescr, grape, debug=debug) # if we have a match return that match if grape: return (grape, other) # did not find a matching grape - return that fact return (None, []) ######################################################################################### # find the vintage tied to the rec # # Global Variable Used: vintageLookup # # returns: vintage # def findVintage( rec, fldWine, debug=False ): # loop through the vintage lookup records for reVintage in vintageLookup: # search for match m = reVintage.search(rec[fldWine]) # if there is a match if m: # extract the vlaue from the first regex group with a value if m.group(1): vintage = m.group(1) if debug: print('fv:vintage-match:', reVintage,':group1') elif m.group(2): vintage = m.group(2) if debug: print('fv:vintage-match:', reVintage,':group2') elif m.group(3): vintage = m.group(3) if debug: print('fv:vintage-match:', reVintage,':group3') else: vintage = m.group(4) if debug: print('fv:vintage-match:', reVintage,':group4') # return what we vound return vintage # did not find it return None ######################################################################################### # Create the winery/grape-wine-liquour conversion table based on the # array of records passed in # # this routine takes the already read in list of definitions and parses them up # in order to create a winery-wine-attributes file - that will be used # later to take new records from searching the internet and properly assign # an aligned/consistent wine description to that wine string # # we expect the wines array to have attributes: fldWineDescr (winedescr), and fldWine (wine_name) # # returns: wgLookup - dictionary - which is built from parsing winedescr NOT wine_name # # wgLookup[winery][grape] = list of lists of attributes to perform lookups with # def buildWineryGrapeLookup( wines, fldWineDescr='winedescr', fldWine='wine', debug=False ): # local variables wgLookup = {} lastWinery = None lastReWinery = None # step through the records read in for rec in wines: # debugging if debug: print('bwgl:new rec:', rec[fldWineDescr]) # set the variable if not fldWineDescr in rec: print('creating-field:', fldWineDescr) rec[fldWineDescr] = '' # local loop variables winery = grape = wine = liquor = None other = [] ### WINERY (lastWinery, lastReWinery) = (winery, reWinery) = findWinery( rec, lastWinery, lastReWinery, fldWine, debug=debug ) # if we did not find the winery - skipt this record if not winery: # debugging if debug: print('bwgl:did not find winery-skipping:', rec[fldWine]) # don't process this record - get the next record to process continue ### IGNOREGRAPE and NOGRAPE and LIQUOR # if this winery has a noGrapeLookup option - use that to split up the record if winery in ignoreGrapeLookup: ### BLANK WINE # don't get the grape for this winery # set wine to blank wine = '' # debugging if debug: print('bwgl:wine check ignoreGrapeLookup on winery:', winery) elif winery in noGrapeLookup: ### NO GRAPE WINE -- fldWineDescr # debugging if debug: print('bwgl:wine check noGrapeLookup on winery:', winery) # find which wine is a match from the noGrapeLookup wine = wineLookupByName( noGrapeLookup[winery], rec[fldWineDescr], [], 'noGrapeLookup', debug=debug ) # not getting a match - we want to continue to have the wine as blank if False and wine == '': # debugging if debug: print('bwgl:nograpelookup:no-match:set wine to None') wine = None elif winery in liquorLookup: ### LIQUOR ---- fldWine # debugging if debug: print('bwgl:liquor check on winery:', winery) # see if a liquor matches (liquor, reLiquor) = findLiquor( rec, winery, fldWine, debug=debug ) # if we found match - populate wine so we don't look for grape if liquor is not None: wine = liquor # debugging if debug: print('bwgl:liquor found and put in wine:', wine) ### GRAPE (if we have not filled in wine) --- fldWineDescr if wine is None: # debugging if debug: print('bwgl:grape check because wine is None') # determine if there is a grape in this string # if ther (grape,other) = findGrapeByStr( rec, fldWineDescr ) # debugging if debug: print('bwgl:grape:', grape, ':other:', other) else: # debugging if debug: print('bwgl:grape check skipped - we have a wine') ### Skip this record if we don't have a wine or a grape if wine is None and grape is None: # debugging if debug: print('bwgl:record skipped - no grape or wine defined') continue ### OTHER (if not already created by grape lookup) ---- fldWineDescr # # if we did not find the grape in the string # so other was not populated # we need to look up other using 'winery' as the filter if grape is None: # debugging if debug: print('bwgl:build other from winery') # find where in the string this grape is positioned (wineryFind, other) = findStrInRecReturnOther( rec, fldWineDescr, winery, debug=debug) ### OTHER Additional Processing # remove CASE - the keyword case if it exists if 'case' in other: other.remove('case') # debugging if debug: print('bwgl:remove case from other') # remove VINTAGE and/or BOTTLESIZE and/or other QUALIFIERS # the last element will either be the vintage (no bottle size) # or will be the bottle size and then next is the vintage # if the last position is not vintage, attempt to remove the bottle size # then remove vintage - this should be the vintage (validated by isdigit lookup) if other: if debug: print('bwgl:looking at other for quals, bottlesize and vintage') # remove qualifiers if exist if not other[-1].isdigit(): # first we check to see if there is a qualifier appended # we are not vintage as the position posiition - see if it is size for qual,reQual in reQualLookup: if qual == other[-1]: if debug: print('bwgl:remove qualifier from other:', qual) del other[-1] break # remove bottle size if exist if other and not other[-1].isdigit(): # we are not vintage as the position posiition - see if it is size for size,reSize in sizeLookup: if size == other[-1]: if debug: print('bwgl:remove bottlesize from other:', size) del other[-1] break # remove vintage if it is there if other and other[-1].isdigit(): # first check to see if this is part of the ignore grape solution if winery in ignoreGrapeLookup and ignoreGrapeLookup[winery]and other[-1] in ignoreGrapeLookup[winery]: if debug: print('bwgl:value is in ignoreLookupGrape - keeping it:', other[-1]) else: # debugging if debug: print('bwgl:remove vintage from other:', other[-1]) del other[-1] # remove WINE - the element if the element is the same as the wine if wine and wine in other: other.remove(wine) # debugging if debug: print('bwgl:remove wine from other:', wine) # debugging if debug: try: print('bwgl:Final-Build:', winery, ':', grape, ':', wine, ':', liquor, ':', other, ':', rec[fldWineDescr], ':', rec[fldWine]) except Exception as e: print('debug error2-continuing:', str(e)) print('fldWine:', fldWine) ### BUILD LOOKUP FOR CONVERSION (we use the grape attribute to build the dictionary) # move liquor value into grape because we did not find the if grape is None and wine is not None: grape = wine # debugging if debug: print('bwgl:set-grape-to-wine:', grape) ### WINERY:GRAPE-WINE-LIQOUR Dictionary creation # debugging if debug: print('bwgl:create wgLookup for winery:', winery, ':grape:', grape) # validate we have an entry for this winery in the lookup dict if winery not in wgLookup: # one does not create - so create a stub for winery:grape wgLookup[winery] = { grape : [] } else: # one DOES exist - check to see if the grape is already here if grape not in wgLookup[winery]: # grape is not here - so create an empty list to stuff values into wgLookup[winery][grape] = [] # check to see if we have OTHER attributes # and if we do - check to see that this list of attributes # is not already in the wineLookup array # and if this list does not exist - then append this list if other and other not in wgLookup[winery][grape]: # add this list of other to this entry wgLookup[winery][grape].append(other) # debugging if debug: print('bwgl:appending to wgLookup:other:', other) # end loop on wines ### SORTED WINERY:GRAPE lookup - most optional attributes first in the list # debbuging if debug: print('bwgl:complete-read-of-master-file:sort wgLookup') # now sort the list of lookups from most specific (greatest number of attributes) to least for winery in wgLookup: for grape in wgLookup[winery]: wgLookup[winery][grape] = sorted(wgLookup[winery][grape], key=len, reverse=True) # debugging if debug: print('\n'*5) print('START WGLOOKUP DUMPED') print('#'*80) if ppFlag: pp.pprint(wgLookup) else: print('bwgl:final-wgLookup:\n', wgLookup) print('#'*80) # done with for loop - return the lookup return wgLookup ######################################################################################### # find the matching set of additional attributes that match this record # from the global lookup. # # we assume that we have already tested that winery and value exist in wgLookup prior to calling this routine # # the special paramaters here are: # value - this is either "wine" or "grape" - this routine allows you to lookup on different attributes # valueDescr - passed in string for debugging telling us which value was passed in # # defaultorderlist = array of array of string - gives the default order of singlematch looks to determine which of # many matches is the one we will select # # Global Variable Used: wgLookup # # returns: valuematchset array selected # def findAddAttribWgLookup( rec, winery, value, fldWine, AbbrLookup=[], defaultorderlist=None, valueDescr='', debug=False ): # local variable - capture all the entries that are single match entries singlematch=[] # debugging if debug: try: print('faawl:value:', valueDescr, ':match-wgLookup:', rec[fldWine], ':', wgLookup[winery][value]) except Exception as e: print('debug error7-continuing:', str(e)) print('fldWine:', fldWine) # for each set of values that could be a match for valuematchset in wgLookup[winery][value]: # debugging if debug: print('faawl:testing valuematchset:', valuematchset, ':length:', len(valuematchset)) # set the flag to start allmatch = True # loop through the set of values that make up this set for valuematch in valuematchset: # for each entry - build a regex and test it and add it up # we need all values in this valueset to be true for this valueset to be match reMatch1 = re.compile(r'\b'+valuematch+r'\b', re.IGNORECASE) reMatch2 = re.compile(r'\s'+valuematch+r'\s', re.IGNORECASE) # check to see if this regex is a match m1 = reMatch1.search(rec[fldWine]) m2 = reMatch2.search(rec[fldWine]) if m1 or m2: # this regex is a match allmatch = True and allmatch elif valuematch in AbbrLookup: # this regex was not a match - but we want to check if the value also has # a translation - and if it has a translation - then we test the translation also # the value did not work but there is an alternate value to check # debugging if debug: print('faawl:valuematch-abbr:', valuematch, ':', wineAbbrLookup[valuematch]) # create the regex reMatch = re.compile(wineAbbrLookup[valuematch], re.IGNORECASE) # test the regex and attach the results to allmatch allmatch = reMatch.search(rec[fldWine]) and allmatch else: # not a match - update allmatch allmatch = False and allmatch # debugging if debug: print('faawl:valuematch:', valuematch, ':allmatch:', allmatch) # check to see if all matched if allmatch: # all matched - so this is a match - so break out of the valuematchset group # debugging if debug: print('faawl:value matched:', valuematchset) # different action based on # of items being match if len(valuematchset) == 1: # debugging if debug: print('faawl:single-valuematch-set-added-to-singlematch:', valuematchset) # single value matching - we don't stop when we find a match singlematch.append(valuematchset) else: # debugging if debug: print('faawl:multivalue-valuematch-set-found:done') # multi value match so we are done when we find a match - so return return valuematchset # did not find matchset in the for loop - check to see if we have singlematch if not singlematch: # debugging if debug: print('faawl:exit with singlematch NOT populated return blank') # did not have singlematch found - we are done - return empty return [] # singlematch populated # debugging if debug: print('faawl:exit with singlematch populated:', singlematch) # check to see how many matches we got if len(singlematch) == 1 or not defaultorderlist: # debugging if debug: print('faawl:return first entry in singlematch:', singlematch[0]) # if there is only one entry in here # or we don't have a default order so we pick the first found # and we set the value to this return singlematch[0] # we need to define which of the singlematch values we will return # the defaultorderlist will be used to set that ordering # # create a local copy of the list that can be changed in this routine defaultorder = defaultorderlist[:] # multiple singlematch values so lets find and pick the best one # debugging if debug: print('faawl:multiple single match value-singlematch:', singlematch) # get the values from singlematch that are not in defaultorder # and put them at the start of defaultorder list # go in reverse order when doing this lookup for val in singlematch[::-1]: if val not in defaultorder: defaultorder.insert(0,val) ### HARDCODED ### # very short term fix - we need to prioritze these single tags (mondavi problem) if winery == 'Mondavi' and ['Tok'] in singlematch: if debug: print('faawl:Change from:', valuematchset, ':to Tok for mondavi') return ['Tok'] # find the first matching value from priority order list for val in defaultorder: if val in singlematch: # debugging if debug: print('faawl:selected-singlematch-value:', val) # we found the first match - set it and break out return val # debugging if debug: print('faawl:valuematchset-empty') # did not match - return empty return [] ######################################################################################### # create a consistent wine name for a list or records with store based wine descriptions # # the special paramaters here are: # wgLookup - dictionary of winery, wine, list of wines # wines - list of records to be processed # # Global Variable Used: ignoreGrapeLookup, noGrapeLookup, wineAbbrLookup, liquorLookup # reCase, sizeLookup # # returns: [updated values in teh wines array] # #### Use the winery/grape-wine-liquour conversion table to define a wine description for the records def setWineryDescrFromWineryGrapeLookup( wgLookup, wines, fldWineDescr = 'winedescr', fldWine = 'wine', fldWineDescrNew = 'winedescrnew', fldWineDescrMatch=False, debug=False ): if debug: print('\n'*10,'START WINEDESCR SETTING HERE ---------------------------------------------') # step through all the records passed in for rec in wines: # local variables winery = grape = wine = vintage = case = size = liquor = nongrape = qual = None winematchset = grapematchset = [] # debugging if debug: try: print('setWinery:fldWine:', rec[fldWine]) except Exception as e: print('debug error2-continuing:', str(e)) print('fldWine:', fldWine) # make the field if it does not exist if fldWineDescrNew not in rec: rec[fldWineDescrNew] = rec[fldWineDescr] ### WINERY (winery, reWinery) = findWinery( rec, None, None, fldWine, debug=debug ) # validate the winery if winery is None: ### WINERY NONE - go to next record # debugging if debug: print('setWinery:winery not found-next record:' + rec[fldWine]) # get the next record continue elif winery not in wgLookup: ### WINERY NOT IN LOOKUP # skip this record - nothing to process # debugging if debug: print('setWinery:winery not in wgLookup:', winery) continue ### GRAPE # find the grape that is this record (grape, reGrape) = findGrapeByRegex( rec, fldWine, debug=debug ) # debugging if debug: print('setWinery:grape found:', grape) ### OVERRIDES if winery in ignoreGrapeLookup: ### IGNORE GRAPE # debugging if debug: print('setWinery:winery-match-ignoreGrape:clear-wine:set-grape-to-None:set-nongrape-True:winery:', winery) # clear wine and grape wine = '' # clear the grape field grape = None # set the liquor flag to control processing nongrape = True if winery in noGrapeLookup: ### NOGRAPE - WINE # debugging if debug: print('setWinery:noGrapeLookup wine check:', winery) # do the lookup and if a search is a match on None take appropriate action wine = wineLookupByName( noGrapeLookup[winery], rec[fldWine], [], 'noGrapeLookup', wineAbbrLookup, debug=debug ) # debugging if debug: print('setWinery:nogrape check:wine:', wine) # test the value we got back if wine == '': # debugging if debug: print('setWinery:noGrapeLookup:matched:None::clear grape:set nongrape to True') # the lookup match None - so we want to ignore any grape found and we blank out the wine grape = None wine = '' nongrape = True elif wine: # matched a wine - so clear the grape value grape = None # debugging if debug: print('setWinery:nograpeLookup:wine found - clear grape field') if wine is None and winery in liquorLookup: ### LIQUOR # debugging if debug: print('setWinery:liqourLookup:', winery) (liquor, reLiquor) = findLiquor( rec, winery, fldWine, debug=debug) # if we found something update wine to be what we found if liquor is not None: wine = liquor # debugging if debug: print('setWinery:liquorLookup-match:', liquor) if not grape and not nongrape and not wine and liquor is None: # NO GRAPE - and not connected to noGrapeLookup or liquorLookkup # get the next record # debugging if debug: print('setWinery:did not find grape-skipping record:', rec[fldWineDescr]) continue # debugging if debug: print('setWinery:pre-vintage found values for wine/liquor:', wine, ':grape:', grape) ### VINTAGE vintage = findVintage( rec, fldWine, debug=debug ) # debugging if debug: print('setWinery:vintage:', vintage) ### CASE information if reCase.search(rec[fldWine]): case = 'case' ### BOTTLE SIZE - get the size information for (size, reSize) in sizeLookup: # debugging if debug: print('setWinery:sizeLookup:',size) if reSize.search(rec[fldWine]) and not reShipsAs.search(rec[fldWine]): # debugging if debug: print('setWinery:sizeLookup:matched:',reSize) break else: size = None if debug: print('setWinery:sizeLookup:None-found') ### QUAL for this wine qual = findQualifier(rec[fldWine], debug=debug) # debugging if debug: try: print('setWinery:FinalAttributes:', winery, ':', grape, ':', wine, ':', liquor, ':', vintage, ':', case, ':', size, ':', qual, ':', rec[fldWine]) except Exception as e: print('debug error5-continuing:', str(e)) print('fldWine:', fldWine) ### WINE - ADDITIONAL INFORMATION if liquor is not None: # debugging if debug: print('setWinery:liquor flag set - no additional data needs to be collected') elif wine is not None: # debugging if debug: print('setWinery:wine is not None - do additional lookups:wine:', wine) # we found a wine / liquor - so see if there are additional attributes if wine in wgLookup[winery] and wgLookup[winery][wine]: # debugging if debug: print('setWinery:lookup winematchset') # there is one or more additional lookups for this winery/wine winematchset = findAddAttribWgLookup( rec, winery, wine, fldWine, wineAbbrLookup, None, valueDescr='wine', debug=debug ) else: # wine not in wgLookup so thing to work print('setWinery:unable to perform wgLookup on winery:', winery, ':wine:', wine, ':rec-wine:', rec[fldWine]) # debugging if debug: try: print('wgLookup[winery]:', wgLookup[winery]) except Exception as e: print('debug error3-continuing:', str(e)) print('winery:', winery) # debugging - wine is not None - what is the final winematchset if debug: print('setWinery:winematchset:', winematchset) elif grape is not None: # debugging if debug: print('setWinery:grape is not None - do additional lookups:', grape) # grape was returned (not wine) so do the lookup on grape if grape in wgLookup[winery] and wgLookup[winery][grape]: # see if we can create a match based on attributes and the grape grapematchset = findAddAttribWgLookup( rec, winery, grape, fldWine, wineAbbrLookup, defaultorderlist, valueDescr='grape', debug=debug ) elif grape in wgLookup[winery]: # do nothing this is a empty set if debug: print('setWinery:grape match: matching record set is blank - no action required') else: # wine not in wgLookup so thing to work # debugging print('setWinery:grape NONMATCH:', rec[fldWine]) if debug: print('setWinery:liquor:', liquor, ':wine:', wine, ':grape:', grape, ':wgLookup[winery]:', wgLookup[winery]) # debugging - wine is not None - what is the final grapematchset if debug: print('setWinery:grapematchset:', grapematchset) ### check the matchsets we got back - if any of them look like vintage values ### remove them from the string and look at up vintage again if vintage: newVintageLookupWine = rec[fldWine] for matchvalue in winematchset: if vintage in matchvalue: newVintageLookupWine = newVintageLookupWine.replace(matchvalue,'') if debug: print('setWinery:2nd-vintage:winematchset:wine-name-removal:', matchvalue) for matchvalue in grapematchset: if vintage in matchvalue: newVintageLookupWine = newVintageLookupWine.replace(matchvalue,'') if debug: print('setWinery:2nd-vintage:grapematchset:wine-name-removal:', matchvalue) if newVintageLookupWine != rec[fldWine]: if debug: print('setWinery:2nd-vintage:newVintageLookupWine:', newVintageLookupWine) newVintage = findVintage( { fldWine : newVintageLookupWine}, fldWine, debug=debug ) if debug: print('setWinery:2nd-vintage:newVintage:', newVintage) vintage = newVintage ### FINAL WINEDESCR # create initial value wineDescr = '' # if winery starts with a z then we don't have a vintage if winery.startswith('z'): vintage = None # debugging if debug: print('setWinery:winery starts with z: clear vintage') # quick test - does the wine and the winematchset the same if winematchset and ' '.join(winematchset) in wine: #debugging if debug: print('setWinery:clearing-winematchset:', winematchset,':is-in-wine:', wine) winematchset = [] if grapematchset and ' '.join(grapematchset) in grape: #TODO - work around for single letter matches if not (len(grapematchset)==1 and len(grapematchset[0])==1): #debugging if debug: print('setWinery:clearing-grapematchset:',grapematchset,':is-in-grape:', grape) grapematchset = [] if grapematchset and size and size in ' '.join(grapematchset): size = '' if winematchset and size and size in ' '.join(winematchset): size = '' if debug: print('setWinery:vallist1:', [winery, grape, wine] + grapematchset + winematchset + [vintage, size, qual, case]) print('setWinery:vallist2:', [winery, grape, wine, *grapematchset, *winematchset, vintage, size, qual, case]) # create a list wdList= [] # step through the values for val in [winery, grape, wine] + grapematchset + winematchset + [vintage, size, qual, case]: # and if there is a value add to the list - otherwise skip if val: wdList.append(val) # build the wine description by joining all these values together wineDescr = ' '.join(wdList) # debugging if False: if debug: print('setWinery:wdList:', wdList) if debug: print('setWinery:wineDescr:', wineDescr) # debugging if debug: try: print(':'.join(['setWinery:wineDescrList', wineDescr, rec[fldWineDescr], str(wineDescr==rec[fldWineDescr]), rec[fldWine]]) ) except Exception as e: print('debug error6-continuing:', str(e)) print('fldWine:', fldWine) # fill thew new value into the array rec[fldWineDescrNew] = wineDescr # fill in the matching field if fldWineDescrMatch: rec[fldWineDescrMatch] = (rec[fldWineDescr] == rec[fldWineDescrNew]) ######################################################################################### # set any digit only field to the word passed def setDigitFld2Value( wines, fld, value, debug=False ): for rec in wines: if rec[fld].isdigit(): rec[fld] = value ######################################################################################### # validate the field settings match the file we read in for update def updateFileOptionDictCheck( optiondict, wines, header, debug=False ): # check to see if the description field is in the file we read in if optiondict['fldWineDescr'] not in wines[0]: if debug: print('updateFileOptionDictCheck:fldWineDescr NOT in file read in:', optiondict['fldWineDescr']) # field needed is not in the record - see if we know what to do if 'cnt' in wines[0]: # the cnt field is in the file - so set to that structure # we will put the updated values into the 'cnt' field print('setting values fldWineDescr and fldWineDescrNew to: cnt') # change the field we are updating optiondict['fldWineDescr'] = optiondict['fldWineDescrNew'] = 'cnt' elif 'winedescr' in wines[0]: # the WineDescr field is in the file - so set to that structure print('setting values fldWineDescr to winedescr and fldWineDescrNew to winedescrnew') # change the field we are updating optiondict['fldWineDescr'] = 'winedescr' optiondict['fldWineDescrNew'] = 'winedescrnew' else: # no idea - we need to error out print('could not find fldWineDescr in wines[0]-aborting:', optiondict['fldWineDescr'], '\nwines[0]:', wines[0]) # force the error error = wines[0][optiondict['fldWineDescr']] # determine if we should create the match column (may want ot remove this section later) # removed this logic - require the person to set this field - we will not set it for them. if False and optiondict['fldWineDescr'] == 'winedescr': # we are using the file format that is the xref file # so check to see if we have match enabled if not optiondict['fldWineDescrMatch']: # create the default value optiondict['fldWineDescrMatch'] = 'same' # provide message print('setting value fldWineDescrMatch to: same') # check to see if the input file is the same as the output file if optiondict['csvfile_update_in'] == optiondict['csvfile_update_out']: # they are the same file (in and out) - so we need to move the input file to a backup location (file_path, base_filename, file_ext) = kvutil.filename_split(optiondict['csvfile_update_in']) # create the new filename backupfile = kvutil.filename_proper( base_filename + optiondict['backupfile_ext'], file_path ) # messaging print('copying ', optiondict['csvfile_update_in'], ' to ', backupfile) # copy the input file to the backup filename shutil.copyfile(optiondict['csvfile_update_in'], backupfile) # set the output keys we are going to assign if optiondict['fldWineDescrNew'] == 'cnt': # output matches the original ref file format with the "cnt" field optiondict['csvdictkeys'] = ['cnt','date','search','store','wine','winesrt'] elif optiondict['fldWineDescrMatch']: # output is a modified xref format so you can look at old and new definitions # optiondict['csvdictkeys'] = [optiondict['fldWineDescr'],optiondict['fldWineDescrNew'],optiondict['fldWineDescrMatch'], 'date','search','company','wine','winesrt'] optiondict['csvdictkeys'] = [optiondict['fldWineDescr'],optiondict['fldWineDescrNew'],optiondict['fldWineDescrMatch'], *header] else: # copy over the read in format optiondict['csvdictkeys'] = [optiondict['fldWineDescrNew']] + header[1:] # output matches expected input - should really change this to be the format of the read in file #optiondict['csvdictkeys'] = [optiondict['fldWineDescrNew'], 'date','search','company','wine','winesrt'] print('updateFileOptionDictCheck:set csvdictkeys to:',optiondict['csvdictkeys']) # --------------------------------------------------------------------------- if __name__ == '__main__': # capture the command line optiondict = kvutil.kv_parse_command_line( optiondictconfig, debug=False ) # set the global debug flag ppFlag = optiondict['pprint'] # set master fields setOptionDictMasterFldValues( optiondict, debug=False ) ### global variable checks ### if optiondict['setup_check']: print('Running global variable check') globalVariableCheck( debug = optiondict['debug'] ) sys.exit() # messaging print('reading in master file:', optiondict['csvfile_master_in']) # read in the MASTER FILE INPUT file wines,header = kvcsv.readcsv2list_with_header(optiondict['csvfile_master_in'], headerlc=True) # build the wine lookup dictionary wgLookup = buildWineryGrapeLookup( wines, optiondict['fldWineDescrMaster'], optiondict['fldWineMaster'], debug=optiondict['debug'] ) # read in the UPDATE FILE INPUT file - if not updating the master file if optiondict['csvfile_master_in'] != optiondict['csvfile_update_in']: # messaging print('reading in update file:', optiondict['csvfile_update_in']) # read in the INPUT file wines,header = kvcsv.readcsv2list_with_header(optiondict['csvfile_update_in'], headerlc=True) # check to see if we read in any records and if not just return if not wines: print('wineset.py - no records read in - no work to be done - exitting') sys.exit() # test to see if we should set the fields based on what we just read in updateFileOptionDictCheck( optiondict, wines, header, debug=optiondict['debug'] ) # do the assignment of wines to records setWineryDescrFromWineryGrapeLookup( wgLookup, wines, optiondict['fldWineDescr'], optiondict['fldWine'], optiondict['fldWineDescrNew'], optiondict['fldWineDescrMatch'], debug=optiondict['debug'] ) # if enabled - set all unassigned new descriptions the default value if optiondict['defaultnew'] is not None: # message print('Setting ', optiondict['fldWineDescrNew'], ' to ', optiondict['defaultnew'], 'if not set') # do the work setDigitFld2Value( wines, optiondict['fldWineDescrNew'], optiondict['defaultnew'], debug=optiondict['debug'] ) # save the output to the file of interest kvcsv.writelist2csv( optiondict['csvfile_update_out'], wines, optiondict['csvdictkeys'] ) # messaging print('Saved results to:', optiondict['csvfile_update_out'])
normal
{ "blob_id": "d786e89b9d478dcff3c541c89731247075d078c3", "index": 678, "step-1": "<mask token>\n\n\ndef globalVariableCheck(debug=False):\n for liquor in liquorLookup:\n if liquor in noGrapeLookup:\n print(\n 'WARNING:liquorLookup regexs will never execute - they are in noGrapeLookup:'\n , liquor)\n if liquor in ignoreGrapeLookup:\n print(\n 'WARNING:liquorLookup regexs will never execute - they are in ignoreGrapeLookup:'\n , liquor)\n for winery in ignoreGrapeLookup:\n if winery in noGrapeLookup:\n print(\n 'WARNING:ignoreGrapeLookup regexs will never execute - they are in noGrapeLookup:'\n , winery)\n\n\ndef setOptionDictMasterFldValues(optiondict, debug=False):\n for fld in ('fldWine', 'fldWineDescr'):\n if not optiondict[fld + 'Master']:\n optiondict[fld + 'Master'] = optiondict[fld]\n\n\n<mask token>\n\n\ndef findWinery(rec, lastWinery, lastReWinery, fldWine, debug=False):\n if lastWinery:\n if debug:\n try:\n print('fw:new winery:', rec[fldWine])\n except Exception as e:\n print('debug error8-continuing:', str(e))\n print('rec[fldWine]:type:', type(rec[fldWine]))\n print('fw:checking if this is lastWinery:', lastWinery)\n if lastReWinery.search(rec[fldWine]):\n if debug:\n print('fw:this matches the last winery')\n return lastWinery, lastReWinery\n elif debug:\n print('fw:not last winery')\n for winery, reWinery in wineryLookup:\n if debug:\n print('fw:not lastWinery-checking winery:', winery)\n if fldWine not in rec:\n print('not a column in this record fldWine:', fldWine)\n print('rec:', rec)\n if reWinery.search(rec[fldWine]):\n if debug:\n print('fw:winery match found:', winery)\n return winery, reWinery\n return None, None\n\n\n<mask token>\n\n\ndef findStrInRecReturnOther(rec, fldWineDescr, findStr, debug=False):\n matchLoc = rec[fldWineDescr].find(findStr)\n if matchLoc > -1:\n other = rec[fldWineDescr][matchLoc + len(findStr) + 1:].split()\n if debug:\n print('fsirro:findStr matched:', findStr)\n if debug:\n print('fsirro:findStr other:', other)\n return findStr, other\n if debug:\n print('fsirro:findStr did not match using:', findStr)\n return None, []\n\n\n<mask token>\n\n\ndef findVintage(rec, fldWine, debug=False):\n for reVintage in vintageLookup:\n m = reVintage.search(rec[fldWine])\n if m:\n if m.group(1):\n vintage = m.group(1)\n if debug:\n print('fv:vintage-match:', reVintage, ':group1')\n elif m.group(2):\n vintage = m.group(2)\n if debug:\n print('fv:vintage-match:', reVintage, ':group2')\n elif m.group(3):\n vintage = m.group(3)\n if debug:\n print('fv:vintage-match:', reVintage, ':group3')\n else:\n vintage = m.group(4)\n if debug:\n print('fv:vintage-match:', reVintage, ':group4')\n return vintage\n return None\n\n\ndef buildWineryGrapeLookup(wines, fldWineDescr='winedescr', fldWine='wine',\n debug=False):\n wgLookup = {}\n lastWinery = None\n lastReWinery = None\n for rec in wines:\n if debug:\n print('bwgl:new rec:', rec[fldWineDescr])\n if not fldWineDescr in rec:\n print('creating-field:', fldWineDescr)\n rec[fldWineDescr] = ''\n winery = grape = wine = liquor = None\n other = []\n lastWinery, lastReWinery = winery, reWinery = findWinery(rec,\n lastWinery, lastReWinery, fldWine, debug=debug)\n if not winery:\n if debug:\n print('bwgl:did not find winery-skipping:', rec[fldWine])\n continue\n if winery in ignoreGrapeLookup:\n wine = ''\n if debug:\n print('bwgl:wine check ignoreGrapeLookup on winery:', winery)\n elif winery in noGrapeLookup:\n if debug:\n print('bwgl:wine check noGrapeLookup on winery:', winery)\n wine = wineLookupByName(noGrapeLookup[winery], rec[fldWineDescr\n ], [], 'noGrapeLookup', debug=debug)\n if False and wine == '':\n if debug:\n print('bwgl:nograpelookup:no-match:set wine to None')\n wine = None\n elif winery in liquorLookup:\n if debug:\n print('bwgl:liquor check on winery:', winery)\n liquor, reLiquor = findLiquor(rec, winery, fldWine, debug=debug)\n if liquor is not None:\n wine = liquor\n if debug:\n print('bwgl:liquor found and put in wine:', wine)\n if wine is None:\n if debug:\n print('bwgl:grape check because wine is None')\n grape, other = findGrapeByStr(rec, fldWineDescr)\n if debug:\n print('bwgl:grape:', grape, ':other:', other)\n elif debug:\n print('bwgl:grape check skipped - we have a wine')\n if wine is None and grape is None:\n if debug:\n print('bwgl:record skipped - no grape or wine defined')\n continue\n if grape is None:\n if debug:\n print('bwgl:build other from winery')\n wineryFind, other = findStrInRecReturnOther(rec, fldWineDescr,\n winery, debug=debug)\n if 'case' in other:\n other.remove('case')\n if debug:\n print('bwgl:remove case from other')\n if other:\n if debug:\n print('bwgl:looking at other for quals, bottlesize and vintage'\n )\n if not other[-1].isdigit():\n for qual, reQual in reQualLookup:\n if qual == other[-1]:\n if debug:\n print('bwgl:remove qualifier from other:', qual)\n del other[-1]\n break\n if other and not other[-1].isdigit():\n for size, reSize in sizeLookup:\n if size == other[-1]:\n if debug:\n print('bwgl:remove bottlesize from other:', size)\n del other[-1]\n break\n if other and other[-1].isdigit():\n if winery in ignoreGrapeLookup and ignoreGrapeLookup[winery\n ] and other[-1] in ignoreGrapeLookup[winery]:\n if debug:\n print(\n 'bwgl:value is in ignoreLookupGrape - keeping it:',\n other[-1])\n else:\n if debug:\n print('bwgl:remove vintage from other:', other[-1])\n del other[-1]\n if wine and wine in other:\n other.remove(wine)\n if debug:\n print('bwgl:remove wine from other:', wine)\n if debug:\n try:\n print('bwgl:Final-Build:', winery, ':', grape, ':', wine,\n ':', liquor, ':', other, ':', rec[fldWineDescr], ':',\n rec[fldWine])\n except Exception as e:\n print('debug error2-continuing:', str(e))\n print('fldWine:', fldWine)\n if grape is None and wine is not None:\n grape = wine\n if debug:\n print('bwgl:set-grape-to-wine:', grape)\n if debug:\n print('bwgl:create wgLookup for winery:', winery, ':grape:', grape)\n if winery not in wgLookup:\n wgLookup[winery] = {grape: []}\n elif grape not in wgLookup[winery]:\n wgLookup[winery][grape] = []\n if other and other not in wgLookup[winery][grape]:\n wgLookup[winery][grape].append(other)\n if debug:\n print('bwgl:appending to wgLookup:other:', other)\n if debug:\n print('bwgl:complete-read-of-master-file:sort wgLookup')\n for winery in wgLookup:\n for grape in wgLookup[winery]:\n wgLookup[winery][grape] = sorted(wgLookup[winery][grape], key=\n len, reverse=True)\n if debug:\n print('\\n' * 5)\n print('START WGLOOKUP DUMPED')\n print('#' * 80)\n if ppFlag:\n pp.pprint(wgLookup)\n else:\n print('bwgl:final-wgLookup:\\n', wgLookup)\n print('#' * 80)\n return wgLookup\n\n\ndef findAddAttribWgLookup(rec, winery, value, fldWine, AbbrLookup=[],\n defaultorderlist=None, valueDescr='', debug=False):\n singlematch = []\n if debug:\n try:\n print('faawl:value:', valueDescr, ':match-wgLookup:', rec[\n fldWine], ':', wgLookup[winery][value])\n except Exception as e:\n print('debug error7-continuing:', str(e))\n print('fldWine:', fldWine)\n for valuematchset in wgLookup[winery][value]:\n if debug:\n print('faawl:testing valuematchset:', valuematchset, ':length:',\n len(valuematchset))\n allmatch = True\n for valuematch in valuematchset:\n reMatch1 = re.compile('\\\\b' + valuematch + '\\\\b', re.IGNORECASE)\n reMatch2 = re.compile('\\\\s' + valuematch + '\\\\s', re.IGNORECASE)\n m1 = reMatch1.search(rec[fldWine])\n m2 = reMatch2.search(rec[fldWine])\n if m1 or m2:\n allmatch = True and allmatch\n elif valuematch in AbbrLookup:\n if debug:\n print('faawl:valuematch-abbr:', valuematch, ':',\n wineAbbrLookup[valuematch])\n reMatch = re.compile(wineAbbrLookup[valuematch], re.IGNORECASE)\n allmatch = reMatch.search(rec[fldWine]) and allmatch\n else:\n allmatch = False and allmatch\n if debug:\n print('faawl:valuematch:', valuematch, ':allmatch:', allmatch)\n if allmatch:\n if debug:\n print('faawl:value matched:', valuematchset)\n if len(valuematchset) == 1:\n if debug:\n print('faawl:single-valuematch-set-added-to-singlematch:',\n valuematchset)\n singlematch.append(valuematchset)\n else:\n if debug:\n print('faawl:multivalue-valuematch-set-found:done')\n return valuematchset\n if not singlematch:\n if debug:\n print('faawl:exit with singlematch NOT populated return blank')\n return []\n if debug:\n print('faawl:exit with singlematch populated:', singlematch)\n if len(singlematch) == 1 or not defaultorderlist:\n if debug:\n print('faawl:return first entry in singlematch:', singlematch[0])\n return singlematch[0]\n defaultorder = defaultorderlist[:]\n if debug:\n print('faawl:multiple single match value-singlematch:', singlematch)\n for val in singlematch[::-1]:\n if val not in defaultorder:\n defaultorder.insert(0, val)\n if winery == 'Mondavi' and ['Tok'] in singlematch:\n if debug:\n print('faawl:Change from:', valuematchset, ':to Tok for mondavi')\n return ['Tok']\n for val in defaultorder:\n if val in singlematch:\n if debug:\n print('faawl:selected-singlematch-value:', val)\n return val\n if debug:\n print('faawl:valuematchset-empty')\n return []\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\ndef globalVariableCheck(debug=False):\n for liquor in liquorLookup:\n if liquor in noGrapeLookup:\n print(\n 'WARNING:liquorLookup regexs will never execute - they are in noGrapeLookup:'\n , liquor)\n if liquor in ignoreGrapeLookup:\n print(\n 'WARNING:liquorLookup regexs will never execute - they are in ignoreGrapeLookup:'\n , liquor)\n for winery in ignoreGrapeLookup:\n if winery in noGrapeLookup:\n print(\n 'WARNING:ignoreGrapeLookup regexs will never execute - they are in noGrapeLookup:'\n , winery)\n\n\ndef setOptionDictMasterFldValues(optiondict, debug=False):\n for fld in ('fldWine', 'fldWineDescr'):\n if not optiondict[fld + 'Master']:\n optiondict[fld + 'Master'] = optiondict[fld]\n\n\n<mask token>\n\n\ndef findQualifier(wine, debug=False):\n for val, reSearch in reQualLookup:\n if reSearch.search(wine):\n if debug:\n print('findQualifier:matched-returning:', val)\n return val\n if debug:\n print('findQualifier:no-match-returning:', None)\n return None\n\n\ndef findWinery(rec, lastWinery, lastReWinery, fldWine, debug=False):\n if lastWinery:\n if debug:\n try:\n print('fw:new winery:', rec[fldWine])\n except Exception as e:\n print('debug error8-continuing:', str(e))\n print('rec[fldWine]:type:', type(rec[fldWine]))\n print('fw:checking if this is lastWinery:', lastWinery)\n if lastReWinery.search(rec[fldWine]):\n if debug:\n print('fw:this matches the last winery')\n return lastWinery, lastReWinery\n elif debug:\n print('fw:not last winery')\n for winery, reWinery in wineryLookup:\n if debug:\n print('fw:not lastWinery-checking winery:', winery)\n if fldWine not in rec:\n print('not a column in this record fldWine:', fldWine)\n print('rec:', rec)\n if reWinery.search(rec[fldWine]):\n if debug:\n print('fw:winery match found:', winery)\n return winery, reWinery\n return None, None\n\n\ndef findLiquor(rec, winery, fldWine, debug=False):\n for liquor, reLiquor in liquorLookup[winery]:\n if debug:\n print('fl:checking liquor:', liquor)\n if reLiquor.search(rec[fldWine]):\n if debug:\n print('fl:liquor match found:', liquor)\n return liquor, reLiquor\n return None, None\n\n\ndef findGrapeByRegex(rec, fldWine, debug=False):\n for grape, reGrape in grapeLookup:\n if debug:\n print('fgbr:grape:', grape)\n if grape is not None and reGrape.search(rec[fldWine]):\n if debug:\n print('fgbr:grape match found:', grape)\n return grape, reGrape\n return None, None\n\n\ndef findStrInRecReturnOther(rec, fldWineDescr, findStr, debug=False):\n matchLoc = rec[fldWineDescr].find(findStr)\n if matchLoc > -1:\n other = rec[fldWineDescr][matchLoc + len(findStr) + 1:].split()\n if debug:\n print('fsirro:findStr matched:', findStr)\n if debug:\n print('fsirro:findStr other:', other)\n return findStr, other\n if debug:\n print('fsirro:findStr did not match using:', findStr)\n return None, []\n\n\ndef findGrapeByStr(rec, fldWineDescr, debug=False):\n for grape, reGrape in grapeLookup:\n if debug:\n print('fg:grape:', grape)\n grape, other = findStrInRecReturnOther(rec, fldWineDescr, grape,\n debug=debug)\n if grape:\n return grape, other\n return None, []\n\n\ndef findVintage(rec, fldWine, debug=False):\n for reVintage in vintageLookup:\n m = reVintage.search(rec[fldWine])\n if m:\n if m.group(1):\n vintage = m.group(1)\n if debug:\n print('fv:vintage-match:', reVintage, ':group1')\n elif m.group(2):\n vintage = m.group(2)\n if debug:\n print('fv:vintage-match:', reVintage, ':group2')\n elif m.group(3):\n vintage = m.group(3)\n if debug:\n print('fv:vintage-match:', reVintage, ':group3')\n else:\n vintage = m.group(4)\n if debug:\n print('fv:vintage-match:', reVintage, ':group4')\n return vintage\n return None\n\n\ndef buildWineryGrapeLookup(wines, fldWineDescr='winedescr', fldWine='wine',\n debug=False):\n wgLookup = {}\n lastWinery = None\n lastReWinery = None\n for rec in wines:\n if debug:\n print('bwgl:new rec:', rec[fldWineDescr])\n if not fldWineDescr in rec:\n print('creating-field:', fldWineDescr)\n rec[fldWineDescr] = ''\n winery = grape = wine = liquor = None\n other = []\n lastWinery, lastReWinery = winery, reWinery = findWinery(rec,\n lastWinery, lastReWinery, fldWine, debug=debug)\n if not winery:\n if debug:\n print('bwgl:did not find winery-skipping:', rec[fldWine])\n continue\n if winery in ignoreGrapeLookup:\n wine = ''\n if debug:\n print('bwgl:wine check ignoreGrapeLookup on winery:', winery)\n elif winery in noGrapeLookup:\n if debug:\n print('bwgl:wine check noGrapeLookup on winery:', winery)\n wine = wineLookupByName(noGrapeLookup[winery], rec[fldWineDescr\n ], [], 'noGrapeLookup', debug=debug)\n if False and wine == '':\n if debug:\n print('bwgl:nograpelookup:no-match:set wine to None')\n wine = None\n elif winery in liquorLookup:\n if debug:\n print('bwgl:liquor check on winery:', winery)\n liquor, reLiquor = findLiquor(rec, winery, fldWine, debug=debug)\n if liquor is not None:\n wine = liquor\n if debug:\n print('bwgl:liquor found and put in wine:', wine)\n if wine is None:\n if debug:\n print('bwgl:grape check because wine is None')\n grape, other = findGrapeByStr(rec, fldWineDescr)\n if debug:\n print('bwgl:grape:', grape, ':other:', other)\n elif debug:\n print('bwgl:grape check skipped - we have a wine')\n if wine is None and grape is None:\n if debug:\n print('bwgl:record skipped - no grape or wine defined')\n continue\n if grape is None:\n if debug:\n print('bwgl:build other from winery')\n wineryFind, other = findStrInRecReturnOther(rec, fldWineDescr,\n winery, debug=debug)\n if 'case' in other:\n other.remove('case')\n if debug:\n print('bwgl:remove case from other')\n if other:\n if debug:\n print('bwgl:looking at other for quals, bottlesize and vintage'\n )\n if not other[-1].isdigit():\n for qual, reQual in reQualLookup:\n if qual == other[-1]:\n if debug:\n print('bwgl:remove qualifier from other:', qual)\n del other[-1]\n break\n if other and not other[-1].isdigit():\n for size, reSize in sizeLookup:\n if size == other[-1]:\n if debug:\n print('bwgl:remove bottlesize from other:', size)\n del other[-1]\n break\n if other and other[-1].isdigit():\n if winery in ignoreGrapeLookup and ignoreGrapeLookup[winery\n ] and other[-1] in ignoreGrapeLookup[winery]:\n if debug:\n print(\n 'bwgl:value is in ignoreLookupGrape - keeping it:',\n other[-1])\n else:\n if debug:\n print('bwgl:remove vintage from other:', other[-1])\n del other[-1]\n if wine and wine in other:\n other.remove(wine)\n if debug:\n print('bwgl:remove wine from other:', wine)\n if debug:\n try:\n print('bwgl:Final-Build:', winery, ':', grape, ':', wine,\n ':', liquor, ':', other, ':', rec[fldWineDescr], ':',\n rec[fldWine])\n except Exception as e:\n print('debug error2-continuing:', str(e))\n print('fldWine:', fldWine)\n if grape is None and wine is not None:\n grape = wine\n if debug:\n print('bwgl:set-grape-to-wine:', grape)\n if debug:\n print('bwgl:create wgLookup for winery:', winery, ':grape:', grape)\n if winery not in wgLookup:\n wgLookup[winery] = {grape: []}\n elif grape not in wgLookup[winery]:\n wgLookup[winery][grape] = []\n if other and other not in wgLookup[winery][grape]:\n wgLookup[winery][grape].append(other)\n if debug:\n print('bwgl:appending to wgLookup:other:', other)\n if debug:\n print('bwgl:complete-read-of-master-file:sort wgLookup')\n for winery in wgLookup:\n for grape in wgLookup[winery]:\n wgLookup[winery][grape] = sorted(wgLookup[winery][grape], key=\n len, reverse=True)\n if debug:\n print('\\n' * 5)\n print('START WGLOOKUP DUMPED')\n print('#' * 80)\n if ppFlag:\n pp.pprint(wgLookup)\n else:\n print('bwgl:final-wgLookup:\\n', wgLookup)\n print('#' * 80)\n return wgLookup\n\n\ndef findAddAttribWgLookup(rec, winery, value, fldWine, AbbrLookup=[],\n defaultorderlist=None, valueDescr='', debug=False):\n singlematch = []\n if debug:\n try:\n print('faawl:value:', valueDescr, ':match-wgLookup:', rec[\n fldWine], ':', wgLookup[winery][value])\n except Exception as e:\n print('debug error7-continuing:', str(e))\n print('fldWine:', fldWine)\n for valuematchset in wgLookup[winery][value]:\n if debug:\n print('faawl:testing valuematchset:', valuematchset, ':length:',\n len(valuematchset))\n allmatch = True\n for valuematch in valuematchset:\n reMatch1 = re.compile('\\\\b' + valuematch + '\\\\b', re.IGNORECASE)\n reMatch2 = re.compile('\\\\s' + valuematch + '\\\\s', re.IGNORECASE)\n m1 = reMatch1.search(rec[fldWine])\n m2 = reMatch2.search(rec[fldWine])\n if m1 or m2:\n allmatch = True and allmatch\n elif valuematch in AbbrLookup:\n if debug:\n print('faawl:valuematch-abbr:', valuematch, ':',\n wineAbbrLookup[valuematch])\n reMatch = re.compile(wineAbbrLookup[valuematch], re.IGNORECASE)\n allmatch = reMatch.search(rec[fldWine]) and allmatch\n else:\n allmatch = False and allmatch\n if debug:\n print('faawl:valuematch:', valuematch, ':allmatch:', allmatch)\n if allmatch:\n if debug:\n print('faawl:value matched:', valuematchset)\n if len(valuematchset) == 1:\n if debug:\n print('faawl:single-valuematch-set-added-to-singlematch:',\n valuematchset)\n singlematch.append(valuematchset)\n else:\n if debug:\n print('faawl:multivalue-valuematch-set-found:done')\n return valuematchset\n if not singlematch:\n if debug:\n print('faawl:exit with singlematch NOT populated return blank')\n return []\n if debug:\n print('faawl:exit with singlematch populated:', singlematch)\n if len(singlematch) == 1 or not defaultorderlist:\n if debug:\n print('faawl:return first entry in singlematch:', singlematch[0])\n return singlematch[0]\n defaultorder = defaultorderlist[:]\n if debug:\n print('faawl:multiple single match value-singlematch:', singlematch)\n for val in singlematch[::-1]:\n if val not in defaultorder:\n defaultorder.insert(0, val)\n if winery == 'Mondavi' and ['Tok'] in singlematch:\n if debug:\n print('faawl:Change from:', valuematchset, ':to Tok for mondavi')\n return ['Tok']\n for val in defaultorder:\n if val in singlematch:\n if debug:\n print('faawl:selected-singlematch-value:', val)\n return val\n if debug:\n print('faawl:valuematchset-empty')\n return []\n\n\n<mask token>\n\n\ndef setDigitFld2Value(wines, fld, value, debug=False):\n for rec in wines:\n if rec[fld].isdigit():\n rec[fld] = value\n\n\ndef updateFileOptionDictCheck(optiondict, wines, header, debug=False):\n if optiondict['fldWineDescr'] not in wines[0]:\n if debug:\n print('updateFileOptionDictCheck:fldWineDescr NOT in file read in:'\n , optiondict['fldWineDescr'])\n if 'cnt' in wines[0]:\n print('setting values fldWineDescr and fldWineDescrNew to: cnt')\n optiondict['fldWineDescr'] = optiondict['fldWineDescrNew'] = 'cnt'\n elif 'winedescr' in wines[0]:\n print(\n 'setting values fldWineDescr to winedescr and fldWineDescrNew to winedescrnew'\n )\n optiondict['fldWineDescr'] = 'winedescr'\n optiondict['fldWineDescrNew'] = 'winedescrnew'\n else:\n print('could not find fldWineDescr in wines[0]-aborting:',\n optiondict['fldWineDescr'], '\\nwines[0]:', wines[0])\n error = wines[0][optiondict['fldWineDescr']]\n if False and optiondict['fldWineDescr'] == 'winedescr':\n if not optiondict['fldWineDescrMatch']:\n optiondict['fldWineDescrMatch'] = 'same'\n print('setting value fldWineDescrMatch to: same')\n if optiondict['csvfile_update_in'] == optiondict['csvfile_update_out']:\n file_path, base_filename, file_ext = kvutil.filename_split(optiondict\n ['csvfile_update_in'])\n backupfile = kvutil.filename_proper(base_filename + optiondict[\n 'backupfile_ext'], file_path)\n print('copying ', optiondict['csvfile_update_in'], ' to ', backupfile)\n shutil.copyfile(optiondict['csvfile_update_in'], backupfile)\n if optiondict['fldWineDescrNew'] == 'cnt':\n optiondict['csvdictkeys'] = ['cnt', 'date', 'search', 'store',\n 'wine', 'winesrt']\n elif optiondict['fldWineDescrMatch']:\n optiondict['csvdictkeys'] = [optiondict['fldWineDescr'], optiondict\n ['fldWineDescrNew'], optiondict['fldWineDescrMatch'], *header]\n else:\n optiondict['csvdictkeys'] = [optiondict['fldWineDescrNew']] + header[1:\n ]\n print('updateFileOptionDictCheck:set csvdictkeys to:', optiondict[\n 'csvdictkeys'])\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef globalVariableCheck(debug=False):\n for liquor in liquorLookup:\n if liquor in noGrapeLookup:\n print(\n 'WARNING:liquorLookup regexs will never execute - they are in noGrapeLookup:'\n , liquor)\n if liquor in ignoreGrapeLookup:\n print(\n 'WARNING:liquorLookup regexs will never execute - they are in ignoreGrapeLookup:'\n , liquor)\n for winery in ignoreGrapeLookup:\n if winery in noGrapeLookup:\n print(\n 'WARNING:ignoreGrapeLookup regexs will never execute - they are in noGrapeLookup:'\n , winery)\n\n\ndef setOptionDictMasterFldValues(optiondict, debug=False):\n for fld in ('fldWine', 'fldWineDescr'):\n if not optiondict[fld + 'Master']:\n optiondict[fld + 'Master'] = optiondict[fld]\n\n\ndef wineLookupByName(nameLookup, lookupStr, other, msg, wineAbbrLookup=None,\n debug=False):\n funcname = 'wineLookupByName:' + msg + ':'\n if debug:\n print(funcname + 'nameLookup:', nameLookup)\n if nameLookup is None:\n if debug:\n print(funcname + 'match: value is none - continue on')\n return ''\n for name in nameLookup:\n if debug:\n print(funcname + 'match-name:', name)\n if name is None:\n if debug:\n print(funcname +\n 'name-matched: value is none - continue on:pass back blank'\n )\n return ''\n reName = re.compile('\\\\b' + name + '\\\\b', re.IGNORECASE)\n if reName.search(lookupStr):\n if debug:\n print(funcname + 'name-MATCHED:', name)\n for val in other:\n if reName.search(val):\n other.remove(val)\n if debug:\n print(funcname + 'name-remove-from-other:', val)\n return name\n if wineAbbrLookup and name in wineAbbrLookup:\n reName = re.compile(wineAbbrLookup[name], re.IGNORECASE)\n if debug:\n print(funcname + 'Abbr-match-name:', name)\n if reName.search(lookupStr):\n if debug:\n print(funcname + 'Abbr-name-MATCHED:', wineAbbrLookup[name]\n )\n for val in other:\n if reName.search(val):\n other.remove(val)\n if debug:\n print(funcname + 'name-remove-from-other:', val)\n return name\n if debug:\n print(funcname + 'name match not found:set to blank')\n return None\n\n\ndef findQualifier(wine, debug=False):\n for val, reSearch in reQualLookup:\n if reSearch.search(wine):\n if debug:\n print('findQualifier:matched-returning:', val)\n return val\n if debug:\n print('findQualifier:no-match-returning:', None)\n return None\n\n\ndef findWinery(rec, lastWinery, lastReWinery, fldWine, debug=False):\n if lastWinery:\n if debug:\n try:\n print('fw:new winery:', rec[fldWine])\n except Exception as e:\n print('debug error8-continuing:', str(e))\n print('rec[fldWine]:type:', type(rec[fldWine]))\n print('fw:checking if this is lastWinery:', lastWinery)\n if lastReWinery.search(rec[fldWine]):\n if debug:\n print('fw:this matches the last winery')\n return lastWinery, lastReWinery\n elif debug:\n print('fw:not last winery')\n for winery, reWinery in wineryLookup:\n if debug:\n print('fw:not lastWinery-checking winery:', winery)\n if fldWine not in rec:\n print('not a column in this record fldWine:', fldWine)\n print('rec:', rec)\n if reWinery.search(rec[fldWine]):\n if debug:\n print('fw:winery match found:', winery)\n return winery, reWinery\n return None, None\n\n\ndef findLiquor(rec, winery, fldWine, debug=False):\n for liquor, reLiquor in liquorLookup[winery]:\n if debug:\n print('fl:checking liquor:', liquor)\n if reLiquor.search(rec[fldWine]):\n if debug:\n print('fl:liquor match found:', liquor)\n return liquor, reLiquor\n return None, None\n\n\ndef findGrapeByRegex(rec, fldWine, debug=False):\n for grape, reGrape in grapeLookup:\n if debug:\n print('fgbr:grape:', grape)\n if grape is not None and reGrape.search(rec[fldWine]):\n if debug:\n print('fgbr:grape match found:', grape)\n return grape, reGrape\n return None, None\n\n\ndef findStrInRecReturnOther(rec, fldWineDescr, findStr, debug=False):\n matchLoc = rec[fldWineDescr].find(findStr)\n if matchLoc > -1:\n other = rec[fldWineDescr][matchLoc + len(findStr) + 1:].split()\n if debug:\n print('fsirro:findStr matched:', findStr)\n if debug:\n print('fsirro:findStr other:', other)\n return findStr, other\n if debug:\n print('fsirro:findStr did not match using:', findStr)\n return None, []\n\n\ndef findGrapeByStr(rec, fldWineDescr, debug=False):\n for grape, reGrape in grapeLookup:\n if debug:\n print('fg:grape:', grape)\n grape, other = findStrInRecReturnOther(rec, fldWineDescr, grape,\n debug=debug)\n if grape:\n return grape, other\n return None, []\n\n\ndef findVintage(rec, fldWine, debug=False):\n for reVintage in vintageLookup:\n m = reVintage.search(rec[fldWine])\n if m:\n if m.group(1):\n vintage = m.group(1)\n if debug:\n print('fv:vintage-match:', reVintage, ':group1')\n elif m.group(2):\n vintage = m.group(2)\n if debug:\n print('fv:vintage-match:', reVintage, ':group2')\n elif m.group(3):\n vintage = m.group(3)\n if debug:\n print('fv:vintage-match:', reVintage, ':group3')\n else:\n vintage = m.group(4)\n if debug:\n print('fv:vintage-match:', reVintage, ':group4')\n return vintage\n return None\n\n\ndef buildWineryGrapeLookup(wines, fldWineDescr='winedescr', fldWine='wine',\n debug=False):\n wgLookup = {}\n lastWinery = None\n lastReWinery = None\n for rec in wines:\n if debug:\n print('bwgl:new rec:', rec[fldWineDescr])\n if not fldWineDescr in rec:\n print('creating-field:', fldWineDescr)\n rec[fldWineDescr] = ''\n winery = grape = wine = liquor = None\n other = []\n lastWinery, lastReWinery = winery, reWinery = findWinery(rec,\n lastWinery, lastReWinery, fldWine, debug=debug)\n if not winery:\n if debug:\n print('bwgl:did not find winery-skipping:', rec[fldWine])\n continue\n if winery in ignoreGrapeLookup:\n wine = ''\n if debug:\n print('bwgl:wine check ignoreGrapeLookup on winery:', winery)\n elif winery in noGrapeLookup:\n if debug:\n print('bwgl:wine check noGrapeLookup on winery:', winery)\n wine = wineLookupByName(noGrapeLookup[winery], rec[fldWineDescr\n ], [], 'noGrapeLookup', debug=debug)\n if False and wine == '':\n if debug:\n print('bwgl:nograpelookup:no-match:set wine to None')\n wine = None\n elif winery in liquorLookup:\n if debug:\n print('bwgl:liquor check on winery:', winery)\n liquor, reLiquor = findLiquor(rec, winery, fldWine, debug=debug)\n if liquor is not None:\n wine = liquor\n if debug:\n print('bwgl:liquor found and put in wine:', wine)\n if wine is None:\n if debug:\n print('bwgl:grape check because wine is None')\n grape, other = findGrapeByStr(rec, fldWineDescr)\n if debug:\n print('bwgl:grape:', grape, ':other:', other)\n elif debug:\n print('bwgl:grape check skipped - we have a wine')\n if wine is None and grape is None:\n if debug:\n print('bwgl:record skipped - no grape or wine defined')\n continue\n if grape is None:\n if debug:\n print('bwgl:build other from winery')\n wineryFind, other = findStrInRecReturnOther(rec, fldWineDescr,\n winery, debug=debug)\n if 'case' in other:\n other.remove('case')\n if debug:\n print('bwgl:remove case from other')\n if other:\n if debug:\n print('bwgl:looking at other for quals, bottlesize and vintage'\n )\n if not other[-1].isdigit():\n for qual, reQual in reQualLookup:\n if qual == other[-1]:\n if debug:\n print('bwgl:remove qualifier from other:', qual)\n del other[-1]\n break\n if other and not other[-1].isdigit():\n for size, reSize in sizeLookup:\n if size == other[-1]:\n if debug:\n print('bwgl:remove bottlesize from other:', size)\n del other[-1]\n break\n if other and other[-1].isdigit():\n if winery in ignoreGrapeLookup and ignoreGrapeLookup[winery\n ] and other[-1] in ignoreGrapeLookup[winery]:\n if debug:\n print(\n 'bwgl:value is in ignoreLookupGrape - keeping it:',\n other[-1])\n else:\n if debug:\n print('bwgl:remove vintage from other:', other[-1])\n del other[-1]\n if wine and wine in other:\n other.remove(wine)\n if debug:\n print('bwgl:remove wine from other:', wine)\n if debug:\n try:\n print('bwgl:Final-Build:', winery, ':', grape, ':', wine,\n ':', liquor, ':', other, ':', rec[fldWineDescr], ':',\n rec[fldWine])\n except Exception as e:\n print('debug error2-continuing:', str(e))\n print('fldWine:', fldWine)\n if grape is None and wine is not None:\n grape = wine\n if debug:\n print('bwgl:set-grape-to-wine:', grape)\n if debug:\n print('bwgl:create wgLookup for winery:', winery, ':grape:', grape)\n if winery not in wgLookup:\n wgLookup[winery] = {grape: []}\n elif grape not in wgLookup[winery]:\n wgLookup[winery][grape] = []\n if other and other not in wgLookup[winery][grape]:\n wgLookup[winery][grape].append(other)\n if debug:\n print('bwgl:appending to wgLookup:other:', other)\n if debug:\n print('bwgl:complete-read-of-master-file:sort wgLookup')\n for winery in wgLookup:\n for grape in wgLookup[winery]:\n wgLookup[winery][grape] = sorted(wgLookup[winery][grape], key=\n len, reverse=True)\n if debug:\n print('\\n' * 5)\n print('START WGLOOKUP DUMPED')\n print('#' * 80)\n if ppFlag:\n pp.pprint(wgLookup)\n else:\n print('bwgl:final-wgLookup:\\n', wgLookup)\n print('#' * 80)\n return wgLookup\n\n\ndef findAddAttribWgLookup(rec, winery, value, fldWine, AbbrLookup=[],\n defaultorderlist=None, valueDescr='', debug=False):\n singlematch = []\n if debug:\n try:\n print('faawl:value:', valueDescr, ':match-wgLookup:', rec[\n fldWine], ':', wgLookup[winery][value])\n except Exception as e:\n print('debug error7-continuing:', str(e))\n print('fldWine:', fldWine)\n for valuematchset in wgLookup[winery][value]:\n if debug:\n print('faawl:testing valuematchset:', valuematchset, ':length:',\n len(valuematchset))\n allmatch = True\n for valuematch in valuematchset:\n reMatch1 = re.compile('\\\\b' + valuematch + '\\\\b', re.IGNORECASE)\n reMatch2 = re.compile('\\\\s' + valuematch + '\\\\s', re.IGNORECASE)\n m1 = reMatch1.search(rec[fldWine])\n m2 = reMatch2.search(rec[fldWine])\n if m1 or m2:\n allmatch = True and allmatch\n elif valuematch in AbbrLookup:\n if debug:\n print('faawl:valuematch-abbr:', valuematch, ':',\n wineAbbrLookup[valuematch])\n reMatch = re.compile(wineAbbrLookup[valuematch], re.IGNORECASE)\n allmatch = reMatch.search(rec[fldWine]) and allmatch\n else:\n allmatch = False and allmatch\n if debug:\n print('faawl:valuematch:', valuematch, ':allmatch:', allmatch)\n if allmatch:\n if debug:\n print('faawl:value matched:', valuematchset)\n if len(valuematchset) == 1:\n if debug:\n print('faawl:single-valuematch-set-added-to-singlematch:',\n valuematchset)\n singlematch.append(valuematchset)\n else:\n if debug:\n print('faawl:multivalue-valuematch-set-found:done')\n return valuematchset\n if not singlematch:\n if debug:\n print('faawl:exit with singlematch NOT populated return blank')\n return []\n if debug:\n print('faawl:exit with singlematch populated:', singlematch)\n if len(singlematch) == 1 or not defaultorderlist:\n if debug:\n print('faawl:return first entry in singlematch:', singlematch[0])\n return singlematch[0]\n defaultorder = defaultorderlist[:]\n if debug:\n print('faawl:multiple single match value-singlematch:', singlematch)\n for val in singlematch[::-1]:\n if val not in defaultorder:\n defaultorder.insert(0, val)\n if winery == 'Mondavi' and ['Tok'] in singlematch:\n if debug:\n print('faawl:Change from:', valuematchset, ':to Tok for mondavi')\n return ['Tok']\n for val in defaultorder:\n if val in singlematch:\n if debug:\n print('faawl:selected-singlematch-value:', val)\n return val\n if debug:\n print('faawl:valuematchset-empty')\n return []\n\n\ndef setWineryDescrFromWineryGrapeLookup(wgLookup, wines, fldWineDescr=\n 'winedescr', fldWine='wine', fldWineDescrNew='winedescrnew',\n fldWineDescrMatch=False, debug=False):\n if debug:\n print('\\n' * 10,\n 'START WINEDESCR SETTING HERE ---------------------------------------------'\n )\n for rec in wines:\n (winery) = (grape) = (wine) = (vintage) = (case) = (size) = (liquor\n ) = (nongrape) = (qual) = None\n winematchset = grapematchset = []\n if debug:\n try:\n print('setWinery:fldWine:', rec[fldWine])\n except Exception as e:\n print('debug error2-continuing:', str(e))\n print('fldWine:', fldWine)\n if fldWineDescrNew not in rec:\n rec[fldWineDescrNew] = rec[fldWineDescr]\n winery, reWinery = findWinery(rec, None, None, fldWine, debug=debug)\n if winery is None:\n if debug:\n print('setWinery:winery not found-next record:' + rec[fldWine])\n continue\n elif winery not in wgLookup:\n if debug:\n print('setWinery:winery not in wgLookup:', winery)\n continue\n grape, reGrape = findGrapeByRegex(rec, fldWine, debug=debug)\n if debug:\n print('setWinery:grape found:', grape)\n if winery in ignoreGrapeLookup:\n if debug:\n print(\n 'setWinery:winery-match-ignoreGrape:clear-wine:set-grape-to-None:set-nongrape-True:winery:'\n , winery)\n wine = ''\n grape = None\n nongrape = True\n if winery in noGrapeLookup:\n if debug:\n print('setWinery:noGrapeLookup wine check:', winery)\n wine = wineLookupByName(noGrapeLookup[winery], rec[fldWine], [],\n 'noGrapeLookup', wineAbbrLookup, debug=debug)\n if debug:\n print('setWinery:nogrape check:wine:', wine)\n if wine == '':\n if debug:\n print(\n 'setWinery:noGrapeLookup:matched:None::clear grape:set nongrape to True'\n )\n grape = None\n wine = ''\n nongrape = True\n elif wine:\n grape = None\n if debug:\n print(\n 'setWinery:nograpeLookup:wine found - clear grape field'\n )\n if wine is None and winery in liquorLookup:\n if debug:\n print('setWinery:liqourLookup:', winery)\n liquor, reLiquor = findLiquor(rec, winery, fldWine, debug=debug)\n if liquor is not None:\n wine = liquor\n if debug:\n print('setWinery:liquorLookup-match:', liquor)\n if not grape and not nongrape and not wine and liquor is None:\n if debug:\n print('setWinery:did not find grape-skipping record:', rec[\n fldWineDescr])\n continue\n if debug:\n print('setWinery:pre-vintage found values for wine/liquor:',\n wine, ':grape:', grape)\n vintage = findVintage(rec, fldWine, debug=debug)\n if debug:\n print('setWinery:vintage:', vintage)\n if reCase.search(rec[fldWine]):\n case = 'case'\n for size, reSize in sizeLookup:\n if debug:\n print('setWinery:sizeLookup:', size)\n if reSize.search(rec[fldWine]) and not reShipsAs.search(rec[\n fldWine]):\n if debug:\n print('setWinery:sizeLookup:matched:', reSize)\n break\n else:\n size = None\n if debug:\n print('setWinery:sizeLookup:None-found')\n qual = findQualifier(rec[fldWine], debug=debug)\n if debug:\n try:\n print('setWinery:FinalAttributes:', winery, ':', grape, ':',\n wine, ':', liquor, ':', vintage, ':', case, ':', size,\n ':', qual, ':', rec[fldWine])\n except Exception as e:\n print('debug error5-continuing:', str(e))\n print('fldWine:', fldWine)\n if liquor is not None:\n if debug:\n print(\n 'setWinery:liquor flag set - no additional data needs to be collected'\n )\n elif wine is not None:\n if debug:\n print(\n 'setWinery:wine is not None - do additional lookups:wine:',\n wine)\n if wine in wgLookup[winery] and wgLookup[winery][wine]:\n if debug:\n print('setWinery:lookup winematchset')\n winematchset = findAddAttribWgLookup(rec, winery, wine,\n fldWine, wineAbbrLookup, None, valueDescr='wine', debug\n =debug)\n else:\n print('setWinery:unable to perform wgLookup on winery:',\n winery, ':wine:', wine, ':rec-wine:', rec[fldWine])\n if debug:\n try:\n print('wgLookup[winery]:', wgLookup[winery])\n except Exception as e:\n print('debug error3-continuing:', str(e))\n print('winery:', winery)\n if debug:\n print('setWinery:winematchset:', winematchset)\n elif grape is not None:\n if debug:\n print('setWinery:grape is not None - do additional lookups:',\n grape)\n if grape in wgLookup[winery] and wgLookup[winery][grape]:\n grapematchset = findAddAttribWgLookup(rec, winery, grape,\n fldWine, wineAbbrLookup, defaultorderlist, valueDescr=\n 'grape', debug=debug)\n elif grape in wgLookup[winery]:\n if debug:\n print(\n 'setWinery:grape match: matching record set is blank - no action required'\n )\n else:\n print('setWinery:grape NONMATCH:', rec[fldWine])\n if debug:\n print('setWinery:liquor:', liquor, ':wine:', wine,\n ':grape:', grape, ':wgLookup[winery]:', wgLookup[\n winery])\n if debug:\n print('setWinery:grapematchset:', grapematchset)\n if vintage:\n newVintageLookupWine = rec[fldWine]\n for matchvalue in winematchset:\n if vintage in matchvalue:\n newVintageLookupWine = newVintageLookupWine.replace(\n matchvalue, '')\n if debug:\n print(\n 'setWinery:2nd-vintage:winematchset:wine-name-removal:'\n , matchvalue)\n for matchvalue in grapematchset:\n if vintage in matchvalue:\n newVintageLookupWine = newVintageLookupWine.replace(\n matchvalue, '')\n if debug:\n print(\n 'setWinery:2nd-vintage:grapematchset:wine-name-removal:'\n , matchvalue)\n if newVintageLookupWine != rec[fldWine]:\n if debug:\n print('setWinery:2nd-vintage:newVintageLookupWine:',\n newVintageLookupWine)\n newVintage = findVintage({fldWine: newVintageLookupWine},\n fldWine, debug=debug)\n if debug:\n print('setWinery:2nd-vintage:newVintage:', newVintage)\n vintage = newVintage\n wineDescr = ''\n if winery.startswith('z'):\n vintage = None\n if debug:\n print('setWinery:winery starts with z: clear vintage')\n if winematchset and ' '.join(winematchset) in wine:\n if debug:\n print('setWinery:clearing-winematchset:', winematchset,\n ':is-in-wine:', wine)\n winematchset = []\n if grapematchset and ' '.join(grapematchset) in grape:\n if not (len(grapematchset) == 1 and len(grapematchset[0]) == 1):\n if debug:\n print('setWinery:clearing-grapematchset:',\n grapematchset, ':is-in-grape:', grape)\n grapematchset = []\n if grapematchset and size and size in ' '.join(grapematchset):\n size = ''\n if winematchset and size and size in ' '.join(winematchset):\n size = ''\n if debug:\n print('setWinery:vallist1:', [winery, grape, wine] +\n grapematchset + winematchset + [vintage, size, qual, case])\n print('setWinery:vallist2:', [winery, grape, wine, *\n grapematchset, *winematchset, vintage, size, qual, case])\n wdList = []\n for val in ([winery, grape, wine] + grapematchset + winematchset +\n [vintage, size, qual, case]):\n if val:\n wdList.append(val)\n wineDescr = ' '.join(wdList)\n if False:\n if debug:\n print('setWinery:wdList:', wdList)\n if debug:\n print('setWinery:wineDescr:', wineDescr)\n if debug:\n try:\n print(':'.join(['setWinery:wineDescrList', wineDescr, rec[\n fldWineDescr], str(wineDescr == rec[fldWineDescr]), rec\n [fldWine]]))\n except Exception as e:\n print('debug error6-continuing:', str(e))\n print('fldWine:', fldWine)\n rec[fldWineDescrNew] = wineDescr\n if fldWineDescrMatch:\n rec[fldWineDescrMatch] = rec[fldWineDescr] == rec[fldWineDescrNew]\n\n\ndef setDigitFld2Value(wines, fld, value, debug=False):\n for rec in wines:\n if rec[fld].isdigit():\n rec[fld] = value\n\n\ndef updateFileOptionDictCheck(optiondict, wines, header, debug=False):\n if optiondict['fldWineDescr'] not in wines[0]:\n if debug:\n print('updateFileOptionDictCheck:fldWineDescr NOT in file read in:'\n , optiondict['fldWineDescr'])\n if 'cnt' in wines[0]:\n print('setting values fldWineDescr and fldWineDescrNew to: cnt')\n optiondict['fldWineDescr'] = optiondict['fldWineDescrNew'] = 'cnt'\n elif 'winedescr' in wines[0]:\n print(\n 'setting values fldWineDescr to winedescr and fldWineDescrNew to winedescrnew'\n )\n optiondict['fldWineDescr'] = 'winedescr'\n optiondict['fldWineDescrNew'] = 'winedescrnew'\n else:\n print('could not find fldWineDescr in wines[0]-aborting:',\n optiondict['fldWineDescr'], '\\nwines[0]:', wines[0])\n error = wines[0][optiondict['fldWineDescr']]\n if False and optiondict['fldWineDescr'] == 'winedescr':\n if not optiondict['fldWineDescrMatch']:\n optiondict['fldWineDescrMatch'] = 'same'\n print('setting value fldWineDescrMatch to: same')\n if optiondict['csvfile_update_in'] == optiondict['csvfile_update_out']:\n file_path, base_filename, file_ext = kvutil.filename_split(optiondict\n ['csvfile_update_in'])\n backupfile = kvutil.filename_proper(base_filename + optiondict[\n 'backupfile_ext'], file_path)\n print('copying ', optiondict['csvfile_update_in'], ' to ', backupfile)\n shutil.copyfile(optiondict['csvfile_update_in'], backupfile)\n if optiondict['fldWineDescrNew'] == 'cnt':\n optiondict['csvdictkeys'] = ['cnt', 'date', 'search', 'store',\n 'wine', 'winesrt']\n elif optiondict['fldWineDescrMatch']:\n optiondict['csvdictkeys'] = [optiondict['fldWineDescr'], optiondict\n ['fldWineDescrNew'], optiondict['fldWineDescrMatch'], *header]\n else:\n optiondict['csvdictkeys'] = [optiondict['fldWineDescrNew']] + header[1:\n ]\n print('updateFileOptionDictCheck:set csvdictkeys to:', optiondict[\n 'csvdictkeys'])\n\n\n<mask token>\n", "step-4": "<mask token>\nimport kvutil\nimport kvcsv\nimport re\nimport sys\nimport shutil\nimport pprint\npp = pprint.PrettyPrinter(indent=4)\nppFlag = False\noptiondictconfig = {'AppVersion': {'value': '1.13', 'description':\n 'defines the version number for the app'}, 'debug': {'value': False,\n 'type': 'bool', 'description':\n 'defines if we are running in debug mode'}, 'verbose': {'value': 1,\n 'type': 'int', 'description':\n 'defines the display level for print messages'}, 'setup_check': {\n 'value': False, 'type': 'bool', 'description':\n 'defines if we checking out setup'}, 'pprint': {'value': False, 'type':\n 'bool', 'description':\n 'defines if we output with pretty print when debugging'},\n 'csvfile_master_in': {'value': 'wine_xref.csv', 'description':\n 'defines the name of the master data input file'}, 'csvfile_update_in':\n {'value': 'wineref.csv', 'description':\n 'defines the name of the input file to updated'}, 'csvfile_update_out':\n {'value': 'wineref2.csv', 'description':\n 'defines the name of the updated output file'}, 'fldWine': {'value':\n 'wine', 'description':\n 'defines the name of the field that holds the Wine '}, 'fldWineDescr':\n {'value': 'winedescr', 'description':\n 'defines the name of the field holding the wine description'},\n 'fldWineDescrNew': {'value': 'winedescrnew', 'description':\n 'defines the name of the NEW field holding the new description '},\n 'fldWineDescrMatch': {'value': None, 'description':\n 'defines the name of the NEW field holding the results of comparison existing to new description '\n }, 'fldWineMaster': {'value': None, 'description':\n 'defines the name of the field that holds the Wine when reading the master file '\n }, 'fldWineDescrMaster': {'value': None, 'description':\n 'defines the name of the field holding the wine description when reading the master file'\n }, 'backupfile_ext': {'value': '.bak', 'description':\n 'defines the extension to use to copy the update input file to if we are replacing it with output'\n }, 'defaultnew': {'value': None, 'description':\n 'defines if we should take field fldWineDescrNew and set to a value if not set'\n }}\nvintageLookup = re.compile('\\\\d\\\\d\\\\d\\\\d\\\\s+\\\\d\\\\d(\\\\d\\\\d)'), re.compile(\n '^\\\\d\\\\d(\\\\d\\\\d)'), re.compile('\\\\s\\\\d\\\\d(\\\\d\\\\d)$'), re.compile(\n '\\\\s\\\\d\\\\d(\\\\d\\\\d)\\\\s'), re.compile('XX\\\\d\\\\d(\\\\d\\\\d)\\\\s'), re.compile(\n '\\\\s\\\\d\\\\d(\\\\d\\\\d)\\\\/'), re.compile(\"\\\\s'?(\\\\d\\\\d)'?$|\\\\s'?(\\\\d\\\\d)'?\\\\s\")\nreCase = re.compile('12\\\\s*X\\\\s*750\\\\s*ML|\\\\bcase\\\\b|12\\\\/750\\\\s*ML', re.\n IGNORECASE)\nreQualLookup = (None, re.compile('\\\\bWithout\\\\s+Gift\\\\b|\\\\bNo\\\\s+Gift', re.\n IGNORECASE)), ('Gift', re.compile('\\\\bGift\\\\b', re.IGNORECASE)), ('VAP',\n re.compile('\\\\bVAP\\\\b', re.IGNORECASE)), ('VAP', re.compile(\n '\\\\bGlassVAP\\\\b', re.IGNORECASE)), ('Glass', re.compile('\\\\bGlass\\\\b',\n re.IGNORECASE)), ('Glass', re.compile('\\\\bGlasses\\\\b', re.IGNORECASE)), (\n 'Etch', re.compile('\\\\bEtch\\\\b', re.IGNORECASE)), ('Basket', re.compile\n ('\\\\bBasket\\\\b', re.IGNORECASE))\nsizeLookup = ('1.75L', re.compile('\\\\b1\\\\.75\\\\s*Li?|\\\\b1\\\\.75$', re.IGNORECASE)\n ), ('1.5L', re.compile('\\\\b1\\\\.5\\\\s*L?\\\\b|\\\\bMagnum\\\\b', re.IGNORECASE)), (\n '375mL', re.compile('Half\\\\s+Bottle|375ml', re.IGNORECASE)), ('200mL',\n re.compile('\\\\b200\\\\s*ML|\\\\(200\\\\s*ML', re.IGNORECASE)), ('50mL', re.\n compile('\\\\b50\\\\s*ML|\\\\(50\\\\s*ML', re.IGNORECASE)), ('500mL', re.\n compile('\\\\b500\\\\s*ML|\\\\(500\\\\s*ML', re.IGNORECASE)), ('3L', re.compile\n ('\\\\b3\\\\s*Li?', re.IGNORECASE)), ('6L', re.compile('\\\\b6\\\\s*Li?', re.\n IGNORECASE)), ('9L', re.compile('\\\\b9\\\\s*Li?', re.IGNORECASE)), ('1L',\n re.compile(\n '\\\\b1L\\\\b|\\\\b1\\\\s+L$|\\\\b1.0\\\\s*L\\\\b|\\\\b1\\\\s+Liter\\\\b|\\\\bOne\\\\s+Liter\\\\b|\\\\bLITER\\\\b|\\\\b1\\\\s*LTR'\n , re.IGNORECASE))\nwineryLookup = ('Alban', re.compile('\\\\bAlban\\\\b', re.IGNORECASE)), ('Arrowood'\n , re.compile('\\\\bArrowood\\\\b', re.IGNORECASE)), ('Atalon', re.compile(\n '\\\\bAtalon\\\\b', re.IGNORECASE)), ('Attune', re.compile('\\\\bAttune\\\\b',\n re.IGNORECASE)), ('Auteur', re.compile('\\\\bAuteur\\\\b', re.IGNORECASE)), (\n 'Austin Hope', re.compile('\\\\bAustin\\\\s+Hope\\\\b', re.IGNORECASE)), ('Badge'\n , re.compile('\\\\bBadge\\\\b', re.IGNORECASE)), ('Balletto', re.compile(\n '\\\\bBalletto\\\\b', re.IGNORECASE)), ('Bell', re.compile(\n '\\\\bBell\\\\s+Cellar', re.IGNORECASE)), ('BR Cohn', re.compile(\n '\\\\bB\\\\.?\\\\s?R\\\\.?\\\\s+Cohn\\\\b', re.IGNORECASE)), ('Bremer', re.compile(\n '\\\\bBremer\\\\b', re.IGNORECASE)), ('Brewer-Clifton', re.compile(\n '\\\\bBrewer[\\\\s\\\\-]Clifton\\\\b', re.IGNORECASE)), ('BV', re.compile(\n '\\\\bBeaulieu\\\\s+V|\\\\bBV\\\\b', re.IGNORECASE)), ('Belle Glos', re.compile\n ('\\\\bBelle\\\\s+Glos\\\\b', re.IGNORECASE)), ('Bennett Ln', re.compile(\n '\\\\bBennet+\\\\sLane\\\\b', re.IGNORECASE)), ('Benovia', re.compile(\n '\\\\bBenovia\\\\b', re.IGNORECASE)), ('Beringer', re.compile(\n '\\\\bBeringer\\\\b', re.IGNORECASE)), ('Blackstone', re.compile(\n '\\\\bBlackstone\\\\b', re.IGNORECASE)), ('Brancott', re.compile(\n '\\\\bBrancott\\\\b', re.IGNORECASE)), ('Cade', re.compile('\\\\bCade\\\\b', re\n .IGNORECASE)), ('Cain Five', re.compile(\n '\\\\bCain\\\\s+Five\\\\b|\\\\bCain\\\\s-\\\\sFive\\\\b|\\\\bCain\\\\s5\\\\b|\\\\bCainFive\\\\b',\n re.IGNORECASE)), ('Cakebread', re.compile('\\\\bCakebread\\\\b', re.IGNORECASE)\n ), ('Cardinale', re.compile('\\\\bCardinale\\\\b', re.IGNORECASE)), ('Caymus',\n re.compile('\\\\bCaymus\\\\b', re.IGNORECASE)), ('Chappellet', re.compile(\n '\\\\bChappellet\\\\b', re.IGNORECASE)), ('Chalk Hill', re.compile(\n '\\\\bChalk\\\\s+Hill\\\\b', re.IGNORECASE)), ('Clos Du Bois', re.compile(\n '\\\\bClos\\\\s+Du\\\\s+Bois\\\\b', re.IGNORECASE)), ('ClosDuVal', re.compile(\n '\\\\bClos\\\\s+du\\\\s+Val\\\\b', re.IGNORECASE)), ('Colgin', re.compile(\n '\\\\bColgin\\\\b', re.IGNORECASE)), ('Concha Don Melchor', re.compile(\n '\\\\bConcha\\\\s.*Don\\\\s+Melchor\\\\b|Don\\\\s+Melchor\\\\b', re.IGNORECASE)), (\n 'Continuum', re.compile('\\\\bContinuum\\\\b', re.IGNORECASE)), ('Corison',\n re.compile('\\\\bCorison\\\\b', re.IGNORECASE)), ('Cristal', re.compile(\n 'Roederer\\\\s?.*Cristal\\\\b|\\\\bCristal\\\\b.+Brut', re.IGNORECASE)), ('Curran',\n re.compile('\\\\bCurran\\\\b', re.IGNORECASE)), ('Darioush', re.compile(\n '\\\\bDarioush\\\\b', re.IGNORECASE)), ('Darioush', re.compile(\n '\\\\bCaravan\\\\b', re.IGNORECASE)), ('David Arthur', re.compile(\n '\\\\bDavid\\\\s+Arthur\\\\b', re.IGNORECASE)), ('David Bruce', re.compile(\n '\\\\bDavid\\\\s+Bruce\\\\b', re.IGNORECASE)), ('Davis Family', re.compile(\n '\\\\bDavis\\\\s+Family\\\\b', re.IGNORECASE)), ('Del Dotto', re.compile(\n '\\\\bDel\\\\s+Dotto\\\\b', re.IGNORECASE)), ('Dominus', re.compile(\n '\\\\bDominus\\\\b', re.IGNORECASE)), ('Goldeneye', re.compile(\n '\\\\bGoldeneye\\\\b', re.IGNORECASE)), ('Paraduxx', re.compile(\n '\\\\bParaduxx\\\\b', re.IGNORECASE)), ('Domaine Carneros', re.compile(\n '\\\\bDomaine\\\\s+Carneros\\\\b', re.IGNORECASE)), ('Dominus', re.compile(\n '\\\\Dominus\\\\b', re.IGNORECASE)), ('Drappier', re.compile(\n '\\\\bDrappier\\\\b', re.IGNORECASE)), ('Duckhorn', re.compile(\n '\\\\bDuckhorn\\\\b', re.IGNORECASE)), ('Dumol', re.compile('\\\\bDumol\\\\b',\n re.IGNORECASE)), ('Dunn', re.compile('\\\\bDunn\\\\b', re.IGNORECASE)), (\n 'Ehlers', re.compile('\\\\bEhlers\\\\b', re.IGNORECASE)), ('Etude', re.\n compile('\\\\bEtude\\\\b', re.IGNORECASE)), ('Far Niente', re.compile(\n '\\\\bFar Niente\\\\b', re.IGNORECASE)), ('Flora', re.compile(\n '\\\\bFlora\\\\s+Springs\\\\b', re.IGNORECASE)), ('Flowers', re.compile(\n '\\\\bFlowers\\\\b', re.IGNORECASE)), ('Robert Foley', re.compile(\n '\\\\bRobert\\\\s+\\\\bFoley\\\\b', re.IGNORECASE)), ('Foley', re.compile(\n '\\\\bFoley\\\\b', re.IGNORECASE)), ('Foxen', re.compile('\\\\bFoxen\\\\b', re.\n IGNORECASE)), ('Franciscan', re.compile('\\\\bFranciscan\\\\b', re.IGNORECASE)\n ), ('Frank Family', re.compile('\\\\bFrank Family\\\\b', re.IGNORECASE)), (\n 'Gary Farrell', re.compile('\\\\bGary\\\\s+Farrel+\\\\b', re.IGNORECASE)), (\n 'Ghost Block', re.compile('\\\\bGhost\\\\s+Block\\\\b', re.IGNORECASE)), (\n 'Grgich', re.compile('\\\\bGrgich\\\\b', re.IGNORECASE)), ('Groth', re.\n compile('\\\\bGroth\\\\b', re.IGNORECASE)), ('Gundlach', re.compile(\n '\\\\bGundlach\\\\b', re.IGNORECASE)), ('Hansel', re.compile('\\\\bHansel\\\\b',\n re.IGNORECASE)), ('Hanzell', re.compile('\\\\bHanzell\\\\b', re.IGNORECASE)), (\n 'Hess', re.compile('\\\\bHess\\\\b', re.IGNORECASE)), ('Hewitt', re.compile\n ('\\\\bHewitt\\\\b', re.IGNORECASE)), ('Hobbs', re.compile(\n '\\\\bHobbs\\\\b|\\\\bcrossbarn\\\\b', re.IGNORECASE)), ('Hundred Acre', re.\n compile('\\\\bHundred\\\\s+Acre\\\\b', re.IGNORECASE)), ('Jordan', re.compile\n ('\\\\bJordan\\\\b', re.IGNORECASE)), ('Justin', re.compile('\\\\bJustin\\\\b',\n re.IGNORECASE)), ('Kim Crawford', re.compile('\\\\bKim\\\\s+Crawford\\\\b',\n re.IGNORECASE)), ('Kistler', re.compile('\\\\bKistler\\\\b', re.IGNORECASE)), (\n 'Kosta', re.compile('\\\\bKosta\\\\s+Browne?\\\\b', re.IGNORECASE)), ('Krug',\n re.compile('\\\\bKrug\\\\b', re.IGNORECASE)), ('Kunde', re.compile(\n '\\\\bKunde\\\\b', re.IGNORECASE)), ('LaCrema', re.compile(\n '\\\\bLa\\\\s?Crema\\\\b', re.IGNORECASE)), ('Lewis', re.compile(\n '\\\\bLewis\\\\b', re.IGNORECASE)), ('Lokoya', re.compile('\\\\bLokoya\\\\b',\n re.IGNORECASE)), ('Meiomi', re.compile('\\\\bMeiomi\\\\b', re.IGNORECASE)), (\n 'Melville', re.compile('\\\\bMelville\\\\b', re.IGNORECASE)), ('Momento Mori',\n re.compile('\\\\bMomento\\\\s+Mori\\\\b', re.IGNORECASE)), ('Mondavi', re.\n compile('\\\\bMondavi\\\\b', re.IGNORECASE)), ('Montelena', re.compile(\n '\\\\bMontelena\\\\b', re.IGNORECASE)), ('Mt Veeder', re.compile(\n '^Mount\\\\s+Veeder\\\\b|^Mt\\\\.? Veeder\\\\b|\\\\d+\\\\s+M[^t]*t\\\\s+Veeder\\\\b',\n re.IGNORECASE)), ('Newton', re.compile('\\\\bNewton\\\\b', re.IGNORECASE)), (\n 'Nickel', re.compile('\\\\bNickel\\\\b', re.IGNORECASE)), ('Opus One', re.\n compile('\\\\bOpus\\\\s+One\\\\b', re.IGNORECASE)), ('P Togni', re.compile(\n '\\\\bTogni\\\\b', re.IGNORECASE)), ('Pahlmeyer Jayson', re.compile(\n '\\\\bJayson\\\\b', re.IGNORECASE)), ('Pahlmeyer', re.compile(\n '\\\\bPahlmeyer\\\\b(?!\\\\s*Jay)', re.IGNORECASE)), ('Papillon', re.compile(\n '\\\\bPapillon\\\\b', re.IGNORECASE)), ('Patz', re.compile('\\\\bPatz\\\\b', re\n .IGNORECASE)), ('Phelps', re.compile('\\\\bPhelps\\\\b', re.IGNORECASE)), (\n 'Plumpjack', re.compile('\\\\bPlumpjack\\\\b', re.IGNORECASE)), ('Pride',\n re.compile('\\\\bPride\\\\b', re.IGNORECASE)), ('Prisoner', re.compile(\n '\\\\bPrisoner\\\\b', re.IGNORECASE)), ('Provenance', re.compile(\n '\\\\bProvenance\\\\b', re.IGNORECASE)), ('R Sinskey', re.compile(\n '\\\\bSinskey\\\\b', re.IGNORECASE)), ('Ramey', re.compile('\\\\bRamey\\\\b',\n re.IGNORECASE)), ('Revana', re.compile('\\\\bRevana\\\\b', re.IGNORECASE)), (\n 'Raptor', re.compile('\\\\bRaptor\\\\s+Ridge\\\\b', re.IGNORECASE)), ('Revana',\n re.compile('\\\\bRevana\\\\b', re.IGNORECASE)), ('Ridge', re.compile(\n '\\\\bRidge\\\\b', re.IGNORECASE)), ('Robert Foley', re.compile(\n '\\\\bRobert\\\\s+Foley\\\\b', re.IGNORECASE)), ('Rombauer', re.compile(\n '\\\\bRombauer\\\\b', re.IGNORECASE)), ('Rudd', re.compile('\\\\bRudd\\\\b', re\n .IGNORECASE)), ('Scarecrow', re.compile('\\\\bScarecrow\\\\b', re.IGNORECASE)\n ), ('Sea Smoke', re.compile('\\\\bSea\\\\s+Smoke\\\\b', re.IGNORECASE)), (\n 'Seghesio', re.compile('\\\\bSeghesio\\\\b', re.IGNORECASE)), ('Shafer', re\n .compile('\\\\bShafer\\\\b', re.IGNORECASE)), ('Sherwin', re.compile(\n '\\\\bSherwin\\\\b', re.IGNORECASE)), ('Silver Oak', re.compile(\n '\\\\bSilver\\\\s+Oak\\\\b', re.IGNORECASE)), ('Silverado', re.compile(\n '\\\\bSilverado\\\\b', re.IGNORECASE)), ('Simi', re.compile('\\\\bSimi\\\\b',\n re.IGNORECASE)), ('Sonoma Cutrer', re.compile('\\\\bCutrer\\\\b', re.\n IGNORECASE)), ('Spottswoode', re.compile('\\\\bSpottswoode\\\\b', re.\n IGNORECASE)), ('Stag Leap', re.compile('\\\\bStag.*\\\\sLeap\\\\b', re.\n IGNORECASE)), ('Sullivan', re.compile('\\\\bSullivan\\\\b', re.IGNORECASE)), (\n 'Summerland', re.compile('\\\\bSummerland\\\\b', re.IGNORECASE)), ('Summers',\n re.compile('\\\\bSummers\\\\b', re.IGNORECASE)), ('Tantara', re.compile(\n '\\\\bTantara\\\\b', re.IGNORECASE)), ('Turnbull', re.compile(\n '\\\\bTurnbull\\\\b', re.IGNORECASE)), ('Veuve', re.compile('\\\\bVeuve\\\\b',\n re.IGNORECASE)), ('Viader', re.compile('\\\\bViader\\\\b', re.IGNORECASE)), (\n 'Waterstone', re.compile('\\\\bWaterstone\\\\b', re.IGNORECASE)), ('Whitehall',\n re.compile('\\\\bWhitehall\\\\b', re.IGNORECASE)), ('Wm Selyem', re.compile\n ('\\\\bWilliams\\\\s*\\\\-?Selyem\\\\b', re.IGNORECASE)), ('ZD', re.compile(\n '\\\\bZD\\\\b', re.IGNORECASE)), ('Zaca', re.compile('\\\\bZaca\\\\b', re.\n IGNORECASE)), ('zBourbon Woodford Res', re.compile(\n '\\\\bWoodford\\\\s+Reserve\\\\b', re.IGNORECASE)), ('zBourbon Woodford Res',\n re.compile('\\\\bWoodford\\\\s+Rsv\\\\b', re.IGNORECASE)), ('zCognac Courvoisier'\n , re.compile('\\\\bCourvoisier\\\\b', re.IGNORECASE)), ('zCognac Hennessy',\n re.compile('\\\\bHennesse?y\\\\b', re.IGNORECASE)), ('zCognac Remy', re.\n compile('\\\\bRemy\\\\s+Martin\\\\b|\\\\bRemy\\\\s+Louis', re.IGNORECASE)), (\n 'zCointreau', re.compile('\\\\bCointreau\\\\b', re.IGNORECASE)), (\n 'zGin Hendrick', re.compile('\\\\bHendrick', re.IGNORECASE)), (\n 'zGin Tanqueray', re.compile('\\\\bTanqueray\\\\b', re.IGNORECASE)), (\n 'zRum Mt Gay', re.compile('\\\\bMount\\\\s+Gay\\\\b|\\\\bMt\\\\s+Gay', re.IGNORECASE)\n ), ('zRum Ron Zacapa', re.compile('\\\\bRon\\\\s+Zacapa\\\\b', re.IGNORECASE)), (\n 'zRye Hayden', re.compile('\\\\bBasil\\\\s+Hayden\\\\b', re.IGNORECASE)), (\n 'zSambuca', re.compile('\\\\bSambuca\\\\b', re.IGNORECASE)), (\n 'zScotch Glenmorangie', re.compile('\\\\bGlenmorangie\\\\b', re.IGNORECASE)), (\n 'zScotch Hibiki Harmony', re.compile('\\\\bHibiki\\\\s.*Harmony\\\\b', re.\n IGNORECASE)), ('zScotch Hibiki', re.compile('\\\\bHibiki\\\\b(?!\\\\s*Har)',\n re.IGNORECASE)), ('zScotch Macallan', re.compile('\\\\bMacallan\\\\b', re.\n IGNORECASE)), ('zTeq Campo Azul', re.compile('\\\\bCampo\\\\s+Azul\\\\b', re.\n IGNORECASE)), ('zTeq Casamigos', re.compile('\\\\bCasamigos\\\\b', re.\n IGNORECASE)), ('zTeq Casino Azul', re.compile('\\\\bCasino\\\\s+Azul\\\\b',\n re.IGNORECASE)), ('zTeq Clase Azul', re.compile('\\\\bClase\\\\s+Azul\\\\b',\n re.IGNORECASE)), ('zTeq Cuervo', re.compile(\n '\\\\bJose\\\\s+Cuervo\\\\b|^Cuervo\\\\b', re.IGNORECASE)), ('zTeq Don Julio',\n re.compile('\\\\bDon\\\\s+Julio\\\\b', re.IGNORECASE)), ('zTeq Dos Artes', re\n .compile('\\\\bDos\\\\s+Artes\\\\b|^Cuervo\\\\b', re.IGNORECASE)), (\n 'zTeq Gran Cava', re.compile('\\\\bGran\\\\s+Cava\\\\b', re.IGNORECASE)), (\n 'zTeq Herradura', re.compile('\\\\bHerradura\\\\b', re.IGNORECASE)), (\n 'zTeq Loma Azul', re.compile('\\\\bLoma\\\\s+Azul\\\\b', re.IGNORECASE)), (\n 'zTeq Padre Azul', re.compile('\\\\bPadre\\\\s+Azul\\\\b', re.IGNORECASE)), (\n 'zTeq Partida', re.compile('\\\\bPartida\\\\b', re.IGNORECASE)), ('zTeq Patron'\n , re.compile('\\\\bPatron\\\\b', re.IGNORECASE)), ('zTripleSec Gr Marnier',\n re.compile('\\\\bGrand\\\\s+Marnier\\\\b', re.IGNORECASE)), (\n 'zTripleSec Dekuyper', re.compile('\\\\bDekuyper\\\\b', re.IGNORECASE)), (\n 'zTripleSec Hiram', re.compile('\\\\bHiram\\\\b', re.IGNORECASE)), (\n 'zVodka Absolut', re.compile('\\\\bAbsolut\\\\b', re.IGNORECASE)), (\n 'zVodka Skyy', re.compile('\\\\bSkyy\\\\b', re.IGNORECASE)), ('zVodka Tito',\n re.compile('\\\\bTito', re.IGNORECASE)), ('zWhiskey Balvenie', re.compile\n ('\\\\bBalvenie\\\\b', re.IGNORECASE)), ('zWhiskey J Walker', re.compile(\n '\\\\bJohn+ie\\\\s+Walker\\\\b', re.IGNORECASE))\ngrapeLookup = ('Cab Franc', re.compile(\n '\\\\bCabernet\\\\s+Franc|\\\\bCab\\\\s+Franc', re.IGNORECASE)), ('Cab', re.\n compile('\\\\bCabernet\\\\b|\\\\sCS\\\\s|\\\\sCS$|\\\\bCab\\\\b', re.IGNORECASE)), (\n 'Claret', re.compile('\\\\bClaret\\\\b', re.IGNORECASE)), ('Rose Pinot', re\n .compile('\\\\bRose\\\\b.*\\\\bPinot\\\\b|\\\\bPinot\\\\b.*\\\\bRose\\\\b', re.IGNORECASE)\n ), ('Pinot', re.compile('\\\\bPinot\\\\b|\\\\bPN\\\\b|\\\\bP\\\\s+Noir\\\\b', re.\n IGNORECASE)), ('Merlot', re.compile('\\\\bMerlot\\\\b|\\\\bME\\\\b', re.IGNORECASE)\n ), ('Sauv Blanc', re.compile('\\\\bSauvignon\\\\s+Blanc\\\\b|\\\\bSB\\\\b', re.\n IGNORECASE)), ('Sauv Blanc', re.compile(\n '\\\\bSauvignon\\\\/Fume\\\\s+Blanc\\\\b', re.IGNORECASE)), ('Meritage', re.\n compile('\\\\bMeritage\\\\b', re.IGNORECASE)), ('Fume', re.compile(\n '\\\\bFume\\\\b|\\\\bFum&#233;', re.IGNORECASE)), ('Champagne', re.compile(\n '\\\\bChampagne\\\\b', re.IGNORECASE)), ('Chard', re.compile(\n '\\\\bChar+d|\\\\bCH\\\\b', re.IGNORECASE)), ('Shiraz', re.compile(\n '\\\\bShiraz\\\\b', re.IGNORECASE)), ('Syrah', re.compile(\n '\\\\bSyrah\\\\b|\\\\bSY\\\\b', re.IGNORECASE)), ('Zin', re.compile(\n '\\\\bZinfandel\\\\b|\\\\bZIN\\\\b|\\\\bZN\\\\b', re.IGNORECASE)), ('Rose', re.\n compile('\\\\bRose\\\\b|\\\\bRos&#233;', re.IGNORECASE)), ('Sangiovese', re.\n compile('\\\\Sangiovese\\\\b', re.IGNORECASE)), ('Gewurzt', re.compile(\n '\\\\bGew.rztraminer\\\\b|\\\\bGew&#252;rzt', re.IGNORECASE)), ('Malbec', re.\n compile('\\\\bMalbec\\\\b', re.IGNORECASE)), ('Viognier', re.compile(\n '\\\\bViognier\\\\b', re.IGNORECASE)), ('Roussanne', re.compile(\n '\\\\bRoussanne\\\\b', re.IGNORECASE)), ('Charbono', re.compile(\n '\\\\bCharbono\\\\b', re.IGNORECASE)), ('PSirah', re.compile(\n '\\\\bPetite Sirah\\\\b', re.IGNORECASE)), ('Cuvee', re.compile(\n '\\\\bCuvee\\\\b', re.IGNORECASE)), ('Red', re.compile(\n '\\\\bRed\\\\b|\\\\bBordeaux\\\\s+Blend\\\\b', re.IGNORECASE)), ('Syrah-Cab', re.\n compile('\\\\bSyrcab\\\\b|\\\\bsyrah[-\\\\s\\\\/]+cab', re.IGNORECASE)), ('Grenache',\n re.compile('\\\\bGrenache\\\\b', re.IGNORECASE)), ('Tempranillo', re.\n compile('\\\\bTempranillo\\\\b', re.IGNORECASE))\nignoreGrapeLookup = {'Cristal': ['Rose', None], 'Domaine Carneros': ['Brut',\n None], 'Dominus': [None], 'Papillon': None, 'Paraduxx': None, 'Veuve':\n None, 'zCointreau': None, 'zGin Hendrick': None, 'zGin Tanqueray': [\n 'Ten', None], 'zTripleSec Gr Marnier': ['1880', '100th', 'Cent', 'Quin',\n None], 'zTripleSec Dekuyper': None, 'zTripleSec Hiram': None,\n 'zVodka Skyy': ['Citrus', None], 'zVodka Tito': None}\nnoGrapeLookup = {'Ehlers': ['120-80'], 'Alban': ['Pandora'], 'BV': [\n 'Tapestry', 'Latour'], 'Bennett Ln': ['Maximus'], 'Bremer': [\n 'Austintatious'], 'Cain Five': None, 'Colgin': ['Cariad', 'IX'],\n 'Concha Don Melchor': None, 'Continuum': None, 'Darioush': ['Duel',\n 'Darius'], 'Duckhorn': ['Discussion'], 'Far Niente': ['Dolce'], 'Flora':\n ['Trilogy'], 'Franciscan': ['Magnificat'], 'Grgich': ['Violetta'],\n 'Gundlach': ['Vintage Reserve'], 'Justin': ['Isosceles'], 'Krug': [\n 'Generations'], 'Mondavi': ['Maestro'], 'Newton': ['Puzzle'],\n 'Opus One': None, 'Phelps': ['Insignia'], 'Prisoner': ['Cuttings',\n 'Derange', 'Saldo', 'Blindfold'], 'Ridge': ['Monte Bello'],\n 'Robert Foley': ['Griffin'], 'Sullivan': ['Coeur de Vigne'], 'Zaca': [\n 'ZThree', 'ZCuvee'], 'zCognac Courvoisier': ['Napolean', 'VS', 'VSOP',\n 'XO'], 'zCognac Hennessy': ['Paradis', 'Richard', 'VS', 'VSOP', 'XO',\n 'Master'], 'zCognac Remy': ['1738', 'Louis XIII', 'VSOP', 'XO', 'VS'],\n 'zRum Ron Zacapa': ['23', 'Negra', 'XO'], 'zRye Hayden': ['Dark',\n 'Caribbean'], 'zScotch Hibiki Harmony': None, 'zTeq Campo Azul': [\n 'Extra Anejo', 'Anejo', 'Blanco', 'Reposado'], 'zTeq Casamigos': [\n 'Extra Anejo', 'Anejo', 'Blanco', 'Reposado'], 'zTeq Casino Azul': [\n 'Extra Anejo', 'Anejo', 'Blanco', 'Reposado', 'Silver'],\n 'zTeq Clase Azul': ['Ultra', 'Extra Anejo', 'Anejo', 'Blanco',\n 'Reposado', 'Mezcal', 'Plata', 'Platino'], 'zTeq Dos Artes': [\n 'Extra Anejo'], 'zTeq Gran Cava': ['Extra Anejo'], 'zTeq Loma Azul': [\n 'Extra Anejo', 'Anejo', 'Blanco', 'Reposado'], 'zTeq Partida': [\n 'Blanco', 'Elegante'], 'zVodka Absolut': ['Citron', 'Mandarin',\n 'Mandrin', 'Mango', 'Ruby', 'Vanilia', 'Raspberri', 'Grapevine', None],\n 'zWhiskey J Walker': ['Double Black', 'Black', 'Blue', 'Gold', 'Green',\n 'Platinum', 'Red', 'Swing', 'White', '18', '21']}\nliquorLookup = {'zRum Mt Gay': [('1703 Mst', re.compile('\\\\b1703\\\\b', re.\n IGNORECASE)), ('BB', re.compile('\\\\bBlack Barrel\\\\b', re.IGNORECASE)),\n ('Eclipse Silver', re.compile('\\\\bEclipse\\\\s+Silver\\\\b', re.IGNORECASE)\n ), ('Eclipse', re.compile('\\\\bEclipse\\\\b', re.IGNORECASE)), ('Old Peat',\n re.compile('\\\\bOld Peat', re.IGNORECASE)), ('Old Pot', re.compile(\n '\\\\bPot\\\\s+Still\\\\b', re.IGNORECASE)), ('Old', re.compile('\\\\bOld\\\\b',\n re.IGNORECASE)), ('Silver', re.compile('\\\\bSilver\\\\b', re.IGNORECASE)),\n ('XO Peat', re.compile('\\\\bXO\\\\b', re.IGNORECASE))],\n 'zScotch Glenmorangie': [('10', re.compile('\\\\b10(YR)?\\\\b', re.\n IGNORECASE)), ('14 Port', re.compile(\n '14.+\\\\bQuinta\\\\b|14.+\\\\bPort\\\\b|\\\\bQuinta\\\\b.+14|\\\\bPort\\\\b.+14', re.\n IGNORECASE)), ('12 Bacalta', re.compile('\\\\bBacalta\\\\b', re.IGNORECASE)\n ), ('12 Burgundy', re.compile('\\\\bBurgundy\\\\b', re.IGNORECASE)), (\n '12 Nectar', re.compile('\\\\bNectar\\\\b', re.IGNORECASE)), ('12 Port', re\n .compile('\\\\bQuinta\\\\b|\\\\bPort\\\\b', re.IGNORECASE)), ('12 Sherry', re.\n compile('\\\\bLa\\\\s?Santa\\\\b|\\\\bSherry\\\\b', re.IGNORECASE)), ('12 Signet',\n re.compile('\\\\bSignet\\\\b', re.IGNORECASE)), ('15 Cadboll', re.compile(\n '\\\\bCadboll', re.IGNORECASE)), ('15', re.compile('\\\\b15(YR)?\\\\b', re.\n IGNORECASE)), ('18', re.compile('\\\\b18(YR)?\\\\b|\\\\b18YEAR\\\\b', re.\n IGNORECASE)), ('25 Astar', re.compile('\\\\bAstar\\\\b', re.IGNORECASE)), (\n '25', re.compile('\\\\b25(YR)?\\\\b', re.IGNORECASE)), ('Companta', re.\n compile('\\\\bCompanta\\\\b', re.IGNORECASE)), ('Finealta', re.compile(\n '\\\\bFinealta\\\\b', re.IGNORECASE)), ('Milsean', re.compile(\n '\\\\bMilsean\\\\b', re.IGNORECASE)), ('Sonnalta', re.compile(\n '\\\\bSonnalta\\\\b', re.IGNORECASE))], 'zScotch Macallan': [('10 Fine', re\n .compile('\\\\bFine.*\\\\b10\\\\b|\\\\b10.*Fine')), ('10', re.compile(\n '\\\\b10\\\\b')), ('12 Double Gold', re.compile(\n '\\\\bDbl\\\\b.*Gold|\\\\bDouble\\\\b.*Gold', re.IGNORECASE)), ('12 Double', re\n .compile('\\\\bDouble\\\\s.*12(YR)?\\\\b', re.IGNORECASE)), ('12 Double', re.\n compile('\\\\b12\\\\s.*Double\\\\b', re.IGNORECASE)), ('12 Double', re.\n compile('\\\\bDbl\\\\b|\\\\bDouble\\\\b', re.IGNORECASE)), ('12 Edition 1', re.\n compile('\\\\bEdition\\\\s.*1\\\\b', re.IGNORECASE)), ('12 Edition 2', re.\n compile('\\\\bEdition\\\\s.*2\\\\b', re.IGNORECASE)), ('12 Edition 3', re.\n compile('\\\\bEdition\\\\s.*3\\\\b', re.IGNORECASE)), ('12 Edition 4', re.\n compile('\\\\bEdition\\\\s.*4\\\\b', re.IGNORECASE)), ('12 Sherry', re.\n compile('\\\\b12\\\\s.*Sherry\\\\b|\\\\bSherry\\\\b\\\\s.*\\\\b12', re.IGNORECASE)),\n ('12 Triple', re.compile('\\\\b12(YR)?\\\\s.*Triple\\\\b', re.IGNORECASE)), (\n '12 Triple', re.compile('\\\\bTriple\\\\s.*12\\\\b', re.IGNORECASE)), ('12',\n re.compile('\\\\b12(YR)?\\\\b', re.IGNORECASE)), ('15 Triple', re.compile(\n '\\\\b15(YR)?\\\\s.*Triple\\\\b|Triple.+\\\\b15(YR)?\\\\b', re.IGNORECASE)), (\n '15 Fine', re.compile('\\\\b15(YR)?\\\\b.*\\\\bFine\\\\b', re.IGNORECASE)), (\n '15', re.compile('\\\\b15(YR)?\\\\b', re.IGNORECASE)), ('17 Sherry', re.\n compile('\\\\b17(YR)?\\\\s.*Sherry\\\\b', re.IGNORECASE)), ('17 Fine', re.\n compile('\\\\b17(YR)?\\\\b.*\\\\bFine\\\\b', re.IGNORECASE)), ('17', re.compile\n ('\\\\b17(YR)?\\\\b', re.IGNORECASE)), ('18 Sherry', re.compile(\n '\\\\b18(YR)?\\\\s.*Sherry\\\\b|Sherry\\\\b.*18', re.IGNORECASE)), ('18 Triple',\n re.compile('\\\\b18(YR)?\\\\s.*Triple\\\\b|Triple.+\\\\b18(YR)?\\\\b', re.\n IGNORECASE)), ('18 Fine', re.compile('\\\\b18(YR)?\\\\b.*\\\\bFine\\\\b', re.\n IGNORECASE)), ('18 Gran', re.compile('Gran\\\\b.*\\\\b18', re.IGNORECASE)),\n ('18', re.compile('\\\\b18(YR)?\\\\b', re.IGNORECASE)), ('21 Fine', re.\n compile('\\\\b21.*Fine\\\\b', re.IGNORECASE)), ('21', re.compile(\n '\\\\b21(YR)?\\\\b', re.IGNORECASE)), ('25 Sherry', re.compile(\n '\\\\b25\\\\s.*Sherry\\\\b', re.IGNORECASE)), ('25', re.compile(\n '\\\\b25(YR)?\\\\b')), ('30 Sherry', re.compile('\\\\b30\\\\s.*Sherry', re.\n IGNORECASE)), ('30 Triple', re.compile(\n '\\\\b30(YR)?\\\\s.*Triple\\\\b|Triple.+\\\\b30(YR)?\\\\b', re.IGNORECASE)), (\n '30 Fine', re.compile('\\\\b30(YR)?\\\\b.*\\\\bFine\\\\b|Fine.*30', re.\n IGNORECASE)), ('30', re.compile('\\\\b30(YR)?\\\\b')), ('Rare', re.compile(\n '\\\\bRare\\\\b', re.IGNORECASE))], 'zTeq Cuervo': [('Especial Gold', re.\n compile('\\\\bEspecial\\\\b.*Gold\\\\b|Gold.*Especial', re.IGNORECASE)), (\n 'Especial Blue', re.compile('\\\\bEspecial\\\\b.*Blue\\\\b', re.IGNORECASE)),\n ('Especial', re.compile('\\\\bEspecial\\\\b', re.IGNORECASE)), (\n 'Familia Platino', re.compile('\\\\bPlatino\\\\b', re.IGNORECASE)), (\n 'Familia Anejo', re.compile('\\\\bFamilia\\\\b|\\\\bReserva\\\\b', re.\n IGNORECASE)), ('Gold', re.compile('\\\\bGold\\\\b', re.IGNORECASE)), (\n 'Reposado Lagavulin', re.compile('\\\\bReposado.*Lagavulin', re.\n IGNORECASE)), ('Tradicional Anejo', re.compile(\n 'Tradicional.*Anejo|Anejo.*Tradicional', re.IGNORECASE)), (\n 'Tradicional Reposado', re.compile(\n 'Tradicional.*Reposado|Reposado.*Tradicional', re.IGNORECASE)), (\n 'Tradicional Silver', re.compile('\\\\bTradicional\\\\b', re.IGNORECASE)),\n ('Tradicional Silver', re.compile('\\\\bTraditional\\\\b', re.IGNORECASE)),\n ('Reposado', re.compile('\\\\bReposado\\\\b', re.IGNORECASE)), ('Silver',\n re.compile('\\\\bSilver\\\\b', re.IGNORECASE))], 'zTeq Don Julio': [('1942',\n re.compile('\\\\b1942\\\\b', re.IGNORECASE)), ('Real', re.compile(\n '\\\\bReal\\\\b', re.IGNORECASE)), ('Anejo Claro 70th', re.compile(\n '\\\\b70th\\\\b', re.IGNORECASE)), ('Anejo Claro', re.compile(\n '\\\\bAnejo\\\\b\\\\s*Claro\\\\b', re.IGNORECASE)), ('Anejo', re.compile(\n '\\\\bAnejo\\\\b', re.IGNORECASE)), ('Blanco', re.compile('\\\\bBlanco\\\\b',\n re.IGNORECASE)), ('Reposado Lagavulin', re.compile(\n '\\\\bRepo.+Lagvulin\\\\b', re.IGNORECASE)), ('Reposado Dbl', re.compile(\n '\\\\bReposado.+Double\\\\b', re.IGNORECASE)), ('Reposado Dbl', re.compile(\n '\\\\bReposado.+Dbl\\\\b', re.IGNORECASE)), ('Reposado Dbl', re.compile(\n '\\\\bDouble.+Reposado\\\\b', re.IGNORECASE)), ('Reposado Private', re.\n compile('\\\\bReposado.+Private\\\\b', re.IGNORECASE)), ('Reposado', re.\n compile('\\\\bReposado\\\\b', re.IGNORECASE)), ('Silver', re.compile(\n '\\\\bSilver\\\\b', re.IGNORECASE))], 'zTeq Herradura': [('Ultra', re.\n compile('\\\\bUltra\\\\b', re.IGNORECASE)), ('Suprema', re.compile(\n '\\\\bSuprema\\\\b', re.IGNORECASE)), ('Anejo', re.compile('\\\\bAnejo\\\\b',\n re.IGNORECASE)), ('Blanco', re.compile('\\\\bBlanco\\\\b', re.IGNORECASE)),\n ('Reposado Gold', re.compile(\n '\\\\bReposado\\\\s+Gold\\\\b|\\\\bGold\\\\s+Reposado\\\\b', re.IGNORECASE)), (\n 'Reposado Scotch', re.compile(\n '\\\\bReposado.+Scotch\\\\b|\\\\bScotch.+Reposado\\\\b', re.IGNORECASE)), (\n 'Reposado Port', re.compile('\\\\bPort.+Reposado\\\\b|\\\\bReposado.+Port\\\\b',\n re.IGNORECASE)), ('Reposado', re.compile('\\\\bReposado\\\\b', re.\n IGNORECASE)), ('Silver', re.compile('\\\\bSilver\\\\b', re.IGNORECASE))],\n 'zTeq Patron': [('Gran Piedra', re.compile('\\\\bPiedra\\\\b', re.\n IGNORECASE)), ('DELETE Roca DELETE', re.compile('\\\\bRoca\\\\b', re.\n IGNORECASE)), ('Anejo Extra Lalique', re.compile('\\\\bLalique\\\\b', re.\n IGNORECASE)), ('Anejo Extra 7yr', re.compile(\n '\\\\b7YR\\\\b|\\\\b7 anos\\\\b|\\\\b7 year\\\\b', re.IGNORECASE)), (\n 'Anejo Extra 5yr', re.compile('\\\\b5YR\\\\b|\\\\b5 anos\\\\b|\\\\b5 year\\\\b', re\n .IGNORECASE)), ('Anejo Extra 10yr', re.compile(\n '\\\\b10\\\\b.+\\\\bExtra\\\\b|\\\\bExtra\\\\b.+10', re.IGNORECASE)), (\n 'Anejo Extra', re.compile('\\\\bExtra\\\\s+Anejo\\\\b', re.IGNORECASE)), (\n 'Gran Anejo', re.compile('\\\\bGran\\\\s+Anejo\\\\b', re.IGNORECASE)), (\n 'Gran Anejo', re.compile('\\\\bBurdeos\\\\b', re.IGNORECASE)), (\n 'Gran Smoky', re.compile('\\\\bGran\\\\s+.*Smoky\\\\b', re.IGNORECASE)), (\n 'Anejo', re.compile('\\\\bAnejo\\\\b', re.IGNORECASE)), ('Gran Platinum',\n re.compile('\\\\bPlatinum\\\\b', re.IGNORECASE)), ('Reposado', re.compile(\n '\\\\bReposado\\\\b', re.IGNORECASE)), ('Silver LTD', re.compile(\n '\\\\bSilver.*Limited\\\\b|\\\\bLimited.*Silver\\\\b', re.IGNORECASE)), (\n 'Silver Estate', re.compile('\\\\bEstate.*Silver\\\\b|\\\\bSilver.*Estate\\\\b',\n re.IGNORECASE)), ('Silver', re.compile('\\\\bSilver\\\\b', re.IGNORECASE)),\n ('Blanco', re.compile('\\\\bBlanco\\\\b', re.IGNORECASE))],\n 'zTeq Padre Azul': [('Blanco', re.compile('\\\\bsilver\\\\b', re.IGNORECASE\n ))], 'zWhiskey Balvenie': [('12 Double', re.compile(\n '\\\\bDouble.*12(YR)?\\\\b', re.IGNORECASE)), ('12 Double', re.compile(\n '\\\\b12(YR)?\\\\s.*Double', re.IGNORECASE)), ('12 First', re.compile(\n '\\\\b12(YR)?\\\\s.*First', re.IGNORECASE)), ('12 USA', re.compile(\n '\\\\b12.*American|American.*12', re.IGNORECASE)), ('12 Toast', re.\n compile('\\\\b12(YR)?\\\\s.*Toast', re.IGNORECASE)), ('12', re.compile(\n '\\\\b12(YR)?\\\\b', re.IGNORECASE)), ('14 Carib', re.compile(\n '\\\\b14(YR)?\\\\s.*Carib', re.IGNORECASE)), ('14 Carib', re.compile(\n '\\\\b14(YR)?\\\\s.*CB\\\\s+Cask', re.IGNORECASE)), ('14 Carib', re.compile(\n '\\\\bCarr?ib', re.IGNORECASE)), ('14 Peat', re.compile(\n '\\\\b14(YR)?\\\\s.*Peat', re.IGNORECASE)), ('15 Sherry', re.compile(\n '\\\\b15(YR)?\\\\s.*Sherry\\\\b', re.IGNORECASE)), ('15 Sherry', re.compile(\n '\\\\bSherry\\\\s+.*15(YR)?\\\\b', re.IGNORECASE)), ('15', re.compile(\n '\\\\b15(YR)?\\\\b', re.IGNORECASE)), ('16 Triple', re.compile(\n '\\\\b16(YR)?\\\\s.*Triple\\\\b', re.IGNORECASE)), ('17 Sherry Double', re.\n compile('\\\\b17(YR)?\\\\s.*Sherry\\\\s+Doub', re.IGNORECASE)), ('17 Sherry',\n re.compile('\\\\b17(YR)?\\\\s.*Sherry', re.IGNORECASE)), ('17 Double', re.\n compile('\\\\b17(YR)?\\\\s.*Double', re.IGNORECASE)), ('17 Double', re.\n compile('\\\\bDouble.*17(YR)?\\\\b', re.IGNORECASE)), ('17 Peat', re.\n compile('\\\\b17(YR)?\\\\s.*Peat', re.IGNORECASE)), ('17 Peat', re.compile(\n '\\\\bPeat.*17(YR)?\\\\b', re.IGNORECASE)), ('17', re.compile(\n '\\\\b17(YR)?\\\\b', re.IGNORECASE)), ('21 Port', re.compile('\\\\b21.*Port',\n re.IGNORECASE)), ('21 Port', re.compile('\\\\bPort.*21\\\\b', re.IGNORECASE\n )), ('21', re.compile('21', re.IGNORECASE)), ('25', re.compile(\n '\\\\b25(YR)?\\\\b', re.IGNORECASE)), ('30', re.compile('\\\\b30(YR)?\\\\b', re\n .IGNORECASE)), ('40', re.compile('\\\\b40(YR)?\\\\b', re.IGNORECASE))],\n 'zBourbon Woodford Res': [('Dbl', re.compile('\\\\bDouble\\\\b', re.\n IGNORECASE)), ('Derby', re.compile('\\\\bDerby\\\\b', re.IGNORECASE)), (\n 'Rye Choc', re.compile('\\\\bChocolate.*Rye\\\\b', re.IGNORECASE)), ('Rye',\n re.compile('\\\\bRye\\\\b', re.IGNORECASE)), ('Brandy', re.compile(\n '\\\\bBrandy\\\\b', re.IGNORECASE)), ('Batch', re.compile('\\\\bBatch\\\\b', re\n .IGNORECASE)), ('Barrel', re.compile('\\\\bBarrel\\\\b', re.IGNORECASE)), (\n 'Master', re.compile('\\\\bMasters?\\\\b', re.IGNORECASE)), ('Malt', re.\n compile('\\\\bMalt\\\\b', re.IGNORECASE)), ('Maple', re.compile(\n '\\\\bMaple\\\\b', re.IGNORECASE)), ('Wheat', re.compile('\\\\bWheat\\\\b', re.\n IGNORECASE)), ('', re.compile('\\\\bWoodford\\\\b', re.IGNORECASE))],\n 'zSambuca': [('Romana Black', re.compile(\n '\\\\bRomana.*\\\\bBlack\\\\b|\\\\bBlack\\\\s+Romana\\\\b', re.IGNORECASE)), (\n 'Romana', re.compile('\\\\bRomana\\\\b', re.IGNORECASE)), ('Di Amore', re.\n compile('\\\\bdi Amore\\\\b', re.IGNORECASE))], 'zScotch Hibiki': [('12',\n re.compile('\\\\b12\\\\s*YE?A?R\\\\b', re.IGNORECASE)), ('17 Limited', re.\n compile('\\\\b17\\\\s*YE?A?R\\\\b.+Limited', re.IGNORECASE)), ('17', re.\n compile('\\\\b17\\\\s*YE?A?R\\\\b', re.IGNORECASE)), ('21 Limited', re.\n compile('\\\\b21\\\\s*YE?A?R\\\\b.+Limited', re.IGNORECASE)), ('21', re.\n compile('\\\\b21\\\\s*YE?A?R\\\\b', re.IGNORECASE)), ('30', re.compile(\n '\\\\b30\\\\s*YE?A?R\\\\b', re.IGNORECASE))]}\nwineAbbrLookup = {'120-80': '\\\\bOne\\\\s+Twenty\\\\s+Over\\\\s+Eighty\\\\b',\n '3Amigos': '\\\\bThree\\\\s+Amigos\\\\b', '3Palms': '\\\\bThree\\\\s+Palms\\\\b',\n '3Sister': '\\\\bThree\\\\s+Sisters?\\\\b', '4Barrell':\n '\\\\b4[\\\\-\\\\s]Barrels?\\\\b', 'Alex': '\\\\bAlexander\\\\b', 'And':\n '\\\\bAnderson\\\\b', 'Car': '\\\\bCarneros\\\\b', 'Carries': '\\\\bCarrie', 'CC':\n '\\\\bC\\\\.?C\\\\.?\\\\s+Ranch\\\\b', 'Clone4': '\\\\bClone\\\\s+4\\\\b', 'Clone6':\n '\\\\bClone\\\\s+6\\\\b', 'Crossbarn': '\\\\bCross\\\\s+Barn\\\\b', 'Donna':\n '\\\\bDonna', 'Est': '\\\\bEstate\\\\b', 'Estate': '\\\\bEst\\\\b', 'Gap':\n '\\\\bGap|\\\\s%27Gap', 'Gary': '\\\\bGary', 'Julia': '\\\\bJulia', 'Knights':\n '\\\\bKnight', 'KistlerVnyd': '\\\\bKistler (Vineyard|VYD|EST)\\\\b', 'LP':\n '\\\\bLes Pierres\\\\b', 'Lyn': '\\\\bLyndenhur?st\\\\b', 'Mont':\n '\\\\bMonterey\\\\b', 'Mt': '\\\\bMount\\\\b|\\\\bMt\\\\.\\\\b', 'Napa/Son':\n '\\\\bNapa.*Son', 'Oak': '\\\\bOakville\\\\b', 'One-Pt-5':\n '\\\\bOne\\\\s+Point\\\\s+Five\\\\b', 'Pomm': '\\\\bPommeraie\\\\b', 'Priv':\n '\\\\bPrivate\\\\b', 'RR': '\\\\bRussian\\\\s+Rivers?\\\\b|RRV', 'RRR':\n '\\\\bRussian\\\\s+Rivers?\\\\b|RRV', 'Res':\n '\\\\bReserve\\\\b|\\\\bRsv\\\\b|\\\\bResrv\\\\b|\\\\bReserv\\\\b|\\\\bReserve$', 'Rose':\n '\\\\bRos&#233;|\\\\bROS&EACUTE;|\\\\bRos%E9', 'Ruth': '\\\\bRutherford\\\\b',\n 'Sandy': '\\\\bSandy', 'Samanthas': '\\\\bSamantha', 'SC':\n '\\\\bSanta\\\\s+Cruz\\\\b', 'SLD': '\\\\bStag.*Leap\\\\b', 'SLH':\n '\\\\bSanta\\\\s+Lucia\\\\b', 'SMV': '\\\\bSanta\\\\s+Maria|\\\\bS\\\\s+Maria', 'SRH':\n '\\\\bSTA\\\\.?|\\\\bSANTA\\\\s+Rita\\\\b|\\\\bSTA\\\\sRITA\\\\sHILLS|\\\\bS\\\\s+RITA\\\\b',\n 'SS': '\\\\bSpecial\\\\s+\\\\Selection\\\\b', 'Stage': '\\\\bStagecoach\\\\b',\n 'Son': '\\\\bSonoma\\\\b', 'SYV': '\\\\bSanta\\\\s+Ynez\\\\s+Valley\\\\b', 'TD9':\n '\\\\bTD\\\\s+9\\\\b|\\\\bTD-9\\\\b', 'Terraces': '\\\\bTerrace', 'TheCutrer':\n '\\\\bThe Cutrer\\\\b|nnay Cutrer\\\\b', 'Tok':\n '\\\\bTo[\\\\s\\\\-]?Kolan|\\\\bTo[\\\\s\\\\-]?Kalon', 'Turn4': '\\\\bTurn\\\\s+4\\\\b',\n 'Vernas': '\\\\bVerna', 'Vine': '\\\\bVines\\\\b', 'Yount':\n '\\\\bYountville\\\\b', 'ZThree': '\\\\bZ.*\\\\bThree\\\\b', 'ZCuvee':\n '\\\\bZ.*\\\\bCuvee\\\\b|\\\\bCuvee Z\\\\b', 'Agustina': '\\\\bAugustina\\\\b',\n 'Durell': '\\\\bDurrell\\\\b', 'Benchland': '\\\\bBenchlands\\\\b', 'Pritchard':\n '\\\\bPitchard\\\\b'}\nreShipsAs = re.compile('\\\\(ships?\\\\s', re.IGNORECASE)\ndefaultorderlist = [['Tok'], ['Oak'], ['Res'], ['RR'], ['Landslide'], [\n 'Yount'], ['RRR'], ['Son'], ['Ruth'], ['Napa'], ['Helena'], ['SRH'], [\n 'SLH'], ['SMV'], ['SLD'], ['Paso'], ['Alex'], ['Single'], ['Estate']]\n\n\ndef globalVariableCheck(debug=False):\n for liquor in liquorLookup:\n if liquor in noGrapeLookup:\n print(\n 'WARNING:liquorLookup regexs will never execute - they are in noGrapeLookup:'\n , liquor)\n if liquor in ignoreGrapeLookup:\n print(\n 'WARNING:liquorLookup regexs will never execute - they are in ignoreGrapeLookup:'\n , liquor)\n for winery in ignoreGrapeLookup:\n if winery in noGrapeLookup:\n print(\n 'WARNING:ignoreGrapeLookup regexs will never execute - they are in noGrapeLookup:'\n , winery)\n\n\ndef setOptionDictMasterFldValues(optiondict, debug=False):\n for fld in ('fldWine', 'fldWineDescr'):\n if not optiondict[fld + 'Master']:\n optiondict[fld + 'Master'] = optiondict[fld]\n\n\ndef wineLookupByName(nameLookup, lookupStr, other, msg, wineAbbrLookup=None,\n debug=False):\n funcname = 'wineLookupByName:' + msg + ':'\n if debug:\n print(funcname + 'nameLookup:', nameLookup)\n if nameLookup is None:\n if debug:\n print(funcname + 'match: value is none - continue on')\n return ''\n for name in nameLookup:\n if debug:\n print(funcname + 'match-name:', name)\n if name is None:\n if debug:\n print(funcname +\n 'name-matched: value is none - continue on:pass back blank'\n )\n return ''\n reName = re.compile('\\\\b' + name + '\\\\b', re.IGNORECASE)\n if reName.search(lookupStr):\n if debug:\n print(funcname + 'name-MATCHED:', name)\n for val in other:\n if reName.search(val):\n other.remove(val)\n if debug:\n print(funcname + 'name-remove-from-other:', val)\n return name\n if wineAbbrLookup and name in wineAbbrLookup:\n reName = re.compile(wineAbbrLookup[name], re.IGNORECASE)\n if debug:\n print(funcname + 'Abbr-match-name:', name)\n if reName.search(lookupStr):\n if debug:\n print(funcname + 'Abbr-name-MATCHED:', wineAbbrLookup[name]\n )\n for val in other:\n if reName.search(val):\n other.remove(val)\n if debug:\n print(funcname + 'name-remove-from-other:', val)\n return name\n if debug:\n print(funcname + 'name match not found:set to blank')\n return None\n\n\ndef findQualifier(wine, debug=False):\n for val, reSearch in reQualLookup:\n if reSearch.search(wine):\n if debug:\n print('findQualifier:matched-returning:', val)\n return val\n if debug:\n print('findQualifier:no-match-returning:', None)\n return None\n\n\ndef findWinery(rec, lastWinery, lastReWinery, fldWine, debug=False):\n if lastWinery:\n if debug:\n try:\n print('fw:new winery:', rec[fldWine])\n except Exception as e:\n print('debug error8-continuing:', str(e))\n print('rec[fldWine]:type:', type(rec[fldWine]))\n print('fw:checking if this is lastWinery:', lastWinery)\n if lastReWinery.search(rec[fldWine]):\n if debug:\n print('fw:this matches the last winery')\n return lastWinery, lastReWinery\n elif debug:\n print('fw:not last winery')\n for winery, reWinery in wineryLookup:\n if debug:\n print('fw:not lastWinery-checking winery:', winery)\n if fldWine not in rec:\n print('not a column in this record fldWine:', fldWine)\n print('rec:', rec)\n if reWinery.search(rec[fldWine]):\n if debug:\n print('fw:winery match found:', winery)\n return winery, reWinery\n return None, None\n\n\ndef findLiquor(rec, winery, fldWine, debug=False):\n for liquor, reLiquor in liquorLookup[winery]:\n if debug:\n print('fl:checking liquor:', liquor)\n if reLiquor.search(rec[fldWine]):\n if debug:\n print('fl:liquor match found:', liquor)\n return liquor, reLiquor\n return None, None\n\n\ndef findGrapeByRegex(rec, fldWine, debug=False):\n for grape, reGrape in grapeLookup:\n if debug:\n print('fgbr:grape:', grape)\n if grape is not None and reGrape.search(rec[fldWine]):\n if debug:\n print('fgbr:grape match found:', grape)\n return grape, reGrape\n return None, None\n\n\ndef findStrInRecReturnOther(rec, fldWineDescr, findStr, debug=False):\n matchLoc = rec[fldWineDescr].find(findStr)\n if matchLoc > -1:\n other = rec[fldWineDescr][matchLoc + len(findStr) + 1:].split()\n if debug:\n print('fsirro:findStr matched:', findStr)\n if debug:\n print('fsirro:findStr other:', other)\n return findStr, other\n if debug:\n print('fsirro:findStr did not match using:', findStr)\n return None, []\n\n\ndef findGrapeByStr(rec, fldWineDescr, debug=False):\n for grape, reGrape in grapeLookup:\n if debug:\n print('fg:grape:', grape)\n grape, other = findStrInRecReturnOther(rec, fldWineDescr, grape,\n debug=debug)\n if grape:\n return grape, other\n return None, []\n\n\ndef findVintage(rec, fldWine, debug=False):\n for reVintage in vintageLookup:\n m = reVintage.search(rec[fldWine])\n if m:\n if m.group(1):\n vintage = m.group(1)\n if debug:\n print('fv:vintage-match:', reVintage, ':group1')\n elif m.group(2):\n vintage = m.group(2)\n if debug:\n print('fv:vintage-match:', reVintage, ':group2')\n elif m.group(3):\n vintage = m.group(3)\n if debug:\n print('fv:vintage-match:', reVintage, ':group3')\n else:\n vintage = m.group(4)\n if debug:\n print('fv:vintage-match:', reVintage, ':group4')\n return vintage\n return None\n\n\ndef buildWineryGrapeLookup(wines, fldWineDescr='winedescr', fldWine='wine',\n debug=False):\n wgLookup = {}\n lastWinery = None\n lastReWinery = None\n for rec in wines:\n if debug:\n print('bwgl:new rec:', rec[fldWineDescr])\n if not fldWineDescr in rec:\n print('creating-field:', fldWineDescr)\n rec[fldWineDescr] = ''\n winery = grape = wine = liquor = None\n other = []\n lastWinery, lastReWinery = winery, reWinery = findWinery(rec,\n lastWinery, lastReWinery, fldWine, debug=debug)\n if not winery:\n if debug:\n print('bwgl:did not find winery-skipping:', rec[fldWine])\n continue\n if winery in ignoreGrapeLookup:\n wine = ''\n if debug:\n print('bwgl:wine check ignoreGrapeLookup on winery:', winery)\n elif winery in noGrapeLookup:\n if debug:\n print('bwgl:wine check noGrapeLookup on winery:', winery)\n wine = wineLookupByName(noGrapeLookup[winery], rec[fldWineDescr\n ], [], 'noGrapeLookup', debug=debug)\n if False and wine == '':\n if debug:\n print('bwgl:nograpelookup:no-match:set wine to None')\n wine = None\n elif winery in liquorLookup:\n if debug:\n print('bwgl:liquor check on winery:', winery)\n liquor, reLiquor = findLiquor(rec, winery, fldWine, debug=debug)\n if liquor is not None:\n wine = liquor\n if debug:\n print('bwgl:liquor found and put in wine:', wine)\n if wine is None:\n if debug:\n print('bwgl:grape check because wine is None')\n grape, other = findGrapeByStr(rec, fldWineDescr)\n if debug:\n print('bwgl:grape:', grape, ':other:', other)\n elif debug:\n print('bwgl:grape check skipped - we have a wine')\n if wine is None and grape is None:\n if debug:\n print('bwgl:record skipped - no grape or wine defined')\n continue\n if grape is None:\n if debug:\n print('bwgl:build other from winery')\n wineryFind, other = findStrInRecReturnOther(rec, fldWineDescr,\n winery, debug=debug)\n if 'case' in other:\n other.remove('case')\n if debug:\n print('bwgl:remove case from other')\n if other:\n if debug:\n print('bwgl:looking at other for quals, bottlesize and vintage'\n )\n if not other[-1].isdigit():\n for qual, reQual in reQualLookup:\n if qual == other[-1]:\n if debug:\n print('bwgl:remove qualifier from other:', qual)\n del other[-1]\n break\n if other and not other[-1].isdigit():\n for size, reSize in sizeLookup:\n if size == other[-1]:\n if debug:\n print('bwgl:remove bottlesize from other:', size)\n del other[-1]\n break\n if other and other[-1].isdigit():\n if winery in ignoreGrapeLookup and ignoreGrapeLookup[winery\n ] and other[-1] in ignoreGrapeLookup[winery]:\n if debug:\n print(\n 'bwgl:value is in ignoreLookupGrape - keeping it:',\n other[-1])\n else:\n if debug:\n print('bwgl:remove vintage from other:', other[-1])\n del other[-1]\n if wine and wine in other:\n other.remove(wine)\n if debug:\n print('bwgl:remove wine from other:', wine)\n if debug:\n try:\n print('bwgl:Final-Build:', winery, ':', grape, ':', wine,\n ':', liquor, ':', other, ':', rec[fldWineDescr], ':',\n rec[fldWine])\n except Exception as e:\n print('debug error2-continuing:', str(e))\n print('fldWine:', fldWine)\n if grape is None and wine is not None:\n grape = wine\n if debug:\n print('bwgl:set-grape-to-wine:', grape)\n if debug:\n print('bwgl:create wgLookup for winery:', winery, ':grape:', grape)\n if winery not in wgLookup:\n wgLookup[winery] = {grape: []}\n elif grape not in wgLookup[winery]:\n wgLookup[winery][grape] = []\n if other and other not in wgLookup[winery][grape]:\n wgLookup[winery][grape].append(other)\n if debug:\n print('bwgl:appending to wgLookup:other:', other)\n if debug:\n print('bwgl:complete-read-of-master-file:sort wgLookup')\n for winery in wgLookup:\n for grape in wgLookup[winery]:\n wgLookup[winery][grape] = sorted(wgLookup[winery][grape], key=\n len, reverse=True)\n if debug:\n print('\\n' * 5)\n print('START WGLOOKUP DUMPED')\n print('#' * 80)\n if ppFlag:\n pp.pprint(wgLookup)\n else:\n print('bwgl:final-wgLookup:\\n', wgLookup)\n print('#' * 80)\n return wgLookup\n\n\ndef findAddAttribWgLookup(rec, winery, value, fldWine, AbbrLookup=[],\n defaultorderlist=None, valueDescr='', debug=False):\n singlematch = []\n if debug:\n try:\n print('faawl:value:', valueDescr, ':match-wgLookup:', rec[\n fldWine], ':', wgLookup[winery][value])\n except Exception as e:\n print('debug error7-continuing:', str(e))\n print('fldWine:', fldWine)\n for valuematchset in wgLookup[winery][value]:\n if debug:\n print('faawl:testing valuematchset:', valuematchset, ':length:',\n len(valuematchset))\n allmatch = True\n for valuematch in valuematchset:\n reMatch1 = re.compile('\\\\b' + valuematch + '\\\\b', re.IGNORECASE)\n reMatch2 = re.compile('\\\\s' + valuematch + '\\\\s', re.IGNORECASE)\n m1 = reMatch1.search(rec[fldWine])\n m2 = reMatch2.search(rec[fldWine])\n if m1 or m2:\n allmatch = True and allmatch\n elif valuematch in AbbrLookup:\n if debug:\n print('faawl:valuematch-abbr:', valuematch, ':',\n wineAbbrLookup[valuematch])\n reMatch = re.compile(wineAbbrLookup[valuematch], re.IGNORECASE)\n allmatch = reMatch.search(rec[fldWine]) and allmatch\n else:\n allmatch = False and allmatch\n if debug:\n print('faawl:valuematch:', valuematch, ':allmatch:', allmatch)\n if allmatch:\n if debug:\n print('faawl:value matched:', valuematchset)\n if len(valuematchset) == 1:\n if debug:\n print('faawl:single-valuematch-set-added-to-singlematch:',\n valuematchset)\n singlematch.append(valuematchset)\n else:\n if debug:\n print('faawl:multivalue-valuematch-set-found:done')\n return valuematchset\n if not singlematch:\n if debug:\n print('faawl:exit with singlematch NOT populated return blank')\n return []\n if debug:\n print('faawl:exit with singlematch populated:', singlematch)\n if len(singlematch) == 1 or not defaultorderlist:\n if debug:\n print('faawl:return first entry in singlematch:', singlematch[0])\n return singlematch[0]\n defaultorder = defaultorderlist[:]\n if debug:\n print('faawl:multiple single match value-singlematch:', singlematch)\n for val in singlematch[::-1]:\n if val not in defaultorder:\n defaultorder.insert(0, val)\n if winery == 'Mondavi' and ['Tok'] in singlematch:\n if debug:\n print('faawl:Change from:', valuematchset, ':to Tok for mondavi')\n return ['Tok']\n for val in defaultorder:\n if val in singlematch:\n if debug:\n print('faawl:selected-singlematch-value:', val)\n return val\n if debug:\n print('faawl:valuematchset-empty')\n return []\n\n\ndef setWineryDescrFromWineryGrapeLookup(wgLookup, wines, fldWineDescr=\n 'winedescr', fldWine='wine', fldWineDescrNew='winedescrnew',\n fldWineDescrMatch=False, debug=False):\n if debug:\n print('\\n' * 10,\n 'START WINEDESCR SETTING HERE ---------------------------------------------'\n )\n for rec in wines:\n (winery) = (grape) = (wine) = (vintage) = (case) = (size) = (liquor\n ) = (nongrape) = (qual) = None\n winematchset = grapematchset = []\n if debug:\n try:\n print('setWinery:fldWine:', rec[fldWine])\n except Exception as e:\n print('debug error2-continuing:', str(e))\n print('fldWine:', fldWine)\n if fldWineDescrNew not in rec:\n rec[fldWineDescrNew] = rec[fldWineDescr]\n winery, reWinery = findWinery(rec, None, None, fldWine, debug=debug)\n if winery is None:\n if debug:\n print('setWinery:winery not found-next record:' + rec[fldWine])\n continue\n elif winery not in wgLookup:\n if debug:\n print('setWinery:winery not in wgLookup:', winery)\n continue\n grape, reGrape = findGrapeByRegex(rec, fldWine, debug=debug)\n if debug:\n print('setWinery:grape found:', grape)\n if winery in ignoreGrapeLookup:\n if debug:\n print(\n 'setWinery:winery-match-ignoreGrape:clear-wine:set-grape-to-None:set-nongrape-True:winery:'\n , winery)\n wine = ''\n grape = None\n nongrape = True\n if winery in noGrapeLookup:\n if debug:\n print('setWinery:noGrapeLookup wine check:', winery)\n wine = wineLookupByName(noGrapeLookup[winery], rec[fldWine], [],\n 'noGrapeLookup', wineAbbrLookup, debug=debug)\n if debug:\n print('setWinery:nogrape check:wine:', wine)\n if wine == '':\n if debug:\n print(\n 'setWinery:noGrapeLookup:matched:None::clear grape:set nongrape to True'\n )\n grape = None\n wine = ''\n nongrape = True\n elif wine:\n grape = None\n if debug:\n print(\n 'setWinery:nograpeLookup:wine found - clear grape field'\n )\n if wine is None and winery in liquorLookup:\n if debug:\n print('setWinery:liqourLookup:', winery)\n liquor, reLiquor = findLiquor(rec, winery, fldWine, debug=debug)\n if liquor is not None:\n wine = liquor\n if debug:\n print('setWinery:liquorLookup-match:', liquor)\n if not grape and not nongrape and not wine and liquor is None:\n if debug:\n print('setWinery:did not find grape-skipping record:', rec[\n fldWineDescr])\n continue\n if debug:\n print('setWinery:pre-vintage found values for wine/liquor:',\n wine, ':grape:', grape)\n vintage = findVintage(rec, fldWine, debug=debug)\n if debug:\n print('setWinery:vintage:', vintage)\n if reCase.search(rec[fldWine]):\n case = 'case'\n for size, reSize in sizeLookup:\n if debug:\n print('setWinery:sizeLookup:', size)\n if reSize.search(rec[fldWine]) and not reShipsAs.search(rec[\n fldWine]):\n if debug:\n print('setWinery:sizeLookup:matched:', reSize)\n break\n else:\n size = None\n if debug:\n print('setWinery:sizeLookup:None-found')\n qual = findQualifier(rec[fldWine], debug=debug)\n if debug:\n try:\n print('setWinery:FinalAttributes:', winery, ':', grape, ':',\n wine, ':', liquor, ':', vintage, ':', case, ':', size,\n ':', qual, ':', rec[fldWine])\n except Exception as e:\n print('debug error5-continuing:', str(e))\n print('fldWine:', fldWine)\n if liquor is not None:\n if debug:\n print(\n 'setWinery:liquor flag set - no additional data needs to be collected'\n )\n elif wine is not None:\n if debug:\n print(\n 'setWinery:wine is not None - do additional lookups:wine:',\n wine)\n if wine in wgLookup[winery] and wgLookup[winery][wine]:\n if debug:\n print('setWinery:lookup winematchset')\n winematchset = findAddAttribWgLookup(rec, winery, wine,\n fldWine, wineAbbrLookup, None, valueDescr='wine', debug\n =debug)\n else:\n print('setWinery:unable to perform wgLookup on winery:',\n winery, ':wine:', wine, ':rec-wine:', rec[fldWine])\n if debug:\n try:\n print('wgLookup[winery]:', wgLookup[winery])\n except Exception as e:\n print('debug error3-continuing:', str(e))\n print('winery:', winery)\n if debug:\n print('setWinery:winematchset:', winematchset)\n elif grape is not None:\n if debug:\n print('setWinery:grape is not None - do additional lookups:',\n grape)\n if grape in wgLookup[winery] and wgLookup[winery][grape]:\n grapematchset = findAddAttribWgLookup(rec, winery, grape,\n fldWine, wineAbbrLookup, defaultorderlist, valueDescr=\n 'grape', debug=debug)\n elif grape in wgLookup[winery]:\n if debug:\n print(\n 'setWinery:grape match: matching record set is blank - no action required'\n )\n else:\n print('setWinery:grape NONMATCH:', rec[fldWine])\n if debug:\n print('setWinery:liquor:', liquor, ':wine:', wine,\n ':grape:', grape, ':wgLookup[winery]:', wgLookup[\n winery])\n if debug:\n print('setWinery:grapematchset:', grapematchset)\n if vintage:\n newVintageLookupWine = rec[fldWine]\n for matchvalue in winematchset:\n if vintage in matchvalue:\n newVintageLookupWine = newVintageLookupWine.replace(\n matchvalue, '')\n if debug:\n print(\n 'setWinery:2nd-vintage:winematchset:wine-name-removal:'\n , matchvalue)\n for matchvalue in grapematchset:\n if vintage in matchvalue:\n newVintageLookupWine = newVintageLookupWine.replace(\n matchvalue, '')\n if debug:\n print(\n 'setWinery:2nd-vintage:grapematchset:wine-name-removal:'\n , matchvalue)\n if newVintageLookupWine != rec[fldWine]:\n if debug:\n print('setWinery:2nd-vintage:newVintageLookupWine:',\n newVintageLookupWine)\n newVintage = findVintage({fldWine: newVintageLookupWine},\n fldWine, debug=debug)\n if debug:\n print('setWinery:2nd-vintage:newVintage:', newVintage)\n vintage = newVintage\n wineDescr = ''\n if winery.startswith('z'):\n vintage = None\n if debug:\n print('setWinery:winery starts with z: clear vintage')\n if winematchset and ' '.join(winematchset) in wine:\n if debug:\n print('setWinery:clearing-winematchset:', winematchset,\n ':is-in-wine:', wine)\n winematchset = []\n if grapematchset and ' '.join(grapematchset) in grape:\n if not (len(grapematchset) == 1 and len(grapematchset[0]) == 1):\n if debug:\n print('setWinery:clearing-grapematchset:',\n grapematchset, ':is-in-grape:', grape)\n grapematchset = []\n if grapematchset and size and size in ' '.join(grapematchset):\n size = ''\n if winematchset and size and size in ' '.join(winematchset):\n size = ''\n if debug:\n print('setWinery:vallist1:', [winery, grape, wine] +\n grapematchset + winematchset + [vintage, size, qual, case])\n print('setWinery:vallist2:', [winery, grape, wine, *\n grapematchset, *winematchset, vintage, size, qual, case])\n wdList = []\n for val in ([winery, grape, wine] + grapematchset + winematchset +\n [vintage, size, qual, case]):\n if val:\n wdList.append(val)\n wineDescr = ' '.join(wdList)\n if False:\n if debug:\n print('setWinery:wdList:', wdList)\n if debug:\n print('setWinery:wineDescr:', wineDescr)\n if debug:\n try:\n print(':'.join(['setWinery:wineDescrList', wineDescr, rec[\n fldWineDescr], str(wineDescr == rec[fldWineDescr]), rec\n [fldWine]]))\n except Exception as e:\n print('debug error6-continuing:', str(e))\n print('fldWine:', fldWine)\n rec[fldWineDescrNew] = wineDescr\n if fldWineDescrMatch:\n rec[fldWineDescrMatch] = rec[fldWineDescr] == rec[fldWineDescrNew]\n\n\ndef setDigitFld2Value(wines, fld, value, debug=False):\n for rec in wines:\n if rec[fld].isdigit():\n rec[fld] = value\n\n\ndef updateFileOptionDictCheck(optiondict, wines, header, debug=False):\n if optiondict['fldWineDescr'] not in wines[0]:\n if debug:\n print('updateFileOptionDictCheck:fldWineDescr NOT in file read in:'\n , optiondict['fldWineDescr'])\n if 'cnt' in wines[0]:\n print('setting values fldWineDescr and fldWineDescrNew to: cnt')\n optiondict['fldWineDescr'] = optiondict['fldWineDescrNew'] = 'cnt'\n elif 'winedescr' in wines[0]:\n print(\n 'setting values fldWineDescr to winedescr and fldWineDescrNew to winedescrnew'\n )\n optiondict['fldWineDescr'] = 'winedescr'\n optiondict['fldWineDescrNew'] = 'winedescrnew'\n else:\n print('could not find fldWineDescr in wines[0]-aborting:',\n optiondict['fldWineDescr'], '\\nwines[0]:', wines[0])\n error = wines[0][optiondict['fldWineDescr']]\n if False and optiondict['fldWineDescr'] == 'winedescr':\n if not optiondict['fldWineDescrMatch']:\n optiondict['fldWineDescrMatch'] = 'same'\n print('setting value fldWineDescrMatch to: same')\n if optiondict['csvfile_update_in'] == optiondict['csvfile_update_out']:\n file_path, base_filename, file_ext = kvutil.filename_split(optiondict\n ['csvfile_update_in'])\n backupfile = kvutil.filename_proper(base_filename + optiondict[\n 'backupfile_ext'], file_path)\n print('copying ', optiondict['csvfile_update_in'], ' to ', backupfile)\n shutil.copyfile(optiondict['csvfile_update_in'], backupfile)\n if optiondict['fldWineDescrNew'] == 'cnt':\n optiondict['csvdictkeys'] = ['cnt', 'date', 'search', 'store',\n 'wine', 'winesrt']\n elif optiondict['fldWineDescrMatch']:\n optiondict['csvdictkeys'] = [optiondict['fldWineDescr'], optiondict\n ['fldWineDescrNew'], optiondict['fldWineDescrMatch'], *header]\n else:\n optiondict['csvdictkeys'] = [optiondict['fldWineDescrNew']] + header[1:\n ]\n print('updateFileOptionDictCheck:set csvdictkeys to:', optiondict[\n 'csvdictkeys'])\n\n\nif __name__ == '__main__':\n optiondict = kvutil.kv_parse_command_line(optiondictconfig, debug=False)\n ppFlag = optiondict['pprint']\n setOptionDictMasterFldValues(optiondict, debug=False)\n if optiondict['setup_check']:\n print('Running global variable check')\n globalVariableCheck(debug=optiondict['debug'])\n sys.exit()\n print('reading in master file:', optiondict['csvfile_master_in'])\n wines, header = kvcsv.readcsv2list_with_header(optiondict[\n 'csvfile_master_in'], headerlc=True)\n wgLookup = buildWineryGrapeLookup(wines, optiondict[\n 'fldWineDescrMaster'], optiondict['fldWineMaster'], debug=\n optiondict['debug'])\n if optiondict['csvfile_master_in'] != optiondict['csvfile_update_in']:\n print('reading in update file:', optiondict['csvfile_update_in'])\n wines, header = kvcsv.readcsv2list_with_header(optiondict[\n 'csvfile_update_in'], headerlc=True)\n if not wines:\n print(\n 'wineset.py - no records read in - no work to be done - exitting'\n )\n sys.exit()\n updateFileOptionDictCheck(optiondict, wines, header, debug=optiondict[\n 'debug'])\n setWineryDescrFromWineryGrapeLookup(wgLookup, wines, optiondict[\n 'fldWineDescr'], optiondict['fldWine'], optiondict[\n 'fldWineDescrNew'], optiondict['fldWineDescrMatch'], debug=\n optiondict['debug'])\n if optiondict['defaultnew'] is not None:\n print('Setting ', optiondict['fldWineDescrNew'], ' to ', optiondict\n ['defaultnew'], 'if not set')\n setDigitFld2Value(wines, optiondict['fldWineDescrNew'], optiondict[\n 'defaultnew'], debug=optiondict['debug'])\n kvcsv.writelist2csv(optiondict['csvfile_update_out'], wines, optiondict\n ['csvdictkeys'])\n print('Saved results to:', optiondict['csvfile_update_out'])\n", "step-5": "'''\r\n@author: Ken Venner\r\n@contact: ken@venerllc.com\r\n@version: 1.13\r\n\r\nRead in a file of wine names and create consistent wine descriptions \r\nfrom these names.\r\n\r\n'''\r\n\r\n\r\nimport kvutil\r\nimport kvcsv\r\n\r\nimport re\r\nimport sys\r\nimport shutil\r\n\r\n# may comment out in the future\r\nimport pprint\r\npp = pprint.PrettyPrinter(indent=4)\r\nppFlag = False\r\n\r\n# application variables\r\noptiondictconfig = {\r\n 'AppVersion' : {\r\n 'value' : '1.13',\r\n 'description' : 'defines the version number for the app',\r\n },\r\n 'debug' : {\r\n 'value' : False,\r\n 'type' : 'bool',\r\n 'description' : 'defines if we are running in debug mode',\r\n },\r\n 'verbose' : {\r\n 'value' : 1,\r\n 'type' : 'int',\r\n 'description' : 'defines the display level for print messages',\r\n },\r\n 'setup_check' : {\r\n 'value' : False,\r\n 'type' : 'bool',\r\n 'description' : 'defines if we checking out setup',\r\n },\r\n 'pprint' : {\r\n 'value' : False,\r\n 'type' : 'bool',\r\n 'description' : 'defines if we output with pretty print when debugging',\r\n },\r\n 'csvfile_master_in' : {\r\n 'value' : 'wine_xref.csv',\r\n 'description' : 'defines the name of the master data input file',\r\n },\r\n 'csvfile_update_in' : {\r\n 'value' : 'wineref.csv',\r\n 'description' : 'defines the name of the input file to updated',\r\n },\r\n 'csvfile_update_out' : {\r\n 'value' : 'wineref2.csv',\r\n 'description' : 'defines the name of the updated output file',\r\n },\r\n 'fldWine' : {\r\n 'value' : 'wine',\r\n 'description' : 'defines the name of the field that holds the Wine ',\r\n },\r\n 'fldWineDescr' : {\r\n 'value' : 'winedescr',\r\n 'description' : 'defines the name of the field holding the wine description',\r\n },\r\n 'fldWineDescrNew' : {\r\n 'value' : 'winedescrnew',\r\n 'description' : 'defines the name of the NEW field holding the new description ',\r\n },\r\n 'fldWineDescrMatch' : {\r\n 'value' : None,\r\n 'description' : 'defines the name of the NEW field holding the results of comparison existing to new description ',\r\n },\r\n 'fldWineMaster' : {\r\n 'value' : None,\r\n 'description' : 'defines the name of the field that holds the Wine when reading the master file ',\r\n },\r\n 'fldWineDescrMaster' : {\r\n 'value' : None,\r\n 'description' : 'defines the name of the field holding the wine description when reading the master file',\r\n },\r\n 'backupfile_ext' : {\r\n 'value' : '.bak',\r\n 'description' : 'defines the extension to use to copy the update input file to if we are replacing it with output',\r\n },\r\n 'defaultnew' : {\r\n 'value' : None,\r\n 'description' : 'defines if we should take field fldWineDescrNew and set to a value if not set',\r\n },\r\n}\r\n\r\n### GLOBAL VARIABLES / LOOKUPS ########################################\r\n\r\n# regex search for vintage in wine name\r\nvintageLookup = (\r\n re.compile('\\d\\d\\d\\d\\s+\\d\\d(\\d\\d)'), # two years together - get this one over early\r\n re.compile('^\\d\\d(\\d\\d)'), # four position start of line\r\n re.compile('\\s\\d\\d(\\d\\d)$'), # four position end of line\r\n re.compile('\\s\\d\\d(\\d\\d)\\s'), # four position middle of line\r\n re.compile('XX\\d\\d(\\d\\d)\\s'), # four position middle of line\r\n re.compile('\\s\\d\\d(\\d\\d)\\/'), # four position split\r\n re.compile('\\s\\'?(\\d\\d)\\'?$|\\s\\'?(\\d\\d)\\'?\\s'), # two position date with optional apostrophe front or back\r\n)\r\n\r\n# regex search for case in wine name\r\nreCase = re.compile(r'12\\s*X\\s*750\\s*ML|\\bcase\\b|12\\/750\\s*ML',re.IGNORECASE)\r\n\r\n# regex to pick up qualifiers from the wine\r\nreQualLookup = (\r\n (None, re.compile(r'\\bWithout\\s+Gift\\b|\\bNo\\s+Gift', re.IGNORECASE)), # the none gift do them first\r\n ('Gift', re.compile(r'\\bGift\\b', re.IGNORECASE)),\r\n ('VAP', re.compile(r'\\bVAP\\b', re.IGNORECASE)),\r\n ('VAP', re.compile(r'\\bGlassVAP\\b', re.IGNORECASE)),\r\n ('Glass', re.compile(r'\\bGlass\\b', re.IGNORECASE)),\r\n ('Glass', re.compile(r'\\bGlasses\\b', re.IGNORECASE)),\r\n ('Etch', re.compile(r'\\bEtch\\b', re.IGNORECASE)),\r\n ('Basket', re.compile(r'\\bBasket\\b', re.IGNORECASE)),\r\n)\r\n\r\n\r\n# regex search to define the size of the wine bottle\r\nsizeLookup = (\r\n ('1.75L', re.compile(r'\\b1\\.75\\s*Li?|\\b1\\.75$', re.IGNORECASE)),\r\n ('1.5L', re.compile(r'\\b1\\.5\\s*L?\\b|\\bMagnum\\b', re.IGNORECASE)),\r\n ('375mL', re.compile(r'Half\\s+Bottle|375ml', re.IGNORECASE)),\r\n ('200mL', re.compile(r'\\b200\\s*ML|\\(200\\s*ML', re.IGNORECASE)),\r\n ('50mL', re.compile(r'\\b50\\s*ML|\\(50\\s*ML', re.IGNORECASE)),\r\n ('500mL', re.compile(r'\\b500\\s*ML|\\(500\\s*ML', re.IGNORECASE)),\r\n ('3L', re.compile(r'\\b3\\s*Li?', re.IGNORECASE)),\r\n ('6L', re.compile(r'\\b6\\s*Li?', re.IGNORECASE)),\r\n ('9L', re.compile(r'\\b9\\s*Li?', re.IGNORECASE)),\r\n ('1L', re.compile(r'\\b1L\\b|\\b1\\s+L$|\\b1.0\\s*L\\b|\\b1\\s+Liter\\b|\\bOne\\s+Liter\\b|\\bLITER\\b|\\b1\\s*LTR', re.IGNORECASE)),\r\n)\r\n\r\n\r\n# regex extract winery names from the wine field\r\nwineryLookup = (\r\n ('Alban', re.compile(r'\\bAlban\\b', re.IGNORECASE)),\r\n ('Arrowood', re.compile(r'\\bArrowood\\b', re.IGNORECASE)),\r\n ('Atalon', re.compile(r'\\bAtalon\\b', re.IGNORECASE)),\r\n ('Attune', re.compile(r'\\bAttune\\b', re.IGNORECASE)),\r\n ('Auteur', re.compile(r'\\bAuteur\\b', re.IGNORECASE)),\r\n ('Austin Hope', re.compile(r'\\bAustin\\s+Hope\\b', re.IGNORECASE)),\r\n ('Badge', re.compile(r'\\bBadge\\b', re.IGNORECASE)),\r\n ('Balletto', re.compile(r'\\bBalletto\\b', re.IGNORECASE)),\r\n ('Bell', re.compile(r'\\bBell\\s+Cellar', re.IGNORECASE)),\r\n ('BR Cohn', re.compile(r'\\bB\\.?\\s?R\\.?\\s+Cohn\\b', re.IGNORECASE)),\r\n ('Bremer', re.compile(r'\\bBremer\\b', re.IGNORECASE)),\r\n ('Brewer-Clifton', re.compile(r'\\bBrewer[\\s\\-]Clifton\\b', re.IGNORECASE)),\r\n ('BV', re.compile(r'\\bBeaulieu\\s+V|\\bBV\\b', re.IGNORECASE)),\r\n ('Belle Glos', re.compile(r'\\bBelle\\s+Glos\\b', re.IGNORECASE)),\r\n ('Bennett Ln', re.compile(r'\\bBennet+\\sLane\\b', re.IGNORECASE)),\r\n ('Benovia', re.compile(r'\\bBenovia\\b', re.IGNORECASE)),\r\n ('Beringer', re.compile(r'\\bBeringer\\b', re.IGNORECASE)),\r\n ('Blackstone', re.compile(r'\\bBlackstone\\b', re.IGNORECASE)),\r\n ('Brancott', re.compile(r'\\bBrancott\\b', re.IGNORECASE)),\r\n ('Cade', re.compile(r'\\bCade\\b', re.IGNORECASE)),\r\n ('Cain Five', re.compile(r'\\bCain\\s+Five\\b|\\bCain\\s-\\sFive\\b|\\bCain\\s5\\b|\\bCainFive\\b', re.IGNORECASE)),\r\n ('Cakebread', re.compile(r'\\bCakebread\\b', re.IGNORECASE)),\r\n ('Cardinale', re.compile(r'\\bCardinale\\b', re.IGNORECASE)),\r\n ('Caymus', re.compile(r'\\bCaymus\\b', re.IGNORECASE)),\r\n ('Chappellet', re.compile(r'\\bChappellet\\b', re.IGNORECASE)),\r\n ('Chalk Hill', re.compile(r'\\bChalk\\s+Hill\\b', re.IGNORECASE)),\r\n ('Clos Du Bois', re.compile(r'\\bClos\\s+Du\\s+Bois\\b', re.IGNORECASE)),\r\n ('ClosDuVal', re.compile(r'\\bClos\\s+du\\s+Val\\b', re.IGNORECASE)),\r\n ('Colgin', re.compile(r'\\bColgin\\b', re.IGNORECASE)),\r\n ('Concha Don Melchor', re.compile(r'\\bConcha\\s.*Don\\s+Melchor\\b|Don\\s+Melchor\\b', re.IGNORECASE)),\r\n ('Continuum', re.compile(r'\\bContinuum\\b', re.IGNORECASE)),\r\n ('Corison', re.compile(r'\\bCorison\\b', re.IGNORECASE)),\r\n ('Cristal', re.compile(r'Roederer\\s?.*Cristal\\b|\\bCristal\\b.+Brut', re.IGNORECASE)),\r\n ('Curran', re.compile(r'\\bCurran\\b', re.IGNORECASE)),\r\n ('Darioush', re.compile(r'\\bDarioush\\b', re.IGNORECASE)),\r\n ('Darioush', re.compile(r'\\bCaravan\\b', re.IGNORECASE)),\r\n ('David Arthur', re.compile(r'\\bDavid\\s+Arthur\\b', re.IGNORECASE)),\r\n ('David Bruce', re.compile(r'\\bDavid\\s+Bruce\\b', re.IGNORECASE)),\r\n ('Davis Family', re.compile(r'\\bDavis\\s+Family\\b', re.IGNORECASE)),\r\n ('Del Dotto', re.compile(r'\\bDel\\s+Dotto\\b', re.IGNORECASE)),\r\n ('Dominus', re.compile(r'\\bDominus\\b', re.IGNORECASE)),\r\n ('Goldeneye', re.compile(r'\\bGoldeneye\\b', re.IGNORECASE)), # before duckhorn\r\n ('Paraduxx', re.compile(r'\\bParaduxx\\b', re.IGNORECASE)), # before duckhorn\r\n ('Domaine Carneros', re.compile(r'\\bDomaine\\s+Carneros\\b', re.IGNORECASE)),\r\n ('Dominus', re.compile(r'\\Dominus\\b', re.IGNORECASE)),\r\n ('Drappier', re.compile(r'\\bDrappier\\b', re.IGNORECASE)),\r\n ('Duckhorn', re.compile(r'\\bDuckhorn\\b', re.IGNORECASE)),\r\n ('Dumol', re.compile(r'\\bDumol\\b', re.IGNORECASE)),\r\n ('Dunn', re.compile(r'\\bDunn\\b', re.IGNORECASE)),\r\n ('Ehlers', re.compile(r'\\bEhlers\\b', re.IGNORECASE)),\r\n ('Etude', re.compile(r'\\bEtude\\b', re.IGNORECASE)),\r\n ('Far Niente', re.compile(r'\\bFar Niente\\b', re.IGNORECASE)),\r\n ('Flora', re.compile(r'\\bFlora\\s+Springs\\b', re.IGNORECASE)),\r\n ('Flowers', re.compile(r'\\bFlowers\\b', re.IGNORECASE)), \r\n ('Robert Foley', re.compile(r'\\bRobert\\s+\\bFoley\\b', re.IGNORECASE)), #before Foley\r\n ('Foley', re.compile(r'\\bFoley\\b', re.IGNORECASE)), \r\n ('Foxen', re.compile(r'\\bFoxen\\b', re.IGNORECASE)),\r\n ('Franciscan', re.compile(r'\\bFranciscan\\b', re.IGNORECASE)),\r\n ('Frank Family', re.compile(r'\\bFrank Family\\b', re.IGNORECASE)),\r\n ('Gary Farrell', re.compile(r'\\bGary\\s+Farrel+\\b', re.IGNORECASE)),\r\n ('Ghost Block', re.compile(r'\\bGhost\\s+Block\\b', re.IGNORECASE)),\r\n ('Grgich', re.compile(r'\\bGrgich\\b', re.IGNORECASE)),\r\n ('Groth', re.compile(r'\\bGroth\\b', re.IGNORECASE)),\r\n ('Gundlach', re.compile(r'\\bGundlach\\b', re.IGNORECASE)),\r\n ('Hansel', re.compile(r'\\bHansel\\b', re.IGNORECASE)),\r\n ('Hanzell', re.compile(r'\\bHanzell\\b', re.IGNORECASE)),\r\n ('Hess', re.compile(r'\\bHess\\b', re.IGNORECASE)),\r\n ('Hewitt', re.compile(r'\\bHewitt\\b', re.IGNORECASE)),\r\n ('Hobbs', re.compile(r'\\bHobbs\\b|\\bcrossbarn\\b', re.IGNORECASE)),\r\n ('Hundred Acre', re.compile(r'\\bHundred\\s+Acre\\b', re.IGNORECASE)),\r\n ('Jordan', re.compile(r'\\bJordan\\b', re.IGNORECASE)),\r\n ('Justin', re.compile(r'\\bJustin\\b', re.IGNORECASE)),\r\n ('Kim Crawford', re.compile(r'\\bKim\\s+Crawford\\b', re.IGNORECASE)),\r\n ('Kistler', re.compile(r'\\bKistler\\b', re.IGNORECASE)),\r\n ('Kosta', re.compile(r'\\bKosta\\s+Browne?\\b', re.IGNORECASE)),\r\n ('Krug', re.compile(r'\\bKrug\\b', re.IGNORECASE)),\r\n ('Kunde', re.compile(r'\\bKunde\\b', re.IGNORECASE)),\r\n ('LaCrema', re.compile(r'\\bLa\\s?Crema\\b', re.IGNORECASE)),\r\n ('Lewis', re.compile(r'\\bLewis\\b', re.IGNORECASE)),\r\n ('Lokoya', re.compile(r'\\bLokoya\\b', re.IGNORECASE)),\r\n ('Meiomi', re.compile(r'\\bMeiomi\\b', re.IGNORECASE)),\r\n ('Melville', re.compile(r'\\bMelville\\b', re.IGNORECASE)),\r\n ('Momento Mori', re.compile(r'\\bMomento\\s+Mori\\b', re.IGNORECASE)),\r\n ('Mondavi', re.compile(r'\\bMondavi\\b', re.IGNORECASE)),\r\n ('Montelena', re.compile(r'\\bMontelena\\b', re.IGNORECASE)),\r\n ('Mt Veeder', re.compile(r'^Mount\\s+Veeder\\b|^Mt\\.? Veeder\\b|\\d+\\s+M[^t]*t\\s+Veeder\\b', re.IGNORECASE)),\r\n ('Newton', re.compile(r'\\bNewton\\b', re.IGNORECASE)),\r\n ('Nickel', re.compile(r'\\bNickel\\b', re.IGNORECASE)),\r\n ('Opus One', re.compile(r'\\bOpus\\s+One\\b', re.IGNORECASE)),\r\n ('P Togni', re.compile(r'\\bTogni\\b', re.IGNORECASE)),\r\n ('Pahlmeyer Jayson', re.compile(r'\\bJayson\\b', re.IGNORECASE)), # this before pahlmeyer\r\n ('Pahlmeyer', re.compile(r'\\bPahlmeyer\\b(?!\\s*Jay)', re.IGNORECASE)),\r\n ('Papillon', re.compile(r'\\bPapillon\\b', re.IGNORECASE)),\r\n ('Patz', re.compile(r'\\bPatz\\b', re.IGNORECASE)),\r\n ('Phelps', re.compile(r'\\bPhelps\\b', re.IGNORECASE)),\r\n ('Plumpjack', re.compile(r'\\bPlumpjack\\b', re.IGNORECASE)),\r\n ('Pride', re.compile(r'\\bPride\\b', re.IGNORECASE)),\r\n ('Prisoner', re.compile(r'\\bPrisoner\\b', re.IGNORECASE)),\r\n ('Provenance', re.compile(r'\\bProvenance\\b', re.IGNORECASE)),\r\n ('R Sinskey', re.compile(r'\\bSinskey\\b', re.IGNORECASE)),\r\n ('Ramey', re.compile(r'\\bRamey\\b', re.IGNORECASE)),\r\n ('Revana', re.compile(r'\\bRevana\\b', re.IGNORECASE)),\r\n ('Raptor', re.compile(r'\\bRaptor\\s+Ridge\\b', re.IGNORECASE)),\r\n ('Revana', re.compile(r'\\bRevana\\b', re.IGNORECASE)),\r\n ('Ridge', re.compile(r'\\bRidge\\b', re.IGNORECASE)),\r\n ('Robert Foley', re.compile(r'\\bRobert\\s+Foley\\b', re.IGNORECASE)),\r\n ('Rombauer', re.compile(r'\\bRombauer\\b', re.IGNORECASE)),\r\n ('Rudd', re.compile(r'\\bRudd\\b', re.IGNORECASE)),\r\n ('Scarecrow', re.compile(r'\\bScarecrow\\b', re.IGNORECASE)),\r\n ('Sea Smoke', re.compile(r'\\bSea\\s+Smoke\\b', re.IGNORECASE)),\r\n ('Seghesio', re.compile(r'\\bSeghesio\\b', re.IGNORECASE)),\r\n ('Shafer', re.compile(r'\\bShafer\\b', re.IGNORECASE)),\r\n ('Sherwin', re.compile(r'\\bSherwin\\b', re.IGNORECASE)),\r\n ('Silver Oak', re.compile(r'\\bSilver\\s+Oak\\b', re.IGNORECASE)),\r\n ('Silverado', re.compile(r'\\bSilverado\\b', re.IGNORECASE)),\r\n ('Simi', re.compile(r'\\bSimi\\b', re.IGNORECASE)),\r\n ('Sonoma Cutrer', re.compile(r'\\bCutrer\\b', re.IGNORECASE)),\r\n ('Spottswoode', re.compile(r'\\bSpottswoode\\b', re.IGNORECASE)),\r\n ('Stag Leap', re.compile(r'\\bStag.*\\sLeap\\b', re.IGNORECASE)),\r\n ('Sullivan', re.compile(r'\\bSullivan\\b', re.IGNORECASE)),\r\n ('Summerland', re.compile(r'\\bSummerland\\b', re.IGNORECASE)),\r\n ('Summers', re.compile(r'\\bSummers\\b', re.IGNORECASE)),\r\n ('Tantara', re.compile(r'\\bTantara\\b', re.IGNORECASE)),\r\n ('Turnbull', re.compile(r'\\bTurnbull\\b', re.IGNORECASE)),\r\n ('Veuve', re.compile(r'\\bVeuve\\b', re.IGNORECASE)),\r\n ('Viader', re.compile(r'\\bViader\\b', re.IGNORECASE)),\r\n ('Waterstone', re.compile(r'\\bWaterstone\\b', re.IGNORECASE)),\r\n ('Whitehall', re.compile(r'\\bWhitehall\\b', re.IGNORECASE)),\r\n ('Wm Selyem', re.compile(r'\\bWilliams\\s*\\-?Selyem\\b', re.IGNORECASE)),\r\n ('ZD', re.compile(r'\\bZD\\b', re.IGNORECASE)),\r\n ('Zaca', re.compile(r'\\bZaca\\b', re.IGNORECASE)),\r\n\r\n \r\n ('zBourbon Woodford Res', re.compile(r'\\bWoodford\\s+Reserve\\b', re.IGNORECASE)),\r\n ('zBourbon Woodford Res', re.compile(r'\\bWoodford\\s+Rsv\\b', re.IGNORECASE)),\r\n ('zCognac Courvoisier', re.compile(r'\\bCourvoisier\\b', re.IGNORECASE)),\r\n ('zCognac Hennessy', re.compile(r'\\bHennesse?y\\b', re.IGNORECASE)),\r\n ('zCognac Remy', re.compile(r'\\bRemy\\s+Martin\\b|\\bRemy\\s+Louis', re.IGNORECASE)),\r\n ('zCointreau', re.compile(r'\\bCointreau\\b', re.IGNORECASE)),\r\n ('zGin Hendrick', re.compile(r'\\bHendrick', re.IGNORECASE)),\r\n ('zGin Tanqueray', re.compile(r'\\bTanqueray\\b', re.IGNORECASE)),\r\n ('zRum Mt Gay', re.compile(r'\\bMount\\s+Gay\\b|\\bMt\\s+Gay', re.IGNORECASE)),\r\n ('zRum Ron Zacapa', re.compile(r'\\bRon\\s+Zacapa\\b', re.IGNORECASE)),\r\n ('zRye Hayden', re.compile(r'\\bBasil\\s+Hayden\\b', re.IGNORECASE)),\r\n ('zSambuca', re.compile(r'\\bSambuca\\b', re.IGNORECASE)),\r\n ('zScotch Glenmorangie', re.compile(r'\\bGlenmorangie\\b', re.IGNORECASE)),\r\n ('zScotch Hibiki Harmony', re.compile(r'\\bHibiki\\s.*Harmony\\b', re.IGNORECASE)),\r\n ('zScotch Hibiki', re.compile(r'\\bHibiki\\b(?!\\s*Har)', re.IGNORECASE)),\r\n ('zScotch Macallan', re.compile(r'\\bMacallan\\b', re.IGNORECASE)),\r\n ('zTeq Campo Azul', re.compile(r'\\bCampo\\s+Azul\\b', re.IGNORECASE)),\r\n ('zTeq Casamigos', re.compile(r'\\bCasamigos\\b', re.IGNORECASE)),\r\n ('zTeq Casino Azul', re.compile(r'\\bCasino\\s+Azul\\b', re.IGNORECASE)),\r\n ('zTeq Clase Azul', re.compile(r'\\bClase\\s+Azul\\b', re.IGNORECASE)),\r\n ('zTeq Cuervo', re.compile(r'\\bJose\\s+Cuervo\\b|^Cuervo\\b', re.IGNORECASE)),\r\n ('zTeq Don Julio', re.compile(r'\\bDon\\s+Julio\\b', re.IGNORECASE)),\r\n ('zTeq Dos Artes', re.compile(r'\\bDos\\s+Artes\\b|^Cuervo\\b', re.IGNORECASE)),\r\n ('zTeq Gran Cava', re.compile(r'\\bGran\\s+Cava\\b', re.IGNORECASE)),\r\n ('zTeq Herradura', re.compile(r'\\bHerradura\\b', re.IGNORECASE)),\r\n ('zTeq Loma Azul', re.compile(r'\\bLoma\\s+Azul\\b', re.IGNORECASE)),\r\n ('zTeq Padre Azul', re.compile(r'\\bPadre\\s+Azul\\b', re.IGNORECASE)),\r\n ('zTeq Partida', re.compile(r'\\bPartida\\b', re.IGNORECASE)),\r\n ('zTeq Patron', re.compile(r'\\bPatron\\b', re.IGNORECASE)),\r\n ('zTripleSec Gr Marnier', re.compile(r'\\bGrand\\s+Marnier\\b', re.IGNORECASE)),\r\n ('zTripleSec Dekuyper', re.compile(r'\\bDekuyper\\b', re.IGNORECASE)),\r\n ('zTripleSec Hiram', re.compile(r'\\bHiram\\b', re.IGNORECASE)),\r\n ('zVodka Absolut', re.compile(r'\\bAbsolut\\b', re.IGNORECASE)),\r\n ('zVodka Skyy', re.compile(r'\\bSkyy\\b', re.IGNORECASE)),\r\n ('zVodka Tito', re.compile(r'\\bTito', re.IGNORECASE)),\r\n ('zWhiskey Balvenie', re.compile(r'\\bBalvenie\\b', re.IGNORECASE)),\r\n ('zWhiskey J Walker', re.compile(r'\\bJohn+ie\\s+Walker\\b', re.IGNORECASE)),\r\n# ('', re.compile(r'\\b\\b', re.IGNORECASE)),\r\n)\r\n\r\n# regex extract the grape from the wine fld\r\ngrapeLookup = (\r\n ('Cab Franc', re.compile(r'\\bCabernet\\s+Franc|\\bCab\\s+Franc', re.IGNORECASE)), # before cab\r\n ('Cab', re.compile(r'\\bCabernet\\b|\\sCS\\s|\\sCS$|\\bCab\\b', re.IGNORECASE)),\r\n ('Claret', re.compile(r'\\bClaret\\b', re.IGNORECASE)),\r\n ('Rose Pinot', re.compile(r'\\bRose\\b.*\\bPinot\\b|\\bPinot\\b.*\\bRose\\b', re.IGNORECASE)),\r\n ('Pinot', re.compile(r'\\bPinot\\b|\\bPN\\b|\\bP\\s+Noir\\b', re.IGNORECASE)),\r\n ('Merlot', re.compile(r'\\bMerlot\\b|\\bME\\b', re.IGNORECASE)),\r\n ('Sauv Blanc', re.compile(r'\\bSauvignon\\s+Blanc\\b|\\bSB\\b', re.IGNORECASE)),\r\n ('Sauv Blanc', re.compile(r'\\bSauvignon\\/Fume\\s+Blanc\\b', re.IGNORECASE)),\r\n ('Meritage', re.compile(r'\\bMeritage\\b', re.IGNORECASE)),\r\n ('Fume', re.compile(r'\\bFume\\b|\\bFum&#233;', re.IGNORECASE)),\r\n ('Champagne', re.compile(r'\\bChampagne\\b', re.IGNORECASE)),\r\n ('Chard', re.compile(r'\\bChar+d|\\bCH\\b', re.IGNORECASE)),\r\n ('Shiraz', re.compile(r'\\bShiraz\\b', re.IGNORECASE)),\r\n ('Syrah', re.compile(r'\\bSyrah\\b|\\bSY\\b',re.IGNORECASE)),\r\n ('Zin', re.compile(r'\\bZinfandel\\b|\\bZIN\\b|\\bZN\\b', re.IGNORECASE)),\r\n ('Rose', re.compile(r'\\bRose\\b|\\bRos&#233;', re.IGNORECASE)),\r\n ('Sangiovese', re.compile(r'\\Sangiovese\\b', re.IGNORECASE)),\r\n# ('Brandy', re.compile(r'\\bBrandy\\b', re.IGNORECASE)),\r\n ('Gewurzt', re.compile(r'\\bGew.rztraminer\\b|\\bGew&#252;rzt', re.IGNORECASE)),\r\n ('Malbec', re.compile(r'\\bMalbec\\b', re.IGNORECASE)),\r\n ('Viognier', re.compile(r'\\bViognier\\b', re.IGNORECASE)),\r\n ('Roussanne', re.compile(r'\\bRoussanne\\b', re.IGNORECASE)),\r\n ('Charbono', re.compile(r'\\bCharbono\\b', re.IGNORECASE)),\r\n ('PSirah', re.compile(r'\\bPetite Sirah\\b', re.IGNORECASE)),\r\n ('Cuvee', re.compile(r'\\bCuvee\\b', re.IGNORECASE)),\r\n ('Red', re.compile(r'\\bRed\\b|\\bBordeaux\\s+Blend\\b', re.IGNORECASE)),\r\n ('Syrah-Cab', re.compile(r'\\bSyrcab\\b|\\bsyrah[-\\s\\/]+cab', re.IGNORECASE)),\r\n ('Grenache', re.compile(r'\\bGrenache\\b', re.IGNORECASE)), \r\n ('Tempranillo', re.compile(r'\\bTempranillo\\b', re.IGNORECASE)),\r\n)\r\n\r\n# wineries that we don't want to look up the grape on\r\nignoreGrapeLookup = {\r\n 'Cristal' : ['Rose', None],\r\n 'Domaine Carneros' : ['Brut', None],\r\n 'Dominus' : [None],\r\n 'Papillon' : None,\r\n 'Paraduxx' : None,\r\n 'Veuve' : None,\r\n 'zCointreau' : None,\r\n 'zGin Hendrick' : None,\r\n 'zGin Tanqueray' : ['Ten', None],\r\n 'zTripleSec Gr Marnier' : ['1880', '100th', 'Cent', 'Quin', None],\r\n 'zTripleSec Dekuyper' : None,\r\n 'zTripleSec Hiram' : None,\r\n 'zVodka Skyy' : ['Citrus', None],\r\n 'zVodka Tito' : None,\r\n# 'Prisoner' : ['Cuttings', 'Red', 'Derange', 'Saldo', 'Blindfold', None],\r\n}\r\n\r\n# winery to wine lookup when no grape is found in the wine name\r\n#\r\n# extract the wine name from a winery - when a field does not have a grape lookup for the row\r\n# the name looked up and found will be the name used\r\nnoGrapeLookup = {\r\n 'Ehlers' : ['120-80'], # matches an abbreviations - and matches fldWineDescr\r\n 'Alban' : ['Pandora'],\r\n 'BV' : ['Tapestry', 'Latour'],\r\n 'Bennett Ln' : ['Maximus'],\r\n 'Bremer' : ['Austintatious'],\r\n 'Cain Five' : None,\r\n 'Colgin' : ['Cariad', 'IX'],\r\n 'Concha Don Melchor' : None,\r\n 'Continuum' : None,\r\n 'Darioush' : ['Duel', 'Darius'],\r\n 'Duckhorn' : ['Discussion'],\r\n 'Far Niente' : ['Dolce'],\r\n 'Flora' : ['Trilogy'],\r\n 'Franciscan' : ['Magnificat'],\r\n 'Grgich' : ['Violetta'],\r\n 'Gundlach' : ['Vintage Reserve'],\r\n 'Justin' : ['Isosceles'],\r\n 'Krug' : ['Generations'],\r\n 'Mondavi' : ['Maestro'],\r\n 'Newton' : ['Puzzle'],\r\n 'Opus One' : None,\r\n 'Phelps' : ['Insignia'],\r\n 'Prisoner' : ['Cuttings', 'Derange', 'Saldo', 'Blindfold'],\r\n 'Ridge' : ['Monte Bello'],\r\n 'Robert Foley' : ['Griffin'],\r\n 'Sullivan' : ['Coeur de Vigne'],\r\n 'Zaca' : ['ZThree', 'ZCuvee'],\r\n 'zCognac Courvoisier' : ['Napolean', 'VS', 'VSOP', 'XO'],\r\n 'zCognac Hennessy' : ['Paradis', 'Richard', 'VS', 'VSOP', 'XO', 'Master'],\r\n 'zCognac Remy' : ['1738', 'Louis XIII', 'VSOP', 'XO', 'VS'],\r\n 'zRum Ron Zacapa' : ['23', 'Negra', 'XO'],\r\n 'zRye Hayden' : ['Dark', 'Caribbean'],\r\n 'zScotch Hibiki Harmony' : None,\r\n# 'zScotch Hibiki' : ['Toki', '12', '17', '21', '30'],\r\n 'zTeq Campo Azul' : ['Extra Anejo', 'Anejo', 'Blanco', 'Reposado'],\r\n 'zTeq Casamigos' : ['Extra Anejo', 'Anejo', 'Blanco', 'Reposado'],\r\n 'zTeq Casino Azul' : ['Extra Anejo', 'Anejo', 'Blanco', 'Reposado', 'Silver'],\r\n 'zTeq Clase Azul' : ['Ultra', 'Extra Anejo', 'Anejo', 'Blanco', 'Reposado', 'Mezcal', 'Plata', 'Platino'],\r\n 'zTeq Dos Artes' : ['Extra Anejo'],\r\n 'zTeq Gran Cava' : ['Extra Anejo'],\r\n 'zTeq Loma Azul' : ['Extra Anejo', 'Anejo', 'Blanco', 'Reposado'],\r\n# 'zTeq Padre Azul' : ['Extra Anejo', 'Anejo', 'Blanco', 'Reposado'],\r\n 'zTeq Partida' : ['Blanco', 'Elegante'],\r\n 'zVodka Absolut' : ['Citron', 'Mandarin', 'Mandrin', 'Mango', 'Ruby', 'Vanilia', 'Raspberri', 'Grapevine', None],\r\n 'zWhiskey J Walker' : ['Double Black', 'Black', 'Blue', 'Gold', 'Green', 'Platinum', 'Red','Swing', 'White', '18', '21'],\r\n}\r\n\r\n\r\n# regex to use to determine if this is a liquor not a wine\r\n#\r\n# winery -> [ liquor, regex ]\r\n# if there is no grape, and no noGrapeLookup found, but the winery has a liquorLookup\r\n# use the list of lookups to find the additional infomratoin to add to the winery\r\n#\r\nliquorLookup = {\r\n 'zRum Mt Gay' : [\r\n ('1703 Mst', re.compile(r'\\b1703\\b', re.IGNORECASE)),\r\n ('BB', re.compile(r'\\bBlack Barrel\\b', re.IGNORECASE)),\r\n ('Eclipse Silver', re.compile(r'\\bEclipse\\s+Silver\\b', re.IGNORECASE)),\r\n ('Eclipse', re.compile(r'\\bEclipse\\b', re.IGNORECASE)),\r\n ('Old Peat', re.compile(r'\\bOld Peat', re.IGNORECASE)),\r\n ('Old Pot', re.compile(r'\\bPot\\s+Still\\b', re.IGNORECASE)),\r\n ('Old', re.compile(r'\\bOld\\b', re.IGNORECASE)),\r\n ('Silver', re.compile(r'\\bSilver\\b', re.IGNORECASE)),\r\n ('XO Peat', re.compile(r'\\bXO\\b', re.IGNORECASE)),\r\n ],\r\n 'zScotch Glenmorangie' : [\r\n ('10', re.compile(r'\\b10(YR)?\\b', re.IGNORECASE)),\r\n ('14 Port', re.compile(r'14.+\\bQuinta\\b|14.+\\bPort\\b|\\bQuinta\\b.+14|\\bPort\\b.+14', re.IGNORECASE)),\r\n ('12 Bacalta', re.compile(r'\\bBacalta\\b', re.IGNORECASE)),\r\n ('12 Burgundy', re.compile(r'\\bBurgundy\\b', re.IGNORECASE)),\r\n ('12 Nectar', re.compile(r'\\bNectar\\b', re.IGNORECASE)),\r\n ('12 Port', re.compile(r'\\bQuinta\\b|\\bPort\\b', re.IGNORECASE)),\r\n ('12 Sherry', re.compile(r'\\bLa\\s?Santa\\b|\\bSherry\\b', re.IGNORECASE)),\r\n ('12 Signet', re.compile(r'\\bSignet\\b', re.IGNORECASE)),\r\n ('15 Cadboll', re.compile(r'\\bCadboll', re.IGNORECASE)),\r\n ('15', re.compile(r'\\b15(YR)?\\b', re.IGNORECASE)),\r\n ('18', re.compile(r'\\b18(YR)?\\b|\\b18YEAR\\b', re.IGNORECASE)),\r\n ('25 Astar', re.compile(r'\\bAstar\\b', re.IGNORECASE)),\r\n ('25', re.compile(r'\\b25(YR)?\\b', re.IGNORECASE)),\r\n ('Companta', re.compile(r'\\bCompanta\\b', re.IGNORECASE)),\r\n ('Finealta', re.compile(r'\\bFinealta\\b', re.IGNORECASE)),\r\n ('Milsean', re.compile(r'\\bMilsean\\b', re.IGNORECASE)),\r\n ('Sonnalta', re.compile(r'\\bSonnalta\\b', re.IGNORECASE)),\r\n ],\r\n 'zScotch Macallan' : [\r\n ('10 Fine', re.compile(r'\\bFine.*\\b10\\b|\\b10.*Fine')),\r\n ('10', re.compile(r'\\b10\\b')),\r\n ('12 Double Gold', re.compile(r'\\bDbl\\b.*Gold|\\bDouble\\b.*Gold', re.IGNORECASE)),\r\n ('12 Double', re.compile(r'\\bDouble\\s.*12(YR)?\\b', re.IGNORECASE)),\r\n ('12 Double', re.compile(r'\\b12\\s.*Double\\b', re.IGNORECASE)),\r\n ('12 Double', re.compile(r'\\bDbl\\b|\\bDouble\\b', re.IGNORECASE)),\r\n ('12 Edition 1', re.compile(r'\\bEdition\\s.*1\\b', re.IGNORECASE)),\r\n ('12 Edition 2', re.compile(r'\\bEdition\\s.*2\\b', re.IGNORECASE)),\r\n ('12 Edition 3', re.compile(r'\\bEdition\\s.*3\\b', re.IGNORECASE)),\r\n ('12 Edition 4', re.compile(r'\\bEdition\\s.*4\\b', re.IGNORECASE)),\r\n ('12 Sherry', re.compile(r'\\b12\\s.*Sherry\\b|\\bSherry\\b\\s.*\\b12', re.IGNORECASE)),\r\n ('12 Triple', re.compile(r'\\b12(YR)?\\s.*Triple\\b', re.IGNORECASE)),\r\n ('12 Triple', re.compile(r'\\bTriple\\s.*12\\b', re.IGNORECASE)),\r\n ('12', re.compile(r'\\b12(YR)?\\b', re.IGNORECASE)),\r\n ('15 Triple', re.compile(r'\\b15(YR)?\\s.*Triple\\b|Triple.+\\b15(YR)?\\b', re.IGNORECASE)),\r\n ('15 Fine', re.compile(r'\\b15(YR)?\\b.*\\bFine\\b', re.IGNORECASE)),\r\n ('15', re.compile(r'\\b15(YR)?\\b', re.IGNORECASE)),\r\n ('17 Sherry', re.compile(r'\\b17(YR)?\\s.*Sherry\\b', re.IGNORECASE)),\r\n ('17 Fine', re.compile(r'\\b17(YR)?\\b.*\\bFine\\b', re.IGNORECASE)),\r\n ('17', re.compile(r'\\b17(YR)?\\b', re.IGNORECASE)),\r\n ('18 Sherry', re.compile(r'\\b18(YR)?\\s.*Sherry\\b|Sherry\\b.*18', re.IGNORECASE)),\r\n ('18 Triple', re.compile(r'\\b18(YR)?\\s.*Triple\\b|Triple.+\\b18(YR)?\\b', re.IGNORECASE)),\r\n ('18 Fine', re.compile(r'\\b18(YR)?\\b.*\\bFine\\b', re.IGNORECASE)),\r\n ('18 Gran', re.compile(r'Gran\\b.*\\b18', re.IGNORECASE)),\r\n ('18', re.compile(r'\\b18(YR)?\\b', re.IGNORECASE)),\r\n ('21 Fine', re.compile(r'\\b21.*Fine\\b', re.IGNORECASE)),\r\n ('21', re.compile(r'\\b21(YR)?\\b', re.IGNORECASE)),\r\n ('25 Sherry', re.compile(r'\\b25\\s.*Sherry\\b', re.IGNORECASE)),\r\n ('25', re.compile(r'\\b25(YR)?\\b')),\r\n ('30 Sherry', re.compile(r'\\b30\\s.*Sherry', re.IGNORECASE)),\r\n ('30 Triple', re.compile(r'\\b30(YR)?\\s.*Triple\\b|Triple.+\\b30(YR)?\\b', re.IGNORECASE)),\r\n ('30 Fine', re.compile(r'\\b30(YR)?\\b.*\\bFine\\b|Fine.*30', re.IGNORECASE)),\r\n ('30', re.compile(r'\\b30(YR)?\\b')),\r\n ('Rare', re.compile(r'\\bRare\\b', re.IGNORECASE)),\r\n ],\r\n 'zTeq Cuervo' : [\r\n ('Especial Gold', re.compile(r'\\bEspecial\\b.*Gold\\b|Gold.*Especial', re.IGNORECASE)),\r\n ('Especial Blue', re.compile(r'\\bEspecial\\b.*Blue\\b', re.IGNORECASE)),\r\n ('Especial', re.compile(r'\\bEspecial\\b', re.IGNORECASE)),\r\n ('Familia Platino', re.compile(r'\\bPlatino\\b', re.IGNORECASE)),\r\n ('Familia Anejo', re.compile(r'\\bFamilia\\b|\\bReserva\\b', re.IGNORECASE)),\r\n ('Gold', re.compile(r'\\bGold\\b', re.IGNORECASE)),\r\n ('Reposado Lagavulin', re.compile(r'\\bReposado.*Lagavulin', re.IGNORECASE)),\r\n ('Tradicional Anejo', re.compile(r'Tradicional.*Anejo|Anejo.*Tradicional', re.IGNORECASE)),\r\n ('Tradicional Reposado', re.compile(r'Tradicional.*Reposado|Reposado.*Tradicional', re.IGNORECASE)),\r\n ('Tradicional Silver', re.compile(r'\\bTradicional\\b', re.IGNORECASE)),\r\n ('Tradicional Silver', re.compile(r'\\bTraditional\\b', re.IGNORECASE)),\r\n ('Reposado', re.compile(r'\\bReposado\\b', re.IGNORECASE)),\r\n ('Silver', re.compile(r'\\bSilver\\b', re.IGNORECASE)),\r\n ],\r\n 'zTeq Don Julio' : [\r\n ('1942', re.compile(r'\\b1942\\b', re.IGNORECASE)),\r\n ('Real', re.compile(r'\\bReal\\b', re.IGNORECASE)),\r\n ('Anejo Claro 70th', re.compile(r'\\b70th\\b', re.IGNORECASE)),\r\n ('Anejo Claro', re.compile(r'\\bAnejo\\b\\s*Claro\\b', re.IGNORECASE)),\r\n ('Anejo', re.compile(r'\\bAnejo\\b', re.IGNORECASE)),\r\n ('Blanco', re.compile(r'\\bBlanco\\b', re.IGNORECASE)),\r\n ('Reposado Lagavulin', re.compile(r'\\bRepo.+Lagvulin\\b', re.IGNORECASE)),\r\n ('Reposado Dbl', re.compile(r'\\bReposado.+Double\\b', re.IGNORECASE)),\r\n ('Reposado Dbl', re.compile(r'\\bReposado.+Dbl\\b', re.IGNORECASE)),\r\n ('Reposado Dbl', re.compile(r'\\bDouble.+Reposado\\b', re.IGNORECASE)),\r\n ('Reposado Private', re.compile(r'\\bReposado.+Private\\b', re.IGNORECASE)),\r\n ('Reposado', re.compile(r'\\bReposado\\b', re.IGNORECASE)),\r\n ('Silver', re.compile(r'\\bSilver\\b', re.IGNORECASE)),\r\n ],\r\n 'zTeq Herradura' : [\r\n ('Ultra', re.compile(r'\\bUltra\\b', re.IGNORECASE)),\r\n ('Suprema', re.compile(r'\\bSuprema\\b', re.IGNORECASE)),\r\n ('Anejo', re.compile(r'\\bAnejo\\b', re.IGNORECASE)),\r\n ('Blanco', re.compile(r'\\bBlanco\\b', re.IGNORECASE)),\r\n ('Reposado Gold', re.compile(r'\\bReposado\\s+Gold\\b|\\bGold\\s+Reposado\\b', re.IGNORECASE)),\r\n ('Reposado Scotch', re.compile(r'\\bReposado.+Scotch\\b|\\bScotch.+Reposado\\b', re.IGNORECASE)),\r\n ('Reposado Port', re.compile(r'\\bPort.+Reposado\\b|\\bReposado.+Port\\b', re.IGNORECASE)),\r\n ('Reposado', re.compile(r'\\bReposado\\b', re.IGNORECASE)),\r\n ('Silver', re.compile(r'\\bSilver\\b', re.IGNORECASE)),\r\n ],\r\n 'zTeq Patron' : [\r\n ('Gran Piedra', re.compile(r'\\bPiedra\\b', re.IGNORECASE)),\r\n ('DELETE Roca DELETE', re.compile(r'\\bRoca\\b', re.IGNORECASE)),\r\n ('Anejo Extra Lalique', re.compile(r'\\bLalique\\b', re.IGNORECASE)),\r\n ('Anejo Extra 7yr', re.compile(r'\\b7YR\\b|\\b7 anos\\b|\\b7 year\\b', re.IGNORECASE)),\r\n ('Anejo Extra 5yr', re.compile(r'\\b5YR\\b|\\b5 anos\\b|\\b5 year\\b', re.IGNORECASE)),\r\n ('Anejo Extra 10yr', re.compile(r'\\b10\\b.+\\bExtra\\b|\\bExtra\\b.+10', re.IGNORECASE)),\r\n ('Anejo Extra', re.compile(r'\\bExtra\\s+Anejo\\b', re.IGNORECASE)),\r\n ('Gran Anejo', re.compile(r'\\bGran\\s+Anejo\\b', re.IGNORECASE)),\r\n ('Gran Anejo', re.compile(r'\\bBurdeos\\b', re.IGNORECASE)),\r\n ('Gran Smoky', re.compile(r'\\bGran\\s+.*Smoky\\b', re.IGNORECASE)),\r\n ('Anejo', re.compile(r'\\bAnejo\\b', re.IGNORECASE)),\r\n ('Gran Platinum', re.compile(r'\\bPlatinum\\b', re.IGNORECASE)),\r\n ('Reposado', re.compile(r'\\bReposado\\b', re.IGNORECASE)),\r\n ('Silver LTD', re.compile(r'\\bSilver.*Limited\\b|\\bLimited.*Silver\\b', re.IGNORECASE)),\r\n ('Silver Estate', re.compile(r'\\bEstate.*Silver\\b|\\bSilver.*Estate\\b', re.IGNORECASE)),\r\n ('Silver', re.compile(r'\\bSilver\\b', re.IGNORECASE)),\r\n ('Blanco', re.compile(r'\\bBlanco\\b', re.IGNORECASE)),\r\n# ('', re.compile(r'\\b\\b', re.IGNORECASE)),\r\n ],\r\n 'zTeq Padre Azul' : [\r\n ('Blanco', re.compile(r'\\bsilver\\b', re.IGNORECASE)),\r\n ],\r\n 'zWhiskey Balvenie' : [\r\n ('12 Double', re.compile(r'\\bDouble.*12(YR)?\\b', re.IGNORECASE)),\r\n ('12 Double', re.compile(r'\\b12(YR)?\\s.*Double', re.IGNORECASE)),\r\n ('12 First', re.compile(r'\\b12(YR)?\\s.*First', re.IGNORECASE)),\r\n ('12 USA', re.compile(r'\\b12.*American|American.*12', re.IGNORECASE)),\r\n ('12 Toast', re.compile(r'\\b12(YR)?\\s.*Toast', re.IGNORECASE)),\r\n ('12', re.compile(r'\\b12(YR)?\\b', re.IGNORECASE)),\r\n ('14 Carib', re.compile(r'\\b14(YR)?\\s.*Carib', re.IGNORECASE)),\r\n ('14 Carib', re.compile(r'\\b14(YR)?\\s.*CB\\s+Cask', re.IGNORECASE)),\r\n ('14 Carib', re.compile(r'\\bCarr?ib', re.IGNORECASE)),\r\n ('14 Peat', re.compile(r'\\b14(YR)?\\s.*Peat', re.IGNORECASE)),\r\n ('15 Sherry', re.compile(r'\\b15(YR)?\\s.*Sherry\\b', re.IGNORECASE)),\r\n ('15 Sherry', re.compile(r'\\bSherry\\s+.*15(YR)?\\b', re.IGNORECASE)),\r\n ('15', re.compile(r'\\b15(YR)?\\b', re.IGNORECASE)),\r\n ('16 Triple', re.compile(r'\\b16(YR)?\\s.*Triple\\b', re.IGNORECASE)),\r\n ('17 Sherry Double', re.compile(r'\\b17(YR)?\\s.*Sherry\\s+Doub', re.IGNORECASE)),\r\n ('17 Sherry', re.compile(r'\\b17(YR)?\\s.*Sherry', re.IGNORECASE)),\r\n ('17 Double', re.compile(r'\\b17(YR)?\\s.*Double', re.IGNORECASE)),\r\n ('17 Double', re.compile(r'\\bDouble.*17(YR)?\\b', re.IGNORECASE)),\r\n# 17 Double Sherry\r\n# 17 Islay\r\n# 17 New Oak\r\n ('17 Peat', re.compile(r'\\b17(YR)?\\s.*Peat', re.IGNORECASE)),\r\n ('17 Peat', re.compile(r'\\bPeat.*17(YR)?\\b', re.IGNORECASE)),\r\n ('17', re.compile(r'\\b17(YR)?\\b', re.IGNORECASE)),\r\n ('21 Port', re.compile(r'\\b21.*Port', re.IGNORECASE)),\r\n ('21 Port', re.compile(r'\\bPort.*21\\b', re.IGNORECASE)),\r\n ('21', re.compile(r'21', re.IGNORECASE)),\r\n ('25', re.compile(r'\\b25(YR)?\\b', re.IGNORECASE)),\r\n ('30', re.compile(r'\\b30(YR)?\\b', re.IGNORECASE)),\r\n ('40', re.compile(r'\\b40(YR)?\\b', re.IGNORECASE)),\r\n ],\r\n 'zBourbon Woodford Res' : [\r\n ('Dbl', re.compile(r'\\bDouble\\b', re.IGNORECASE)),\r\n ('Derby', re.compile(r'\\bDerby\\b', re.IGNORECASE)),\r\n ('Rye Choc', re.compile(r'\\bChocolate.*Rye\\b', re.IGNORECASE)),\r\n ('Rye', re.compile(r'\\bRye\\b', re.IGNORECASE)),\r\n ('Brandy', re.compile(r'\\bBrandy\\b', re.IGNORECASE)),\r\n ('Batch', re.compile(r'\\bBatch\\b', re.IGNORECASE)),\r\n ('Barrel', re.compile(r'\\bBarrel\\b', re.IGNORECASE)),\r\n ('Master', re.compile(r'\\bMasters?\\b', re.IGNORECASE)),\r\n ('Malt', re.compile(r'\\bMalt\\b', re.IGNORECASE)),\r\n ('Maple', re.compile(r'\\bMaple\\b', re.IGNORECASE)),\r\n ('Wheat', re.compile(r'\\bWheat\\b', re.IGNORECASE)),\r\n ('', re.compile(r'\\bWoodford\\b', re.IGNORECASE)),\r\n ],\r\n 'zSambuca' : [\r\n ('Romana Black', re.compile(r'\\bRomana.*\\bBlack\\b|\\bBlack\\s+Romana\\b', re.IGNORECASE)),\r\n ('Romana', re.compile(r'\\bRomana\\b', re.IGNORECASE)),\r\n ('Di Amore', re.compile(r'\\bdi Amore\\b', re.IGNORECASE)),\r\n ],\r\n 'zScotch Hibiki' : [\r\n ('12', re.compile(r'\\b12\\s*YE?A?R\\b', re.IGNORECASE)),\r\n ('17 Limited', re.compile(r'\\b17\\s*YE?A?R\\b.+Limited', re.IGNORECASE)),\r\n ('17', re.compile(r'\\b17\\s*YE?A?R\\b', re.IGNORECASE)),\r\n ('21 Limited', re.compile(r'\\b21\\s*YE?A?R\\b.+Limited', re.IGNORECASE)),\r\n ('21', re.compile(r'\\b21\\s*YE?A?R\\b', re.IGNORECASE)),\r\n ('30', re.compile(r'\\b30\\s*YE?A?R\\b', re.IGNORECASE)),\r\n ]\r\n}\r\n# regex to expand out optional values in the optoinal values to find a match against wine fld\r\nwineAbbrLookup = {\r\n '120-80' : r'\\bOne\\s+Twenty\\s+Over\\s+Eighty\\b',\r\n '3Amigos' : r'\\bThree\\s+Amigos\\b',\r\n '3Palms' : r'\\bThree\\s+Palms\\b',\r\n '3Sister' : r'\\bThree\\s+Sisters?\\b',\r\n '4Barrell' : r'\\b4[\\-\\s]Barrels?\\b',\r\n 'Alex' : r'\\bAlexander\\b',\r\n 'And' : r'\\bAnderson\\b',\r\n 'Car' : r'\\bCarneros\\b',\r\n 'Carries' : r'\\bCarrie',\r\n 'CC' : r'\\bC\\.?C\\.?\\s+Ranch\\b',\r\n 'Clone4' : r'\\bClone\\s+4\\b',\r\n 'Clone6' : r'\\bClone\\s+6\\b',\r\n 'Crossbarn' : r'\\bCross\\s+Barn\\b',\r\n 'Donna' : r'\\bDonna',\r\n 'Est' : r'\\bEstate\\b',\r\n 'Estate' : r'\\bEst\\b',\r\n 'Gap' : r'\\bGap|\\s%27Gap',\r\n 'Gary' : r'\\bGary',\r\n 'Julia' : r'\\bJulia',\r\n 'Knights' : r'\\bKnight',\r\n 'KistlerVnyd' : r'\\bKistler (Vineyard|VYD|EST)\\b',\r\n 'LP' : r'\\bLes Pierres\\b',\r\n 'Lyn' : r'\\bLyndenhur?st\\b',\r\n 'Mont' : r'\\bMonterey\\b',\r\n 'Mt' : r'\\bMount\\b|\\bMt\\.\\b',\r\n 'Napa/Son' : r'\\bNapa.*Son',\r\n 'Oak' : r'\\bOakville\\b',\r\n 'One-Pt-5' : r'\\bOne\\s+Point\\s+Five\\b',\r\n 'Pomm' : r'\\bPommeraie\\b',\r\n 'Priv' : r'\\bPrivate\\b',\r\n 'RR' : r'\\bRussian\\s+Rivers?\\b|RRV',\r\n 'RRR' : r'\\bRussian\\s+Rivers?\\b|RRV',\r\n 'Res' : r'\\bReserve\\b|\\bRsv\\b|\\bResrv\\b|\\bReserv\\b|\\bReserve$',\r\n 'Rose' : r'\\bRos&#233;|\\bROS&EACUTE;|\\bRos%E9',\r\n 'Ruth' : r'\\bRutherford\\b',\r\n 'Sandy' : r'\\bSandy',\r\n 'Samanthas' : r'\\bSamantha',\r\n 'SC' : r'\\bSanta\\s+Cruz\\b',\r\n 'SLD' : r'\\bStag.*Leap\\b',\r\n 'SLH' : r'\\bSanta\\s+Lucia\\b',\r\n 'SMV' : r'\\bSanta\\s+Maria|\\bS\\s+Maria',\r\n 'SRH' : r'\\bSTA\\.?|\\bSANTA\\s+Rita\\b|\\bSTA\\sRITA\\sHILLS|\\bS\\s+RITA\\b',\r\n 'SS' : r'\\bSpecial\\s+\\Selection\\b',\r\n 'Stage' : r'\\bStagecoach\\b',\r\n 'Son' : r'\\bSonoma\\b',\r\n 'SYV' : r'\\bSanta\\s+Ynez\\s+Valley\\b',\r\n 'TD9' : r'\\bTD\\s+9\\b|\\bTD-9\\b',\r\n 'Terraces' : r'\\bTerrace',\r\n 'TheCutrer' : r'\\bThe Cutrer\\b|nnay Cutrer\\b',\r\n 'Tok' : r'\\bTo[\\s\\-]?Kolan|\\bTo[\\s\\-]?Kalon',\r\n 'Turn4' : r'\\bTurn\\s+4\\b',\r\n 'Vernas' : r'\\bVerna',\r\n 'Vine' : r'\\bVines\\b',\r\n 'Yount' : r'\\bYountville\\b',\r\n 'ZThree' : r'\\bZ.*\\bThree\\b',\r\n 'ZCuvee' : r'\\bZ.*\\bCuvee\\b|\\bCuvee Z\\b', \r\n\r\n # misspellings\r\n 'Agustina' : r'\\bAugustina\\b',\r\n 'Durell' : r'\\bDurrell\\b',\r\n 'Benchland' : r'\\bBenchlands\\b',\r\n 'Pritchard' : r'\\bPitchard\\b',\r\n}\r\n\r\n# regex search - set the ships as\r\nreShipsAs = re.compile(r'\\(ships?\\s', re.IGNORECASE)\r\n\r\n# the order in which we pull multiple single match attributes \r\ndefaultorderlist=[['Tok'], ['Oak'], ['Res'], ['RR'], ['Landslide'], ['Yount'], ['RRR'], ['Son'], ['Ruth'], ['Napa'], ['Helena'], ['SRH'], ['SLH'], ['SMV'], ['SLD'], ['Paso'], ['Alex'], ['Single'], ['Estate']]\r\n \r\n### FUNCTIONS ############################################\r\n\r\n#########################################################################################\r\ndef globalVariableCheck( debug=False ):\r\n # check for liquor definitions that are in noGrapeLookup\r\n # these will never execute\r\n for liquor in liquorLookup:\r\n if liquor in noGrapeLookup:\r\n print('WARNING:liquorLookup regexs will never execute - they are in noGrapeLookup:', liquor)\r\n if liquor in ignoreGrapeLookup:\r\n print('WARNING:liquorLookup regexs will never execute - they are in ignoreGrapeLookup:', liquor)\r\n for winery in ignoreGrapeLookup:\r\n if winery in noGrapeLookup:\r\n print('WARNING:ignoreGrapeLookup regexs will never execute - they are in noGrapeLookup:', winery)\r\n \r\n#########################################################################################\r\ndef setOptionDictMasterFldValues( optiondict, debug=False ):\r\n # default these fields to the fld values if they are not set\r\n # otherwise leave them alone\r\n for fld in ('fldWine', 'fldWineDescr'):\r\n if not optiondict[fld+'Master']:\r\n optiondict[fld+'Master'] = optiondict[fld]\r\n \r\n\r\n#########################################################################################\r\n# having a list of names to look at and match on - see if this record has a match\r\n# nameLookup - list of names could have 'None' as the last value, or just the value of None\r\n# lookupStr - string to be searched\r\n# other - array of strings that will have the matching name removed from\r\n# msg - string defining who called this function\r\n#\r\n# returns: string - if a matching string is found\r\n# None - did not find a match\r\n# '' - valid match with \"None\"\r\n#\r\ndef wineLookupByName( nameLookup, lookupStr, other, msg, wineAbbrLookup=None, debug=False ):\r\n\r\n # string for debugging messages\r\n funcname = 'wineLookupByName:' + msg + ':'\r\n\r\n # debugging\r\n if debug: print(funcname + 'nameLookup:', nameLookup)\r\n \r\n # if the value for this winery is None - than there is no additiona work we are done\r\n if nameLookup is None:\r\n # no additional processing\r\n # debugging\r\n if debug: print(funcname + 'match: value is none - continue on')\r\n # return empty string\r\n return ''\r\n\r\n \r\n # there are additional lookups for this winery - not using grape as part of the description\r\n # check each of the things to look up\r\n for name in nameLookup:\r\n # debugging\r\n if debug: print(funcname + 'match-name:', name)\r\n \r\n # special processing of a lookup value of none\r\n if name is None:\r\n # Lookup on none - means just use what we found\r\n # debugging\r\n if debug: print(funcname + 'name-matched: value is none - continue on:pass back blank')\r\n # stop iterating on nameLookup - by returning empty string\r\n return ''\r\n\r\n # we have not encountered 'None' - so build the regex based on the text provided\r\n reName = re.compile( r'\\b'+name+r'\\b', re.IGNORECASE)\r\n\r\n # check to see if we have a match with this regex\r\n if reName.search(lookupStr):\r\n # we have a match - so this is the additional attribute we are looking for\r\n # debugging\r\n if debug: print(funcname+'name-MATCHED:', name)\r\n # remove from other if it is in there\r\n for val in other:\r\n if reName.search(val):\r\n other.remove(val)\r\n # debugging\r\n if debug: print(funcname + 'name-remove-from-other:', val)\r\n # stop iterating on nameLookup - return what we found\r\n return name\r\n\r\n # 2nd check see if have a translation and this name is translatable\r\n if wineAbbrLookup and name in wineAbbrLookup:\r\n # build the regex with the look up value\r\n reName = re.compile(wineAbbrLookup[name], re.IGNORECASE)\r\n # debugging\r\n if debug: print(funcname + 'Abbr-match-name:', name)\r\n # check to see if we have a match with this regext\r\n if reName.search(lookupStr):\r\n # we have a match - so this is the additional attribute we are looking for\r\n # debugging\r\n if debug: print(funcname+'Abbr-name-MATCHED:', wineAbbrLookup[name])\r\n # remove from other if it is in there\r\n for val in other:\r\n if reName.search(val):\r\n other.remove(val)\r\n # debugging\r\n if debug: print(funcname + 'name-remove-from-other:', val)\r\n # stop iterating on nameLookup - return what we found\r\n return name\r\n\r\n # checked all the namelookupd - and did not find any matches\r\n # debuging\r\n if debug: print(funcname + 'name match not found:set to blank')\r\n # return none meaning we did not find a match\r\n return None\r\n\r\n\r\n#########################################################################################\r\n# find the qualifer like gift, etch, glass tied to this string\r\n#\r\n# \r\n#\r\n# returns: first qualifier or None\r\n#\r\ndef findQualifier( wine, debug=False ):\r\n for (val, reSearch) in reQualLookup:\r\n if reSearch.search(wine):\r\n if debug: print('findQualifier:matched-returning:', val)\r\n return val\r\n\r\n if debug: print('findQualifier:no-match-returning:', None)\r\n return None\r\n\r\n\r\n#########################################################################################\r\n# find the winery tied to the rec\r\n#\r\n# Global Variable Used: wineryLookup (an array of regex that define the winery)\r\n#\r\n# returns: (winery, reWinery)\r\n#\r\ndef findWinery( rec, lastWinery, lastReWinery, fldWine, debug=False ):\r\n # if we had a prior winery - test for this match first\r\n if lastWinery:\r\n # debugging\r\n if debug:\r\n try:\r\n print('fw:new winery:', rec[fldWine])\r\n except Exception as e:\r\n print('debug error8-continuing:', str(e))\r\n print('rec[fldWine]:type:', type(rec[fldWine]))\r\n # print('fw:new winery:', rec[fldWine].decode('windows-1252'))\r\n print('fw:checking if this is lastWinery:', lastWinery)\r\n \r\n # check to see if the winery is a match again for this record\r\n if lastReWinery.search(rec[fldWine]):\r\n # debugging\r\n if debug: print('fw:this matches the last winery')\r\n # match again - return values\r\n return(lastWinery, lastReWinery)\r\n else:\r\n # not match - debugging\r\n if debug: print('fw:not last winery')\r\n\r\n # if we did not match lastWinery - lets look through the list\r\n # go through the list of wineries (global variable),\r\n # each row contains wineryName, wineryRegex\r\n # pulling out the tuple from the lookup\r\n for (winery, reWinery) in wineryLookup:\r\n # debugging\r\n if debug: print('fw:not lastWinery-checking winery:', winery)\r\n\r\n if fldWine not in rec:\r\n print('not a column in this record fldWine:', fldWine)\r\n print('rec:', rec)\r\n \r\n # check to see if this winery is a match\r\n if reWinery.search(rec[fldWine]):\r\n # debugging\r\n if debug: print('fw:winery match found:', winery)\r\n # this is a match - set the variables\r\n return (winery, reWinery)\r\n\r\n # for loop ends without a match\r\n # did not find a matching winery in the for loop - clear values\r\n return (None, None)\r\n\r\n#########################################################################################\r\n# find the liquor tied to the rec, leveraging the winery\r\n# Global Variable Used: liquorLookup\r\n#\r\n# returns: (liquor, reLiquor)\r\n#\r\ndef findLiquor( rec, winery, fldWine, debug=False ):\r\n\r\n # go through the list of liquors (global variable), pulling out the tuple from the lookup\r\n for (liquor, reLiquor) in liquorLookup[winery]:\r\n # debugging\r\n if debug: print('fl:checking liquor:', liquor)\r\n\r\n # check to see if this liquor is a match\r\n if reLiquor.search(rec[fldWine]):\r\n # debugging\r\n if debug: print('fl:liquor match found:', liquor)\r\n # this is a match - set the variables\r\n return (liquor, reLiquor)\r\n\r\n # for loop ends without a match\r\n # did not find a matching liquor in the for loop - clear values\r\n return (None, None)\r\n\r\n#########################################################################################\r\n# find the grape tied to the rec by regex evaluation\r\n#\r\n# Global Variable Used: grapeLookup\r\n#\r\n# returns: (grape, reGrape)\r\n#\r\ndef findGrapeByRegex( rec, fldWine, debug=False ):\r\n\r\n # go through the list of liquors (global variable), pulling out the tuple from the lookup\r\n for (grape, reGrape) in grapeLookup:\r\n # debugging\r\n if debug: print('fgbr:grape:', grape)\r\n\r\n # check to see if this liquor is a match\r\n if grape is not None and reGrape.search(rec[fldWine]):\r\n # debugging\r\n if debug: print('fgbr:grape match found:', grape)\r\n # this is a match - set the variables\r\n return (grape, reGrape)\r\n\r\n # for loop ends without a match\r\n # did not find a matching grape in the for loop - clear values\r\n return (None, None)\r\n\r\n#########################################################################################\r\n# find a string in a field of a record using string match and \r\n# on match, return that it matched and the remainder of the string as an array\r\n#\r\n# returns: (findStr, other)\r\n#\r\ndef findStrInRecReturnOther( rec, fldWineDescr, findStr, debug=False ):\r\n # find where in the string this findStr is positioned\r\n matchLoc = rec[fldWineDescr].find(findStr)\r\n # if we found a location\r\n if matchLoc > -1:\r\n # then strip everthing to the left of the findStr value and then split this to create other attributes\r\n other = rec[fldWineDescr][matchLoc+len(findStr)+1:].split()\r\n \r\n # debugging\r\n if debug: print('fsirro:findStr matched:', findStr)\r\n if debug: print('fsirro:findStr other:', other)\r\n \r\n # return what we found\r\n return (findStr, other)\r\n \r\n #no match found - debugging\r\n if debug: print('fsirro:findStr did not match using:', findStr)\r\n # did not find a matching findStr - return that fact\r\n return (None, [])\r\n \r\n#########################################################################################\r\n# find the grape tied to the rec and the list of other attributes\r\n# to the right of the grape in that description\r\n#\r\n# Global Variable Used: grapeLookup\r\n#\r\n# returns: (grape, other)\r\n#\r\ndef findGrapeByStr( rec, fldWineDescr, debug=False ):\r\n # find the grape and strip everything right of that from the fldWineDescr field\r\n for (grape,reGrape) in grapeLookup:\r\n # debugging\r\n if debug: print('fg:grape:', grape)\r\n\r\n # find where in the string this grape is positioned\r\n (grape, other) = findStrInRecReturnOther( rec, fldWineDescr, grape, debug=debug)\r\n\r\n # if we have a match return that match\r\n if grape:\r\n return (grape, other)\r\n \r\n # did not find a matching grape - return that fact\r\n return (None, [])\r\n \r\n#########################################################################################\r\n# find the vintage tied to the rec\r\n#\r\n# Global Variable Used: vintageLookup\r\n#\r\n# returns: vintage\r\n#\r\ndef findVintage( rec, fldWine, debug=False ):\r\n # loop through the vintage lookup records\r\n for reVintage in vintageLookup:\r\n # search for match\r\n m = reVintage.search(rec[fldWine])\r\n # if there is a match\r\n if m:\r\n # extract the vlaue from the first regex group with a value\r\n if m.group(1):\r\n vintage = m.group(1)\r\n if debug: print('fv:vintage-match:', reVintage,':group1')\r\n elif m.group(2):\r\n vintage = m.group(2)\r\n if debug: print('fv:vintage-match:', reVintage,':group2')\r\n elif m.group(3):\r\n vintage = m.group(3)\r\n if debug: print('fv:vintage-match:', reVintage,':group3')\r\n else:\r\n vintage = m.group(4)\r\n if debug: print('fv:vintage-match:', reVintage,':group4')\r\n # return what we vound\r\n return vintage\r\n\r\n # did not find it\r\n return None\r\n \r\n#########################################################################################\r\n# Create the winery/grape-wine-liquour conversion table based on the\r\n# array of records passed in\r\n#\r\n# this routine takes the already read in list of definitions and parses them up\r\n# in order to create a winery-wine-attributes file - that will be used\r\n# later to take new records from searching the internet and properly assign\r\n# an aligned/consistent wine description to that wine string\r\n#\r\n# we expect the wines array to have attributes: fldWineDescr (winedescr), and fldWine (wine_name)\r\n#\r\n# returns: wgLookup - dictionary - which is built from parsing winedescr NOT wine_name\r\n#\r\n# wgLookup[winery][grape] = list of lists of attributes to perform lookups with\r\n#\r\ndef buildWineryGrapeLookup( wines, fldWineDescr='winedescr', fldWine='wine', debug=False ):\r\n\r\n # local variables\r\n wgLookup = {}\r\n lastWinery = None\r\n lastReWinery = None\r\n\r\n\r\n # step through the records read in\r\n for rec in wines:\r\n # debugging\r\n if debug: print('bwgl:new rec:', rec[fldWineDescr])\r\n\r\n # set the variable\r\n if not fldWineDescr in rec:\r\n print('creating-field:', fldWineDescr)\r\n rec[fldWineDescr] = ''\r\n \r\n # local loop variables\r\n winery = grape = wine = liquor = None\r\n other = []\r\n \r\n ### WINERY\r\n (lastWinery, lastReWinery) = (winery, reWinery) = findWinery( rec, lastWinery, lastReWinery, fldWine, debug=debug )\r\n \r\n # if we did not find the winery - skipt this record\r\n if not winery:\r\n # debugging\r\n if debug: print('bwgl:did not find winery-skipping:', rec[fldWine])\r\n # don't process this record - get the next record to process\r\n continue\r\n\r\n ### IGNOREGRAPE and NOGRAPE and LIQUOR\r\n\r\n # if this winery has a noGrapeLookup option - use that to split up the record\r\n if winery in ignoreGrapeLookup:\r\n ### BLANK WINE\r\n \r\n # don't get the grape for this winery\r\n # set wine to blank\r\n wine = ''\r\n # debugging\r\n if debug: print('bwgl:wine check ignoreGrapeLookup on winery:', winery)\r\n elif winery in noGrapeLookup:\r\n ### NO GRAPE WINE -- fldWineDescr\r\n \r\n # debugging\r\n if debug: print('bwgl:wine check noGrapeLookup on winery:', winery)\r\n \r\n # find which wine is a match from the noGrapeLookup\r\n wine = wineLookupByName( noGrapeLookup[winery], rec[fldWineDescr], [], 'noGrapeLookup', debug=debug )\r\n\r\n # not getting a match - we want to continue to have the wine as blank\r\n if False and wine == '':\r\n # debugging\r\n if debug: print('bwgl:nograpelookup:no-match:set wine to None')\r\n wine = None\r\n elif winery in liquorLookup:\r\n ### LIQUOR ---- fldWine\r\n # debugging\r\n if debug: print('bwgl:liquor check on winery:', winery)\r\n # see if a liquor matches\r\n (liquor, reLiquor) = findLiquor( rec, winery, fldWine, debug=debug )\r\n # if we found match - populate wine so we don't look for grape\r\n if liquor is not None:\r\n wine = liquor\r\n # debugging\r\n if debug: print('bwgl:liquor found and put in wine:', wine)\r\n\r\n \r\n ### GRAPE (if we have not filled in wine) --- fldWineDescr\r\n if wine is None:\r\n # debugging\r\n if debug: print('bwgl:grape check because wine is None')\r\n # determine if there is a grape in this string\r\n # if ther\r\n (grape,other) = findGrapeByStr( rec, fldWineDescr )\r\n # debugging\r\n if debug: print('bwgl:grape:', grape, ':other:', other)\r\n else:\r\n # debugging\r\n if debug: print('bwgl:grape check skipped - we have a wine')\r\n\r\n ### Skip this record if we don't have a wine or a grape\r\n if wine is None and grape is None:\r\n # debugging\r\n if debug: print('bwgl:record skipped - no grape or wine defined')\r\n continue\r\n\r\n ### OTHER (if not already created by grape lookup) ---- fldWineDescr\r\n #\r\n # if we did not find the grape in the string\r\n # so other was not populated\r\n # we need to look up other using 'winery' as the filter\r\n if grape is None:\r\n # debugging\r\n if debug: print('bwgl:build other from winery')\r\n # find where in the string this grape is positioned\r\n (wineryFind, other) = findStrInRecReturnOther( rec, fldWineDescr, winery, debug=debug)\r\n\r\n \r\n ### OTHER Additional Processing\r\n\r\n # remove CASE - the keyword case if it exists\r\n if 'case' in other:\r\n other.remove('case')\r\n # debugging\r\n if debug: print('bwgl:remove case from other')\r\n \r\n # remove VINTAGE and/or BOTTLESIZE and/or other QUALIFIERS\r\n # the last element will either be the vintage (no bottle size)\r\n # or will be the bottle size and then next is the vintage\r\n # if the last position is not vintage, attempt to remove the bottle size\r\n # then remove vintage - this should be the vintage (validated by isdigit lookup)\r\n if other:\r\n if debug: print('bwgl:looking at other for quals, bottlesize and vintage')\r\n # remove qualifiers if exist\r\n if not other[-1].isdigit():\r\n # first we check to see if there is a qualifier appended\r\n # we are not vintage as the position posiition - see if it is size\r\n for qual,reQual in reQualLookup:\r\n if qual == other[-1]:\r\n if debug: print('bwgl:remove qualifier from other:', qual)\r\n del other[-1]\r\n break\r\n \r\n # remove bottle size if exist\r\n if other and not other[-1].isdigit():\r\n # we are not vintage as the position posiition - see if it is size\r\n for size,reSize in sizeLookup:\r\n if size == other[-1]:\r\n if debug: print('bwgl:remove bottlesize from other:', size)\r\n del other[-1]\r\n break\r\n\r\n # remove vintage if it is there\r\n if other and other[-1].isdigit():\r\n # first check to see if this is part of the ignore grape solution\r\n if winery in ignoreGrapeLookup and ignoreGrapeLookup[winery]and other[-1] in ignoreGrapeLookup[winery]:\r\n if debug: print('bwgl:value is in ignoreLookupGrape - keeping it:', other[-1])\r\n else:\r\n # debugging\r\n if debug: print('bwgl:remove vintage from other:', other[-1])\r\n del other[-1]\r\n\r\n # remove WINE - the element if the element is the same as the wine\r\n if wine and wine in other:\r\n other.remove(wine)\r\n # debugging\r\n if debug: print('bwgl:remove wine from other:', wine)\r\n\r\n # debugging\r\n if debug:\r\n try:\r\n print('bwgl:Final-Build:', winery, ':', grape, ':', wine, ':', liquor, ':', other, ':', rec[fldWineDescr], ':', rec[fldWine])\r\n except Exception as e:\r\n print('debug error2-continuing:', str(e))\r\n print('fldWine:', fldWine)\r\n\r\n ### BUILD LOOKUP FOR CONVERSION (we use the grape attribute to build the dictionary)\r\n\r\n # move liquor value into grape because we did not find the\r\n if grape is None and wine is not None:\r\n grape = wine\r\n # debugging\r\n if debug: print('bwgl:set-grape-to-wine:', grape)\r\n \r\n\r\n ### WINERY:GRAPE-WINE-LIQOUR Dictionary creation\r\n\r\n # debugging\r\n if debug: print('bwgl:create wgLookup for winery:', winery, ':grape:', grape)\r\n \r\n # validate we have an entry for this winery in the lookup dict\r\n if winery not in wgLookup:\r\n # one does not create - so create a stub for winery:grape\r\n wgLookup[winery] = { grape : [] }\r\n else:\r\n # one DOES exist - check to see if the grape is already here\r\n if grape not in wgLookup[winery]:\r\n # grape is not here - so create an empty list to stuff values into\r\n wgLookup[winery][grape] = []\r\n\r\n # check to see if we have OTHER attributes\r\n # and if we do - check to see that this list of attributes\r\n # is not already in the wineLookup array\r\n # and if this list does not exist - then append this list\r\n if other and other not in wgLookup[winery][grape]:\r\n # add this list of other to this entry\r\n wgLookup[winery][grape].append(other)\r\n # debugging\r\n if debug: print('bwgl:appending to wgLookup:other:', other)\r\n \r\n # end loop on wines\r\n\r\n ### SORTED WINERY:GRAPE lookup - most optional attributes first in the list\r\n\r\n # debbuging\r\n if debug: print('bwgl:complete-read-of-master-file:sort wgLookup')\r\n\r\n # now sort the list of lookups from most specific (greatest number of attributes) to least\r\n for winery in wgLookup:\r\n for grape in wgLookup[winery]:\r\n wgLookup[winery][grape] = sorted(wgLookup[winery][grape], key=len, reverse=True)\r\n \r\n\r\n # debugging\r\n if debug:\r\n print('\\n'*5)\r\n print('START WGLOOKUP DUMPED')\r\n print('#'*80)\r\n if ppFlag:\r\n pp.pprint(wgLookup)\r\n else:\r\n print('bwgl:final-wgLookup:\\n', wgLookup)\r\n print('#'*80)\r\n\r\n \r\n # done with for loop - return the lookup\r\n return wgLookup\r\n\r\n#########################################################################################\r\n# find the matching set of additional attributes that match this record\r\n# from the global lookup.\r\n#\r\n# we assume that we have already tested that winery and value exist in wgLookup prior to calling this routine\r\n#\r\n# the special paramaters here are:\r\n# value - this is either \"wine\" or \"grape\" - this routine allows you to lookup on different attributes\r\n# valueDescr - passed in string for debugging telling us which value was passed in\r\n#\r\n# defaultorderlist = array of array of string - gives the default order of singlematch looks to determine which of\r\n# many matches is the one we will select\r\n#\r\n# Global Variable Used: wgLookup\r\n#\r\n# returns: valuematchset array selected\r\n#\r\ndef findAddAttribWgLookup( rec, winery, value, fldWine, AbbrLookup=[], defaultorderlist=None, valueDescr='', debug=False ):\r\n\r\n # local variable - capture all the entries that are single match entries\r\n singlematch=[]\r\n\r\n # debugging\r\n if debug:\r\n try:\r\n print('faawl:value:', valueDescr, ':match-wgLookup:', rec[fldWine], ':', wgLookup[winery][value])\r\n except Exception as e:\r\n print('debug error7-continuing:', str(e))\r\n print('fldWine:', fldWine)\r\n\r\n # for each set of values that could be a match\r\n for valuematchset in wgLookup[winery][value]:\r\n # debugging\r\n if debug: print('faawl:testing valuematchset:', valuematchset, ':length:', len(valuematchset))\r\n # set the flag to start\r\n allmatch = True\r\n # loop through the set of values that make up this set\r\n for valuematch in valuematchset:\r\n # for each entry - build a regex and test it and add it up\r\n # we need all values in this valueset to be true for this valueset to be match\r\n reMatch1 = re.compile(r'\\b'+valuematch+r'\\b', re.IGNORECASE)\r\n reMatch2 = re.compile(r'\\s'+valuematch+r'\\s', re.IGNORECASE)\r\n # check to see if this regex is a match\r\n m1 = reMatch1.search(rec[fldWine])\r\n m2 = reMatch2.search(rec[fldWine])\r\n if m1 or m2:\r\n # this regex is a match\r\n allmatch = True and allmatch\r\n elif valuematch in AbbrLookup:\r\n # this regex was not a match - but we want to check if the value also has\r\n # a translation - and if it has a translation - then we test the translation also\r\n # the value did not work but there is an alternate value to check\r\n # debugging\r\n if debug: print('faawl:valuematch-abbr:', valuematch, ':', wineAbbrLookup[valuematch])\r\n # create the regex\r\n reMatch = re.compile(wineAbbrLookup[valuematch], re.IGNORECASE)\r\n # test the regex and attach the results to allmatch\r\n allmatch = reMatch.search(rec[fldWine]) and allmatch\r\n else:\r\n # not a match - update allmatch\r\n allmatch = False and allmatch\r\n \r\n # debugging\r\n if debug: print('faawl:valuematch:', valuematch, ':allmatch:', allmatch)\r\n\r\n # check to see if all matched\r\n if allmatch:\r\n # all matched - so this is a match - so break out of the valuematchset group\r\n # debugging\r\n if debug: print('faawl:value matched:', valuematchset)\r\n # different action based on # of items being match\r\n if len(valuematchset) == 1:\r\n # debugging\r\n if debug: print('faawl:single-valuematch-set-added-to-singlematch:', valuematchset)\r\n # single value matching - we don't stop when we find a match\r\n singlematch.append(valuematchset)\r\n else:\r\n # debugging\r\n if debug: print('faawl:multivalue-valuematch-set-found:done')\r\n # multi value match so we are done when we find a match - so return\r\n return valuematchset\r\n\r\n # did not find matchset in the for loop - check to see if we have singlematch\r\n if not singlematch:\r\n # debugging\r\n if debug: print('faawl:exit with singlematch NOT populated return blank')\r\n # did not have singlematch found - we are done - return empty\r\n return []\r\n \r\n\r\n # singlematch populated\r\n # debugging\r\n if debug: print('faawl:exit with singlematch populated:', singlematch)\r\n # check to see how many matches we got\r\n if len(singlematch) == 1 or not defaultorderlist:\r\n # debugging\r\n if debug: print('faawl:return first entry in singlematch:', singlematch[0])\r\n # if there is only one entry in here\r\n # or we don't have a default order so we pick the first found\r\n # and we set the value to this\r\n return singlematch[0]\r\n\r\n # we need to define which of the singlematch values we will return\r\n # the defaultorderlist will be used to set that ordering\r\n #\r\n # create a local copy of the list that can be changed in this routine\r\n defaultorder = defaultorderlist[:]\r\n \r\n # multiple singlematch values so lets find and pick the best one\r\n # debugging\r\n if debug: print('faawl:multiple single match value-singlematch:', singlematch)\r\n\r\n\r\n # get the values from singlematch that are not in defaultorder\r\n # and put them at the start of defaultorder list\r\n # go in reverse order when doing this lookup\r\n for val in singlematch[::-1]:\r\n if val not in defaultorder:\r\n defaultorder.insert(0,val)\r\n \r\n ### HARDCODED ###\r\n # very short term fix - we need to prioritze these single tags (mondavi problem)\r\n if winery == 'Mondavi' and ['Tok'] in singlematch:\r\n if debug: print('faawl:Change from:', valuematchset, ':to Tok for mondavi')\r\n return ['Tok']\r\n\r\n # find the first matching value from priority order list\r\n for val in defaultorder:\r\n if val in singlematch:\r\n # debugging\r\n if debug: print('faawl:selected-singlematch-value:', val)\r\n # we found the first match - set it and break out\r\n return val\r\n\r\n # debugging\r\n if debug: print('faawl:valuematchset-empty')\r\n\r\n # did not match - return empty\r\n return []\r\n\r\n\r\n\r\n#########################################################################################\r\n# create a consistent wine name for a list or records with store based wine descriptions\r\n#\r\n# the special paramaters here are:\r\n# wgLookup - dictionary of winery, wine, list of wines\r\n# wines - list of records to be processed\r\n#\r\n# Global Variable Used: ignoreGrapeLookup, noGrapeLookup, wineAbbrLookup, liquorLookup\r\n# reCase, sizeLookup\r\n#\r\n# returns: [updated values in teh wines array]\r\n#\r\n#### Use the winery/grape-wine-liquour conversion table to define a wine description for the records\r\ndef setWineryDescrFromWineryGrapeLookup( wgLookup, wines, fldWineDescr = 'winedescr', fldWine = 'wine', fldWineDescrNew = 'winedescrnew', fldWineDescrMatch=False, debug=False ):\r\n\r\n if debug:\r\n print('\\n'*10,'START WINEDESCR SETTING HERE ---------------------------------------------')\r\n \r\n # step through all the records passed in\r\n for rec in wines:\r\n\r\n # local variables\r\n winery = grape = wine = vintage = case = size = liquor = nongrape = qual = None\r\n winematchset = grapematchset = []\r\n \r\n # debugging\r\n if debug:\r\n try:\r\n print('setWinery:fldWine:', rec[fldWine])\r\n except Exception as e:\r\n print('debug error2-continuing:', str(e))\r\n print('fldWine:', fldWine)\r\n \r\n # make the field if it does not exist\r\n if fldWineDescrNew not in rec:\r\n rec[fldWineDescrNew] = rec[fldWineDescr]\r\n \r\n ### WINERY\r\n (winery, reWinery) = findWinery( rec, None, None, fldWine, debug=debug )\r\n \r\n # validate the winery\r\n if winery is None:\r\n ### WINERY NONE - go to next record\r\n # debugging\r\n if debug: print('setWinery:winery not found-next record:' + rec[fldWine])\r\n # get the next record\r\n continue\r\n elif winery not in wgLookup:\r\n ### WINERY NOT IN LOOKUP\r\n # skip this record - nothing to process\r\n # debugging\r\n if debug: print('setWinery:winery not in wgLookup:', winery)\r\n continue\r\n\r\n ### GRAPE\r\n # find the grape that is this record\r\n (grape, reGrape) = findGrapeByRegex( rec, fldWine, debug=debug )\r\n\r\n # debugging\r\n if debug: print('setWinery:grape found:', grape)\r\n \r\n ### OVERRIDES\r\n if winery in ignoreGrapeLookup:\r\n ### IGNORE GRAPE\r\n \r\n # debugging\r\n if debug: print('setWinery:winery-match-ignoreGrape:clear-wine:set-grape-to-None:set-nongrape-True:winery:', winery)\r\n \r\n # clear wine and grape\r\n wine = ''\r\n\r\n # clear the grape field\r\n grape = None\r\n \r\n # set the liquor flag to control processing\r\n nongrape = True\r\n \r\n if winery in noGrapeLookup:\r\n ### NOGRAPE - WINE\r\n\r\n # debugging\r\n if debug: print('setWinery:noGrapeLookup wine check:', winery)\r\n\r\n # do the lookup and if a search is a match on None take appropriate action\r\n wine = wineLookupByName( noGrapeLookup[winery], rec[fldWine], [], 'noGrapeLookup', wineAbbrLookup, debug=debug )\r\n\r\n # debugging\r\n if debug: print('setWinery:nogrape check:wine:', wine)\r\n \r\n # test the value we got back\r\n if wine == '':\r\n # debugging\r\n if debug: print('setWinery:noGrapeLookup:matched:None::clear grape:set nongrape to True')\r\n # the lookup match None - so we want to ignore any grape found and we blank out the wine\r\n grape = None\r\n wine = ''\r\n nongrape = True\r\n elif wine:\r\n # matched a wine - so clear the grape value\r\n grape = None\r\n # debugging\r\n if debug: print('setWinery:nograpeLookup:wine found - clear grape field') \r\n\r\n if wine is None and winery in liquorLookup:\r\n ### LIQUOR\r\n # debugging\r\n if debug: print('setWinery:liqourLookup:', winery)\r\n\r\n (liquor, reLiquor) = findLiquor( rec, winery, fldWine, debug=debug)\r\n # if we found something update wine to be what we found\r\n if liquor is not None:\r\n wine = liquor\r\n # debugging\r\n if debug: print('setWinery:liquorLookup-match:', liquor)\r\n\r\n if not grape and not nongrape and not wine and liquor is None:\r\n # NO GRAPE - and not connected to noGrapeLookup or liquorLookkup\r\n # get the next record\r\n # debugging\r\n if debug: print('setWinery:did not find grape-skipping record:', rec[fldWineDescr])\r\n continue\r\n\r\n # debugging\r\n if debug: print('setWinery:pre-vintage found values for wine/liquor:', wine, ':grape:', grape)\r\n \r\n ### VINTAGE\r\n vintage = findVintage( rec, fldWine, debug=debug )\r\n\r\n # debugging\r\n if debug: print('setWinery:vintage:', vintage)\r\n \r\n ### CASE information\r\n if reCase.search(rec[fldWine]):\r\n case = 'case'\r\n \r\n ### BOTTLE SIZE - get the size information\r\n for (size, reSize) in sizeLookup:\r\n # debugging\r\n if debug: print('setWinery:sizeLookup:',size)\r\n if reSize.search(rec[fldWine]) and not reShipsAs.search(rec[fldWine]):\r\n # debugging\r\n if debug: print('setWinery:sizeLookup:matched:',reSize)\r\n break\r\n else:\r\n size = None\r\n if debug: print('setWinery:sizeLookup:None-found')\r\n\r\n ### QUAL for this wine\r\n qual = findQualifier(rec[fldWine], debug=debug)\r\n\r\n # debugging\r\n if debug:\r\n try:\r\n print('setWinery:FinalAttributes:', winery, ':', grape, ':', wine, ':', liquor, ':', vintage, ':', case, ':', size, ':', qual, ':', rec[fldWine])\r\n except Exception as e:\r\n print('debug error5-continuing:', str(e))\r\n print('fldWine:', fldWine)\r\n \r\n\r\n ### WINE - ADDITIONAL INFORMATION\r\n if liquor is not None:\r\n # debugging\r\n if debug: print('setWinery:liquor flag set - no additional data needs to be collected')\r\n elif wine is not None:\r\n\r\n # debugging\r\n if debug: print('setWinery:wine is not None - do additional lookups:wine:', wine) \r\n \r\n # we found a wine / liquor - so see if there are additional attributes\r\n if wine in wgLookup[winery] and wgLookup[winery][wine]:\r\n # debugging\r\n if debug: print('setWinery:lookup winematchset')\r\n # there is one or more additional lookups for this winery/wine\r\n winematchset = findAddAttribWgLookup( rec, winery, wine, fldWine, wineAbbrLookup, None, valueDescr='wine', debug=debug )\r\n else:\r\n # wine not in wgLookup so thing to work\r\n print('setWinery:unable to perform wgLookup on winery:', winery, ':wine:', wine, ':rec-wine:', rec[fldWine])\r\n # debugging\r\n if debug:\r\n try:\r\n print('wgLookup[winery]:', wgLookup[winery])\r\n except Exception as e:\r\n print('debug error3-continuing:', str(e))\r\n print('winery:', winery)\r\n \r\n # debugging - wine is not None - what is the final winematchset\r\n if debug: print('setWinery:winematchset:', winematchset)\r\n elif grape is not None:\r\n # debugging\r\n if debug: print('setWinery:grape is not None - do additional lookups:', grape)\r\n\r\n # grape was returned (not wine) so do the lookup on grape\r\n if grape in wgLookup[winery] and wgLookup[winery][grape]:\r\n # see if we can create a match based on attributes and the grape\r\n grapematchset = findAddAttribWgLookup( rec, winery, grape, fldWine, wineAbbrLookup, defaultorderlist, valueDescr='grape', debug=debug )\r\n\r\n elif grape in wgLookup[winery]:\r\n # do nothing this is a empty set\r\n if debug: print('setWinery:grape match: matching record set is blank - no action required')\r\n else:\r\n # wine not in wgLookup so thing to work\r\n # debugging\r\n print('setWinery:grape NONMATCH:', rec[fldWine])\r\n if debug: print('setWinery:liquor:', liquor, ':wine:', wine, ':grape:', grape, ':wgLookup[winery]:', wgLookup[winery])\r\n\r\n # debugging - wine is not None - what is the final grapematchset\r\n if debug: print('setWinery:grapematchset:', grapematchset)\r\n\r\n ### check the matchsets we got back - if any of them look like vintage values\r\n ### remove them from the string and look at up vintage again\r\n if vintage:\r\n newVintageLookupWine = rec[fldWine]\r\n for matchvalue in winematchset:\r\n if vintage in matchvalue:\r\n newVintageLookupWine = newVintageLookupWine.replace(matchvalue,'')\r\n if debug: print('setWinery:2nd-vintage:winematchset:wine-name-removal:', matchvalue)\r\n for matchvalue in grapematchset:\r\n if vintage in matchvalue:\r\n newVintageLookupWine = newVintageLookupWine.replace(matchvalue,'')\r\n if debug: print('setWinery:2nd-vintage:grapematchset:wine-name-removal:', matchvalue)\r\n if newVintageLookupWine != rec[fldWine]:\r\n if debug: print('setWinery:2nd-vintage:newVintageLookupWine:', newVintageLookupWine)\r\n newVintage = findVintage( { fldWine : newVintageLookupWine}, fldWine, debug=debug )\r\n if debug: print('setWinery:2nd-vintage:newVintage:', newVintage)\r\n vintage = newVintage\r\n\r\n ### FINAL WINEDESCR\r\n\r\n # create initial value\r\n wineDescr = ''\r\n\r\n\r\n # if winery starts with a z then we don't have a vintage\r\n if winery.startswith('z'):\r\n vintage = None\r\n # debugging\r\n if debug: print('setWinery:winery starts with z: clear vintage')\r\n\r\n # quick test - does the wine and the winematchset the same\r\n if winematchset and ' '.join(winematchset) in wine:\r\n #debugging\r\n if debug: print('setWinery:clearing-winematchset:', winematchset,':is-in-wine:', wine)\r\n winematchset = []\r\n if grapematchset and ' '.join(grapematchset) in grape:\r\n #TODO - work around for single letter matches\r\n if not (len(grapematchset)==1 and len(grapematchset[0])==1):\r\n #debugging\r\n if debug: print('setWinery:clearing-grapematchset:',grapematchset,':is-in-grape:', grape)\r\n grapematchset = []\r\n if grapematchset and size and size in ' '.join(grapematchset):\r\n size = ''\r\n if winematchset and size and size in ' '.join(winematchset):\r\n size = ''\r\n\r\n if debug:\r\n print('setWinery:vallist1:', [winery, grape, wine] + grapematchset + winematchset + [vintage, size, qual, case])\r\n print('setWinery:vallist2:', [winery, grape, wine, *grapematchset, *winematchset, vintage, size, qual, case])\r\n \r\n # create a list\r\n wdList= []\r\n # step through the values\r\n for val in [winery, grape, wine] + grapematchset + winematchset + [vintage, size, qual, case]:\r\n # and if there is a value add to the list - otherwise skip\r\n if val: wdList.append(val)\r\n\r\n # build the wine description by joining all these values together\r\n wineDescr = ' '.join(wdList)\r\n\r\n # debugging\r\n if False:\r\n if debug: print('setWinery:wdList:', wdList)\r\n if debug: print('setWinery:wineDescr:', wineDescr)\r\n \r\n # debugging\r\n if debug:\r\n try:\r\n print(':'.join(['setWinery:wineDescrList', wineDescr, rec[fldWineDescr], str(wineDescr==rec[fldWineDescr]), rec[fldWine]]) )\r\n except Exception as e:\r\n print('debug error6-continuing:', str(e))\r\n print('fldWine:', fldWine)\r\n\r\n # fill thew new value into the array\r\n rec[fldWineDescrNew] = wineDescr\r\n\r\n # fill in the matching field\r\n if fldWineDescrMatch:\r\n rec[fldWineDescrMatch] = (rec[fldWineDescr] == rec[fldWineDescrNew])\r\n \r\n\r\n#########################################################################################\r\n# set any digit only field to the word passed \r\ndef setDigitFld2Value( wines, fld, value, debug=False ):\r\n for rec in wines:\r\n if rec[fld].isdigit():\r\n rec[fld] = value\r\n\r\n#########################################################################################\r\n# validate the field settings match the file we read in for update\r\ndef updateFileOptionDictCheck( optiondict, wines, header, debug=False ):\r\n # check to see if the description field is in the file we read in\r\n if optiondict['fldWineDescr'] not in wines[0]:\r\n if debug: print('updateFileOptionDictCheck:fldWineDescr NOT in file read in:', optiondict['fldWineDescr'])\r\n # field needed is not in the record - see if we know what to do\r\n if 'cnt' in wines[0]:\r\n # the cnt field is in the file - so set to that structure\r\n # we will put the updated values into the 'cnt' field\r\n print('setting values fldWineDescr and fldWineDescrNew to: cnt')\r\n # change the field we are updating\r\n optiondict['fldWineDescr'] = optiondict['fldWineDescrNew'] = 'cnt'\r\n elif 'winedescr' in wines[0]:\r\n # the WineDescr field is in the file - so set to that structure\r\n print('setting values fldWineDescr to winedescr and fldWineDescrNew to winedescrnew')\r\n # change the field we are updating\r\n optiondict['fldWineDescr'] = 'winedescr'\r\n optiondict['fldWineDescrNew'] = 'winedescrnew'\r\n else:\r\n # no idea - we need to error out\r\n print('could not find fldWineDescr in wines[0]-aborting:', optiondict['fldWineDescr'], '\\nwines[0]:', wines[0])\r\n # force the error\r\n error = wines[0][optiondict['fldWineDescr']]\r\n\r\n # determine if we should create the match column (may want ot remove this section later)\r\n # removed this logic - require the person to set this field - we will not set it for them.\r\n if False and optiondict['fldWineDescr'] == 'winedescr':\r\n # we are using the file format that is the xref file\r\n # so check to see if we have match enabled\r\n if not optiondict['fldWineDescrMatch']:\r\n # create the default value\r\n optiondict['fldWineDescrMatch'] = 'same'\r\n # provide message\r\n print('setting value fldWineDescrMatch to: same')\r\n\r\n # check to see if the input file is the same as the output file\r\n if optiondict['csvfile_update_in'] == optiondict['csvfile_update_out']:\r\n # they are the same file (in and out) - so we need to move the input file to a backup location\r\n (file_path, base_filename, file_ext) = kvutil.filename_split(optiondict['csvfile_update_in'])\r\n # create the new filename\r\n backupfile = kvutil.filename_proper( base_filename + optiondict['backupfile_ext'], file_path )\r\n # messaging\r\n print('copying ', optiondict['csvfile_update_in'], ' to ', backupfile)\r\n # copy the input file to the backup filename\r\n shutil.copyfile(optiondict['csvfile_update_in'], backupfile)\r\n\r\n # set the output keys we are going to assign\r\n if optiondict['fldWineDescrNew'] == 'cnt':\r\n # output matches the original ref file format with the \"cnt\" field\r\n optiondict['csvdictkeys'] = ['cnt','date','search','store','wine','winesrt']\r\n elif optiondict['fldWineDescrMatch']:\r\n # output is a modified xref format so you can look at old and new definitions\r\n# optiondict['csvdictkeys'] = [optiondict['fldWineDescr'],optiondict['fldWineDescrNew'],optiondict['fldWineDescrMatch'], 'date','search','company','wine','winesrt']\r\n optiondict['csvdictkeys'] = [optiondict['fldWineDescr'],optiondict['fldWineDescrNew'],optiondict['fldWineDescrMatch'], *header]\r\n else:\r\n # copy over the read in format\r\n optiondict['csvdictkeys'] = [optiondict['fldWineDescrNew']] + header[1:]\r\n # output matches expected input - should really change this to be the format of the read in file\r\n #optiondict['csvdictkeys'] = [optiondict['fldWineDescrNew'], 'date','search','company','wine','winesrt']\r\n\r\n print('updateFileOptionDictCheck:set csvdictkeys to:',optiondict['csvdictkeys'])\r\n\r\n \r\n# ---------------------------------------------------------------------------\r\nif __name__ == '__main__':\r\n\r\n # capture the command line\r\n optiondict = kvutil.kv_parse_command_line( optiondictconfig, debug=False )\r\n\r\n # set the global debug flag\r\n ppFlag = optiondict['pprint']\r\n\r\n # set master fields\r\n setOptionDictMasterFldValues( optiondict, debug=False )\r\n \r\n ### global variable checks ###\r\n if optiondict['setup_check']:\r\n print('Running global variable check')\r\n globalVariableCheck( debug = optiondict['debug'] )\r\n sys.exit()\r\n \r\n # messaging\r\n print('reading in master file:', optiondict['csvfile_master_in'])\r\n\r\n # read in the MASTER FILE INPUT file\r\n wines,header = kvcsv.readcsv2list_with_header(optiondict['csvfile_master_in'], headerlc=True)\r\n\r\n # build the wine lookup dictionary\r\n wgLookup = buildWineryGrapeLookup( wines, optiondict['fldWineDescrMaster'], optiondict['fldWineMaster'], debug=optiondict['debug'] )\r\n\r\n # read in the UPDATE FILE INPUT file - if not updating the master file\r\n if optiondict['csvfile_master_in'] != optiondict['csvfile_update_in']:\r\n # messaging\r\n print('reading in update file:', optiondict['csvfile_update_in'])\r\n # read in the INPUT file\r\n wines,header = kvcsv.readcsv2list_with_header(optiondict['csvfile_update_in'], headerlc=True)\r\n # check to see if we read in any records and if not just return\r\n if not wines:\r\n print('wineset.py - no records read in - no work to be done - exitting')\r\n sys.exit()\r\n \r\n\r\n # test to see if we should set the fields based on what we just read in\r\n updateFileOptionDictCheck( optiondict, wines, header, debug=optiondict['debug'] )\r\n\r\n\r\n # do the assignment of wines to records\r\n setWineryDescrFromWineryGrapeLookup( wgLookup, wines, optiondict['fldWineDescr'], optiondict['fldWine'], optiondict['fldWineDescrNew'], optiondict['fldWineDescrMatch'], debug=optiondict['debug'] )\r\n\r\n # if enabled - set all unassigned new descriptions the default value\r\n if optiondict['defaultnew'] is not None:\r\n # message\r\n print('Setting ', optiondict['fldWineDescrNew'], ' to ', optiondict['defaultnew'], 'if not set')\r\n # do the work\r\n setDigitFld2Value( wines, optiondict['fldWineDescrNew'], optiondict['defaultnew'], debug=optiondict['debug'] )\r\n\r\n # save the output to the file of interest\r\n kvcsv.writelist2csv( optiondict['csvfile_update_out'], wines, optiondict['csvdictkeys'] )\r\n\r\n # messaging\r\n print('Saved results to:', optiondict['csvfile_update_out'])\r\n\r\n", "step-ids": [ 7, 13, 15, 18, 19 ] }
[ 7, 13, 15, 18, 19 ]
<|reserved_special_token_0|> @pulumi.input_type class DashboardArgs: <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> class Dashboard(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi. ResourceOptions]=None, dashboard_definition: Optional[pulumi.Input[ str]]=None, dashboard_description: Optional[pulumi.Input[str]]=None, dashboard_name: Optional[pulumi.Input[str]]=None, project_id: Optional[pulumi.Input[str]]=None, tags: Optional[pulumi.Input[ Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]]]=None, __props__=None): """ Resource schema for AWS::IoTSiteWise::Dashboard :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] dashboard_definition: The dashboard definition specified in a JSON literal. :param pulumi.Input[str] dashboard_description: A description for the dashboard. :param pulumi.Input[str] dashboard_name: A friendly name for the dashboard. :param pulumi.Input[str] project_id: The ID of the project in which to create the dashboard. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]] tags: A list of key-value pairs that contain metadata for the dashboard. """ ... @overload def __init__(__self__, resource_name: str, args: DashboardArgs, opts: Optional[pulumi.ResourceOptions]=None): """ Resource schema for AWS::IoTSiteWise::Dashboard :param str resource_name: The name of the resource. :param DashboardArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(DashboardArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args. __dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi. ResourceOptions]=None, dashboard_definition: Optional[pulumi.Input[ str]]=None, dashboard_description: Optional[pulumi.Input[str]]=None, dashboard_name: Optional[pulumi.Input[str]]=None, project_id: Optional[pulumi.Input[str]]=None, tags: Optional[pulumi.Input[ Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]]]=None, __props__=None): opts = pulumi.ResourceOptions.merge(_utilities. get_resource_opts_defaults(), opts) if not isinstance(opts, pulumi.ResourceOptions): raise TypeError( 'Expected resource options to be a ResourceOptions instance') if opts.id is None: if __props__ is not None: raise TypeError( '__props__ is only valid when passed in combination with a valid opts.id to get an existing resource' ) __props__ = DashboardArgs.__new__(DashboardArgs) if dashboard_definition is None and not opts.urn: raise TypeError( "Missing required property 'dashboard_definition'") __props__.__dict__['dashboard_definition'] = dashboard_definition if dashboard_description is None and not opts.urn: raise TypeError( "Missing required property 'dashboard_description'") __props__.__dict__['dashboard_description'] = dashboard_description __props__.__dict__['dashboard_name'] = dashboard_name __props__.__dict__['project_id'] = project_id __props__.__dict__['tags'] = tags __props__.__dict__['dashboard_arn'] = None __props__.__dict__['dashboard_id'] = None super(Dashboard, __self__).__init__('aws-native:iotsitewise:Dashboard', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[ pulumi.ResourceOptions]=None) ->'Dashboard': """ Get an existing Dashboard resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id) ) __props__ = DashboardArgs.__new__(DashboardArgs) __props__.__dict__['dashboard_arn'] = None __props__.__dict__['dashboard_definition'] = None __props__.__dict__['dashboard_description'] = None __props__.__dict__['dashboard_id'] = None __props__.__dict__['dashboard_name'] = None __props__.__dict__['project_id'] = None __props__.__dict__['tags'] = None return Dashboard(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name='dashboardArn') def dashboard_arn(self) ->pulumi.Output[str]: """ The ARN of the dashboard. """ return pulumi.get(self, 'dashboard_arn') @property @pulumi.getter(name='dashboardDefinition') def dashboard_definition(self) ->pulumi.Output[str]: """ The dashboard definition specified in a JSON literal. """ return pulumi.get(self, 'dashboard_definition') @property @pulumi.getter(name='dashboardDescription') def dashboard_description(self) ->pulumi.Output[str]: """ A description for the dashboard. """ return pulumi.get(self, 'dashboard_description') @property @pulumi.getter(name='dashboardId') def dashboard_id(self) ->pulumi.Output[str]: """ The ID of the dashboard. """ return pulumi.get(self, 'dashboard_id') @property @pulumi.getter(name='dashboardName') def dashboard_name(self) ->pulumi.Output[str]: """ A friendly name for the dashboard. """ return pulumi.get(self, 'dashboard_name') @property @pulumi.getter(name='projectId') def project_id(self) ->pulumi.Output[Optional[str]]: """ The ID of the project in which to create the dashboard. """ return pulumi.get(self, 'project_id') @property @pulumi.getter def tags(self) ->pulumi.Output[Optional[Sequence['outputs.DashboardTag']]]: """ A list of key-value pairs that contain metadata for the dashboard. """ return pulumi.get(self, 'tags') <|reserved_special_token_1|> <|reserved_special_token_0|> @pulumi.input_type class DashboardArgs: def __init__(__self__, *, dashboard_definition: pulumi.Input[str], dashboard_description: pulumi.Input[str], dashboard_name: Optional[ pulumi.Input[str]]=None, project_id: Optional[pulumi.Input[str]]= None, tags: Optional[pulumi.Input[Sequence[pulumi.Input[ 'DashboardTagArgs']]]]=None): """ The set of arguments for constructing a Dashboard resource. :param pulumi.Input[str] dashboard_definition: The dashboard definition specified in a JSON literal. :param pulumi.Input[str] dashboard_description: A description for the dashboard. :param pulumi.Input[str] dashboard_name: A friendly name for the dashboard. :param pulumi.Input[str] project_id: The ID of the project in which to create the dashboard. :param pulumi.Input[Sequence[pulumi.Input['DashboardTagArgs']]] tags: A list of key-value pairs that contain metadata for the dashboard. """ pulumi.set(__self__, 'dashboard_definition', dashboard_definition) pulumi.set(__self__, 'dashboard_description', dashboard_description) if dashboard_name is not None: pulumi.set(__self__, 'dashboard_name', dashboard_name) if project_id is not None: pulumi.set(__self__, 'project_id', project_id) if tags is not None: pulumi.set(__self__, 'tags', tags) @property @pulumi.getter(name='dashboardDefinition') def dashboard_definition(self) ->pulumi.Input[str]: """ The dashboard definition specified in a JSON literal. """ return pulumi.get(self, 'dashboard_definition') @dashboard_definition.setter def dashboard_definition(self, value: pulumi.Input[str]): pulumi.set(self, 'dashboard_definition', value) <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> @property @pulumi.getter(name='projectId') def project_id(self) ->Optional[pulumi.Input[str]]: """ The ID of the project in which to create the dashboard. """ return pulumi.get(self, 'project_id') @project_id.setter def project_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, 'project_id', value) @property @pulumi.getter def tags(self) ->Optional[pulumi.Input[Sequence[pulumi.Input[ 'DashboardTagArgs']]]]: """ A list of key-value pairs that contain metadata for the dashboard. """ return pulumi.get(self, 'tags') @tags.setter def tags(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[ 'DashboardTagArgs']]]]): pulumi.set(self, 'tags', value) class Dashboard(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi. ResourceOptions]=None, dashboard_definition: Optional[pulumi.Input[ str]]=None, dashboard_description: Optional[pulumi.Input[str]]=None, dashboard_name: Optional[pulumi.Input[str]]=None, project_id: Optional[pulumi.Input[str]]=None, tags: Optional[pulumi.Input[ Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]]]=None, __props__=None): """ Resource schema for AWS::IoTSiteWise::Dashboard :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] dashboard_definition: The dashboard definition specified in a JSON literal. :param pulumi.Input[str] dashboard_description: A description for the dashboard. :param pulumi.Input[str] dashboard_name: A friendly name for the dashboard. :param pulumi.Input[str] project_id: The ID of the project in which to create the dashboard. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]] tags: A list of key-value pairs that contain metadata for the dashboard. """ ... @overload def __init__(__self__, resource_name: str, args: DashboardArgs, opts: Optional[pulumi.ResourceOptions]=None): """ Resource schema for AWS::IoTSiteWise::Dashboard :param str resource_name: The name of the resource. :param DashboardArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(DashboardArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args. __dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi. ResourceOptions]=None, dashboard_definition: Optional[pulumi.Input[ str]]=None, dashboard_description: Optional[pulumi.Input[str]]=None, dashboard_name: Optional[pulumi.Input[str]]=None, project_id: Optional[pulumi.Input[str]]=None, tags: Optional[pulumi.Input[ Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]]]=None, __props__=None): opts = pulumi.ResourceOptions.merge(_utilities. get_resource_opts_defaults(), opts) if not isinstance(opts, pulumi.ResourceOptions): raise TypeError( 'Expected resource options to be a ResourceOptions instance') if opts.id is None: if __props__ is not None: raise TypeError( '__props__ is only valid when passed in combination with a valid opts.id to get an existing resource' ) __props__ = DashboardArgs.__new__(DashboardArgs) if dashboard_definition is None and not opts.urn: raise TypeError( "Missing required property 'dashboard_definition'") __props__.__dict__['dashboard_definition'] = dashboard_definition if dashboard_description is None and not opts.urn: raise TypeError( "Missing required property 'dashboard_description'") __props__.__dict__['dashboard_description'] = dashboard_description __props__.__dict__['dashboard_name'] = dashboard_name __props__.__dict__['project_id'] = project_id __props__.__dict__['tags'] = tags __props__.__dict__['dashboard_arn'] = None __props__.__dict__['dashboard_id'] = None super(Dashboard, __self__).__init__('aws-native:iotsitewise:Dashboard', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[ pulumi.ResourceOptions]=None) ->'Dashboard': """ Get an existing Dashboard resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id) ) __props__ = DashboardArgs.__new__(DashboardArgs) __props__.__dict__['dashboard_arn'] = None __props__.__dict__['dashboard_definition'] = None __props__.__dict__['dashboard_description'] = None __props__.__dict__['dashboard_id'] = None __props__.__dict__['dashboard_name'] = None __props__.__dict__['project_id'] = None __props__.__dict__['tags'] = None return Dashboard(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name='dashboardArn') def dashboard_arn(self) ->pulumi.Output[str]: """ The ARN of the dashboard. """ return pulumi.get(self, 'dashboard_arn') @property @pulumi.getter(name='dashboardDefinition') def dashboard_definition(self) ->pulumi.Output[str]: """ The dashboard definition specified in a JSON literal. """ return pulumi.get(self, 'dashboard_definition') @property @pulumi.getter(name='dashboardDescription') def dashboard_description(self) ->pulumi.Output[str]: """ A description for the dashboard. """ return pulumi.get(self, 'dashboard_description') @property @pulumi.getter(name='dashboardId') def dashboard_id(self) ->pulumi.Output[str]: """ The ID of the dashboard. """ return pulumi.get(self, 'dashboard_id') @property @pulumi.getter(name='dashboardName') def dashboard_name(self) ->pulumi.Output[str]: """ A friendly name for the dashboard. """ return pulumi.get(self, 'dashboard_name') @property @pulumi.getter(name='projectId') def project_id(self) ->pulumi.Output[Optional[str]]: """ The ID of the project in which to create the dashboard. """ return pulumi.get(self, 'project_id') @property @pulumi.getter def tags(self) ->pulumi.Output[Optional[Sequence['outputs.DashboardTag']]]: """ A list of key-value pairs that contain metadata for the dashboard. """ return pulumi.get(self, 'tags') <|reserved_special_token_1|> <|reserved_special_token_0|> @pulumi.input_type class DashboardArgs: def __init__(__self__, *, dashboard_definition: pulumi.Input[str], dashboard_description: pulumi.Input[str], dashboard_name: Optional[ pulumi.Input[str]]=None, project_id: Optional[pulumi.Input[str]]= None, tags: Optional[pulumi.Input[Sequence[pulumi.Input[ 'DashboardTagArgs']]]]=None): """ The set of arguments for constructing a Dashboard resource. :param pulumi.Input[str] dashboard_definition: The dashboard definition specified in a JSON literal. :param pulumi.Input[str] dashboard_description: A description for the dashboard. :param pulumi.Input[str] dashboard_name: A friendly name for the dashboard. :param pulumi.Input[str] project_id: The ID of the project in which to create the dashboard. :param pulumi.Input[Sequence[pulumi.Input['DashboardTagArgs']]] tags: A list of key-value pairs that contain metadata for the dashboard. """ pulumi.set(__self__, 'dashboard_definition', dashboard_definition) pulumi.set(__self__, 'dashboard_description', dashboard_description) if dashboard_name is not None: pulumi.set(__self__, 'dashboard_name', dashboard_name) if project_id is not None: pulumi.set(__self__, 'project_id', project_id) if tags is not None: pulumi.set(__self__, 'tags', tags) @property @pulumi.getter(name='dashboardDefinition') def dashboard_definition(self) ->pulumi.Input[str]: """ The dashboard definition specified in a JSON literal. """ return pulumi.get(self, 'dashboard_definition') @dashboard_definition.setter def dashboard_definition(self, value: pulumi.Input[str]): pulumi.set(self, 'dashboard_definition', value) <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> @dashboard_name.setter def dashboard_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, 'dashboard_name', value) @property @pulumi.getter(name='projectId') def project_id(self) ->Optional[pulumi.Input[str]]: """ The ID of the project in which to create the dashboard. """ return pulumi.get(self, 'project_id') @project_id.setter def project_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, 'project_id', value) @property @pulumi.getter def tags(self) ->Optional[pulumi.Input[Sequence[pulumi.Input[ 'DashboardTagArgs']]]]: """ A list of key-value pairs that contain metadata for the dashboard. """ return pulumi.get(self, 'tags') @tags.setter def tags(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[ 'DashboardTagArgs']]]]): pulumi.set(self, 'tags', value) class Dashboard(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi. ResourceOptions]=None, dashboard_definition: Optional[pulumi.Input[ str]]=None, dashboard_description: Optional[pulumi.Input[str]]=None, dashboard_name: Optional[pulumi.Input[str]]=None, project_id: Optional[pulumi.Input[str]]=None, tags: Optional[pulumi.Input[ Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]]]=None, __props__=None): """ Resource schema for AWS::IoTSiteWise::Dashboard :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] dashboard_definition: The dashboard definition specified in a JSON literal. :param pulumi.Input[str] dashboard_description: A description for the dashboard. :param pulumi.Input[str] dashboard_name: A friendly name for the dashboard. :param pulumi.Input[str] project_id: The ID of the project in which to create the dashboard. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]] tags: A list of key-value pairs that contain metadata for the dashboard. """ ... @overload def __init__(__self__, resource_name: str, args: DashboardArgs, opts: Optional[pulumi.ResourceOptions]=None): """ Resource schema for AWS::IoTSiteWise::Dashboard :param str resource_name: The name of the resource. :param DashboardArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(DashboardArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args. __dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi. ResourceOptions]=None, dashboard_definition: Optional[pulumi.Input[ str]]=None, dashboard_description: Optional[pulumi.Input[str]]=None, dashboard_name: Optional[pulumi.Input[str]]=None, project_id: Optional[pulumi.Input[str]]=None, tags: Optional[pulumi.Input[ Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]]]=None, __props__=None): opts = pulumi.ResourceOptions.merge(_utilities. get_resource_opts_defaults(), opts) if not isinstance(opts, pulumi.ResourceOptions): raise TypeError( 'Expected resource options to be a ResourceOptions instance') if opts.id is None: if __props__ is not None: raise TypeError( '__props__ is only valid when passed in combination with a valid opts.id to get an existing resource' ) __props__ = DashboardArgs.__new__(DashboardArgs) if dashboard_definition is None and not opts.urn: raise TypeError( "Missing required property 'dashboard_definition'") __props__.__dict__['dashboard_definition'] = dashboard_definition if dashboard_description is None and not opts.urn: raise TypeError( "Missing required property 'dashboard_description'") __props__.__dict__['dashboard_description'] = dashboard_description __props__.__dict__['dashboard_name'] = dashboard_name __props__.__dict__['project_id'] = project_id __props__.__dict__['tags'] = tags __props__.__dict__['dashboard_arn'] = None __props__.__dict__['dashboard_id'] = None super(Dashboard, __self__).__init__('aws-native:iotsitewise:Dashboard', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[ pulumi.ResourceOptions]=None) ->'Dashboard': """ Get an existing Dashboard resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id) ) __props__ = DashboardArgs.__new__(DashboardArgs) __props__.__dict__['dashboard_arn'] = None __props__.__dict__['dashboard_definition'] = None __props__.__dict__['dashboard_description'] = None __props__.__dict__['dashboard_id'] = None __props__.__dict__['dashboard_name'] = None __props__.__dict__['project_id'] = None __props__.__dict__['tags'] = None return Dashboard(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name='dashboardArn') def dashboard_arn(self) ->pulumi.Output[str]: """ The ARN of the dashboard. """ return pulumi.get(self, 'dashboard_arn') @property @pulumi.getter(name='dashboardDefinition') def dashboard_definition(self) ->pulumi.Output[str]: """ The dashboard definition specified in a JSON literal. """ return pulumi.get(self, 'dashboard_definition') @property @pulumi.getter(name='dashboardDescription') def dashboard_description(self) ->pulumi.Output[str]: """ A description for the dashboard. """ return pulumi.get(self, 'dashboard_description') @property @pulumi.getter(name='dashboardId') def dashboard_id(self) ->pulumi.Output[str]: """ The ID of the dashboard. """ return pulumi.get(self, 'dashboard_id') @property @pulumi.getter(name='dashboardName') def dashboard_name(self) ->pulumi.Output[str]: """ A friendly name for the dashboard. """ return pulumi.get(self, 'dashboard_name') @property @pulumi.getter(name='projectId') def project_id(self) ->pulumi.Output[Optional[str]]: """ The ID of the project in which to create the dashboard. """ return pulumi.get(self, 'project_id') @property @pulumi.getter def tags(self) ->pulumi.Output[Optional[Sequence['outputs.DashboardTag']]]: """ A list of key-value pairs that contain metadata for the dashboard. """ return pulumi.get(self, 'tags') <|reserved_special_token_1|> <|reserved_special_token_0|> @pulumi.input_type class DashboardArgs: def __init__(__self__, *, dashboard_definition: pulumi.Input[str], dashboard_description: pulumi.Input[str], dashboard_name: Optional[ pulumi.Input[str]]=None, project_id: Optional[pulumi.Input[str]]= None, tags: Optional[pulumi.Input[Sequence[pulumi.Input[ 'DashboardTagArgs']]]]=None): """ The set of arguments for constructing a Dashboard resource. :param pulumi.Input[str] dashboard_definition: The dashboard definition specified in a JSON literal. :param pulumi.Input[str] dashboard_description: A description for the dashboard. :param pulumi.Input[str] dashboard_name: A friendly name for the dashboard. :param pulumi.Input[str] project_id: The ID of the project in which to create the dashboard. :param pulumi.Input[Sequence[pulumi.Input['DashboardTagArgs']]] tags: A list of key-value pairs that contain metadata for the dashboard. """ pulumi.set(__self__, 'dashboard_definition', dashboard_definition) pulumi.set(__self__, 'dashboard_description', dashboard_description) if dashboard_name is not None: pulumi.set(__self__, 'dashboard_name', dashboard_name) if project_id is not None: pulumi.set(__self__, 'project_id', project_id) if tags is not None: pulumi.set(__self__, 'tags', tags) @property @pulumi.getter(name='dashboardDefinition') def dashboard_definition(self) ->pulumi.Input[str]: """ The dashboard definition specified in a JSON literal. """ return pulumi.get(self, 'dashboard_definition') @dashboard_definition.setter def dashboard_definition(self, value: pulumi.Input[str]): pulumi.set(self, 'dashboard_definition', value) <|reserved_special_token_0|> <|reserved_special_token_0|> @property @pulumi.getter(name='dashboardName') def dashboard_name(self) ->Optional[pulumi.Input[str]]: """ A friendly name for the dashboard. """ return pulumi.get(self, 'dashboard_name') @dashboard_name.setter def dashboard_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, 'dashboard_name', value) @property @pulumi.getter(name='projectId') def project_id(self) ->Optional[pulumi.Input[str]]: """ The ID of the project in which to create the dashboard. """ return pulumi.get(self, 'project_id') @project_id.setter def project_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, 'project_id', value) @property @pulumi.getter def tags(self) ->Optional[pulumi.Input[Sequence[pulumi.Input[ 'DashboardTagArgs']]]]: """ A list of key-value pairs that contain metadata for the dashboard. """ return pulumi.get(self, 'tags') @tags.setter def tags(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[ 'DashboardTagArgs']]]]): pulumi.set(self, 'tags', value) class Dashboard(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi. ResourceOptions]=None, dashboard_definition: Optional[pulumi.Input[ str]]=None, dashboard_description: Optional[pulumi.Input[str]]=None, dashboard_name: Optional[pulumi.Input[str]]=None, project_id: Optional[pulumi.Input[str]]=None, tags: Optional[pulumi.Input[ Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]]]=None, __props__=None): """ Resource schema for AWS::IoTSiteWise::Dashboard :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] dashboard_definition: The dashboard definition specified in a JSON literal. :param pulumi.Input[str] dashboard_description: A description for the dashboard. :param pulumi.Input[str] dashboard_name: A friendly name for the dashboard. :param pulumi.Input[str] project_id: The ID of the project in which to create the dashboard. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]] tags: A list of key-value pairs that contain metadata for the dashboard. """ ... @overload def __init__(__self__, resource_name: str, args: DashboardArgs, opts: Optional[pulumi.ResourceOptions]=None): """ Resource schema for AWS::IoTSiteWise::Dashboard :param str resource_name: The name of the resource. :param DashboardArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(DashboardArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args. __dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi. ResourceOptions]=None, dashboard_definition: Optional[pulumi.Input[ str]]=None, dashboard_description: Optional[pulumi.Input[str]]=None, dashboard_name: Optional[pulumi.Input[str]]=None, project_id: Optional[pulumi.Input[str]]=None, tags: Optional[pulumi.Input[ Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]]]=None, __props__=None): opts = pulumi.ResourceOptions.merge(_utilities. get_resource_opts_defaults(), opts) if not isinstance(opts, pulumi.ResourceOptions): raise TypeError( 'Expected resource options to be a ResourceOptions instance') if opts.id is None: if __props__ is not None: raise TypeError( '__props__ is only valid when passed in combination with a valid opts.id to get an existing resource' ) __props__ = DashboardArgs.__new__(DashboardArgs) if dashboard_definition is None and not opts.urn: raise TypeError( "Missing required property 'dashboard_definition'") __props__.__dict__['dashboard_definition'] = dashboard_definition if dashboard_description is None and not opts.urn: raise TypeError( "Missing required property 'dashboard_description'") __props__.__dict__['dashboard_description'] = dashboard_description __props__.__dict__['dashboard_name'] = dashboard_name __props__.__dict__['project_id'] = project_id __props__.__dict__['tags'] = tags __props__.__dict__['dashboard_arn'] = None __props__.__dict__['dashboard_id'] = None super(Dashboard, __self__).__init__('aws-native:iotsitewise:Dashboard', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[ pulumi.ResourceOptions]=None) ->'Dashboard': """ Get an existing Dashboard resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id) ) __props__ = DashboardArgs.__new__(DashboardArgs) __props__.__dict__['dashboard_arn'] = None __props__.__dict__['dashboard_definition'] = None __props__.__dict__['dashboard_description'] = None __props__.__dict__['dashboard_id'] = None __props__.__dict__['dashboard_name'] = None __props__.__dict__['project_id'] = None __props__.__dict__['tags'] = None return Dashboard(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name='dashboardArn') def dashboard_arn(self) ->pulumi.Output[str]: """ The ARN of the dashboard. """ return pulumi.get(self, 'dashboard_arn') @property @pulumi.getter(name='dashboardDefinition') def dashboard_definition(self) ->pulumi.Output[str]: """ The dashboard definition specified in a JSON literal. """ return pulumi.get(self, 'dashboard_definition') @property @pulumi.getter(name='dashboardDescription') def dashboard_description(self) ->pulumi.Output[str]: """ A description for the dashboard. """ return pulumi.get(self, 'dashboard_description') @property @pulumi.getter(name='dashboardId') def dashboard_id(self) ->pulumi.Output[str]: """ The ID of the dashboard. """ return pulumi.get(self, 'dashboard_id') @property @pulumi.getter(name='dashboardName') def dashboard_name(self) ->pulumi.Output[str]: """ A friendly name for the dashboard. """ return pulumi.get(self, 'dashboard_name') @property @pulumi.getter(name='projectId') def project_id(self) ->pulumi.Output[Optional[str]]: """ The ID of the project in which to create the dashboard. """ return pulumi.get(self, 'project_id') @property @pulumi.getter def tags(self) ->pulumi.Output[Optional[Sequence['outputs.DashboardTag']]]: """ A list of key-value pairs that contain metadata for the dashboard. """ return pulumi.get(self, 'tags') <|reserved_special_token_1|> # coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import copy import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._inputs import * __all__ = ['DashboardArgs', 'Dashboard'] @pulumi.input_type class DashboardArgs: def __init__(__self__, *, dashboard_definition: pulumi.Input[str], dashboard_description: pulumi.Input[str], dashboard_name: Optional[pulumi.Input[str]] = None, project_id: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Sequence[pulumi.Input['DashboardTagArgs']]]] = None): """ The set of arguments for constructing a Dashboard resource. :param pulumi.Input[str] dashboard_definition: The dashboard definition specified in a JSON literal. :param pulumi.Input[str] dashboard_description: A description for the dashboard. :param pulumi.Input[str] dashboard_name: A friendly name for the dashboard. :param pulumi.Input[str] project_id: The ID of the project in which to create the dashboard. :param pulumi.Input[Sequence[pulumi.Input['DashboardTagArgs']]] tags: A list of key-value pairs that contain metadata for the dashboard. """ pulumi.set(__self__, "dashboard_definition", dashboard_definition) pulumi.set(__self__, "dashboard_description", dashboard_description) if dashboard_name is not None: pulumi.set(__self__, "dashboard_name", dashboard_name) if project_id is not None: pulumi.set(__self__, "project_id", project_id) if tags is not None: pulumi.set(__self__, "tags", tags) @property @pulumi.getter(name="dashboardDefinition") def dashboard_definition(self) -> pulumi.Input[str]: """ The dashboard definition specified in a JSON literal. """ return pulumi.get(self, "dashboard_definition") @dashboard_definition.setter def dashboard_definition(self, value: pulumi.Input[str]): pulumi.set(self, "dashboard_definition", value) @property @pulumi.getter(name="dashboardDescription") def dashboard_description(self) -> pulumi.Input[str]: """ A description for the dashboard. """ return pulumi.get(self, "dashboard_description") @dashboard_description.setter def dashboard_description(self, value: pulumi.Input[str]): pulumi.set(self, "dashboard_description", value) @property @pulumi.getter(name="dashboardName") def dashboard_name(self) -> Optional[pulumi.Input[str]]: """ A friendly name for the dashboard. """ return pulumi.get(self, "dashboard_name") @dashboard_name.setter def dashboard_name(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "dashboard_name", value) @property @pulumi.getter(name="projectId") def project_id(self) -> Optional[pulumi.Input[str]]: """ The ID of the project in which to create the dashboard. """ return pulumi.get(self, "project_id") @project_id.setter def project_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "project_id", value) @property @pulumi.getter def tags(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['DashboardTagArgs']]]]: """ A list of key-value pairs that contain metadata for the dashboard. """ return pulumi.get(self, "tags") @tags.setter def tags(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['DashboardTagArgs']]]]): pulumi.set(self, "tags", value) class Dashboard(pulumi.CustomResource): @overload def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, dashboard_definition: Optional[pulumi.Input[str]] = None, dashboard_description: Optional[pulumi.Input[str]] = None, dashboard_name: Optional[pulumi.Input[str]] = None, project_id: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]]] = None, __props__=None): """ Resource schema for AWS::IoTSiteWise::Dashboard :param str resource_name: The name of the resource. :param pulumi.ResourceOptions opts: Options for the resource. :param pulumi.Input[str] dashboard_definition: The dashboard definition specified in a JSON literal. :param pulumi.Input[str] dashboard_description: A description for the dashboard. :param pulumi.Input[str] dashboard_name: A friendly name for the dashboard. :param pulumi.Input[str] project_id: The ID of the project in which to create the dashboard. :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]] tags: A list of key-value pairs that contain metadata for the dashboard. """ ... @overload def __init__(__self__, resource_name: str, args: DashboardArgs, opts: Optional[pulumi.ResourceOptions] = None): """ Resource schema for AWS::IoTSiteWise::Dashboard :param str resource_name: The name of the resource. :param DashboardArgs args: The arguments to use to populate this resource's properties. :param pulumi.ResourceOptions opts: Options for the resource. """ ... def __init__(__self__, resource_name: str, *args, **kwargs): resource_args, opts = _utilities.get_resource_args_opts(DashboardArgs, pulumi.ResourceOptions, *args, **kwargs) if resource_args is not None: __self__._internal_init(resource_name, opts, **resource_args.__dict__) else: __self__._internal_init(resource_name, *args, **kwargs) def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, dashboard_definition: Optional[pulumi.Input[str]] = None, dashboard_description: Optional[pulumi.Input[str]] = None, dashboard_name: Optional[pulumi.Input[str]] = None, project_id: Optional[pulumi.Input[str]] = None, tags: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]]] = None, __props__=None): opts = pulumi.ResourceOptions.merge(_utilities.get_resource_opts_defaults(), opts) if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = DashboardArgs.__new__(DashboardArgs) if dashboard_definition is None and not opts.urn: raise TypeError("Missing required property 'dashboard_definition'") __props__.__dict__["dashboard_definition"] = dashboard_definition if dashboard_description is None and not opts.urn: raise TypeError("Missing required property 'dashboard_description'") __props__.__dict__["dashboard_description"] = dashboard_description __props__.__dict__["dashboard_name"] = dashboard_name __props__.__dict__["project_id"] = project_id __props__.__dict__["tags"] = tags __props__.__dict__["dashboard_arn"] = None __props__.__dict__["dashboard_id"] = None super(Dashboard, __self__).__init__( 'aws-native:iotsitewise:Dashboard', resource_name, __props__, opts) @staticmethod def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'Dashboard': """ Get an existing Dashboard resource's state with the given name, id, and optional extra properties used to qualify the lookup. :param str resource_name: The unique name of the resulting resource. :param pulumi.Input[str] id: The unique provider ID of the resource to lookup. :param pulumi.ResourceOptions opts: Options for the resource. """ opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = DashboardArgs.__new__(DashboardArgs) __props__.__dict__["dashboard_arn"] = None __props__.__dict__["dashboard_definition"] = None __props__.__dict__["dashboard_description"] = None __props__.__dict__["dashboard_id"] = None __props__.__dict__["dashboard_name"] = None __props__.__dict__["project_id"] = None __props__.__dict__["tags"] = None return Dashboard(resource_name, opts=opts, __props__=__props__) @property @pulumi.getter(name="dashboardArn") def dashboard_arn(self) -> pulumi.Output[str]: """ The ARN of the dashboard. """ return pulumi.get(self, "dashboard_arn") @property @pulumi.getter(name="dashboardDefinition") def dashboard_definition(self) -> pulumi.Output[str]: """ The dashboard definition specified in a JSON literal. """ return pulumi.get(self, "dashboard_definition") @property @pulumi.getter(name="dashboardDescription") def dashboard_description(self) -> pulumi.Output[str]: """ A description for the dashboard. """ return pulumi.get(self, "dashboard_description") @property @pulumi.getter(name="dashboardId") def dashboard_id(self) -> pulumi.Output[str]: """ The ID of the dashboard. """ return pulumi.get(self, "dashboard_id") @property @pulumi.getter(name="dashboardName") def dashboard_name(self) -> pulumi.Output[str]: """ A friendly name for the dashboard. """ return pulumi.get(self, "dashboard_name") @property @pulumi.getter(name="projectId") def project_id(self) -> pulumi.Output[Optional[str]]: """ The ID of the project in which to create the dashboard. """ return pulumi.get(self, "project_id") @property @pulumi.getter def tags(self) -> pulumi.Output[Optional[Sequence['outputs.DashboardTag']]]: """ A list of key-value pairs that contain metadata for the dashboard. """ return pulumi.get(self, "tags")
flexible
{ "blob_id": "2332783c96b24caa383bf47d82384e1c40a48e94", "index": 8566, "step-1": "<mask token>\n\n\n@pulumi.input_type\nclass DashboardArgs:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Dashboard(pulumi.CustomResource):\n\n @overload\n def __init__(__self__, resource_name: str, opts: Optional[pulumi.\n ResourceOptions]=None, dashboard_definition: Optional[pulumi.Input[\n str]]=None, dashboard_description: Optional[pulumi.Input[str]]=None,\n dashboard_name: Optional[pulumi.Input[str]]=None, project_id:\n Optional[pulumi.Input[str]]=None, tags: Optional[pulumi.Input[\n Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]]]=None,\n __props__=None):\n \"\"\"\n Resource schema for AWS::IoTSiteWise::Dashboard\n\n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] dashboard_definition: The dashboard definition specified in a JSON literal.\n :param pulumi.Input[str] dashboard_description: A description for the dashboard.\n :param pulumi.Input[str] dashboard_name: A friendly name for the dashboard.\n :param pulumi.Input[str] project_id: The ID of the project in which to create the dashboard.\n :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]] tags: A list of key-value pairs that contain metadata for the dashboard.\n \"\"\"\n ...\n\n @overload\n def __init__(__self__, resource_name: str, args: DashboardArgs, opts:\n Optional[pulumi.ResourceOptions]=None):\n \"\"\"\n Resource schema for AWS::IoTSiteWise::Dashboard\n\n :param str resource_name: The name of the resource.\n :param DashboardArgs args: The arguments to use to populate this resource's properties.\n :param pulumi.ResourceOptions opts: Options for the resource.\n \"\"\"\n ...\n\n def __init__(__self__, resource_name: str, *args, **kwargs):\n resource_args, opts = _utilities.get_resource_args_opts(DashboardArgs,\n pulumi.ResourceOptions, *args, **kwargs)\n if resource_args is not None:\n __self__._internal_init(resource_name, opts, **resource_args.\n __dict__)\n else:\n __self__._internal_init(resource_name, *args, **kwargs)\n\n def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.\n ResourceOptions]=None, dashboard_definition: Optional[pulumi.Input[\n str]]=None, dashboard_description: Optional[pulumi.Input[str]]=None,\n dashboard_name: Optional[pulumi.Input[str]]=None, project_id:\n Optional[pulumi.Input[str]]=None, tags: Optional[pulumi.Input[\n Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]]]=None,\n __props__=None):\n opts = pulumi.ResourceOptions.merge(_utilities.\n get_resource_opts_defaults(), opts)\n if not isinstance(opts, pulumi.ResourceOptions):\n raise TypeError(\n 'Expected resource options to be a ResourceOptions instance')\n if opts.id is None:\n if __props__ is not None:\n raise TypeError(\n '__props__ is only valid when passed in combination with a valid opts.id to get an existing resource'\n )\n __props__ = DashboardArgs.__new__(DashboardArgs)\n if dashboard_definition is None and not opts.urn:\n raise TypeError(\n \"Missing required property 'dashboard_definition'\")\n __props__.__dict__['dashboard_definition'] = dashboard_definition\n if dashboard_description is None and not opts.urn:\n raise TypeError(\n \"Missing required property 'dashboard_description'\")\n __props__.__dict__['dashboard_description'] = dashboard_description\n __props__.__dict__['dashboard_name'] = dashboard_name\n __props__.__dict__['project_id'] = project_id\n __props__.__dict__['tags'] = tags\n __props__.__dict__['dashboard_arn'] = None\n __props__.__dict__['dashboard_id'] = None\n super(Dashboard, __self__).__init__('aws-native:iotsitewise:Dashboard',\n resource_name, __props__, opts)\n\n @staticmethod\n def get(resource_name: str, id: pulumi.Input[str], opts: Optional[\n pulumi.ResourceOptions]=None) ->'Dashboard':\n \"\"\"\n Get an existing Dashboard resource's state with the given name, id, and optional extra\n properties used to qualify the lookup.\n\n :param str resource_name: The unique name of the resulting resource.\n :param pulumi.Input[str] id: The unique provider ID of the resource to lookup.\n :param pulumi.ResourceOptions opts: Options for the resource.\n \"\"\"\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)\n )\n __props__ = DashboardArgs.__new__(DashboardArgs)\n __props__.__dict__['dashboard_arn'] = None\n __props__.__dict__['dashboard_definition'] = None\n __props__.__dict__['dashboard_description'] = None\n __props__.__dict__['dashboard_id'] = None\n __props__.__dict__['dashboard_name'] = None\n __props__.__dict__['project_id'] = None\n __props__.__dict__['tags'] = None\n return Dashboard(resource_name, opts=opts, __props__=__props__)\n\n @property\n @pulumi.getter(name='dashboardArn')\n def dashboard_arn(self) ->pulumi.Output[str]:\n \"\"\"\n The ARN of the dashboard.\n \"\"\"\n return pulumi.get(self, 'dashboard_arn')\n\n @property\n @pulumi.getter(name='dashboardDefinition')\n def dashboard_definition(self) ->pulumi.Output[str]:\n \"\"\"\n The dashboard definition specified in a JSON literal.\n \"\"\"\n return pulumi.get(self, 'dashboard_definition')\n\n @property\n @pulumi.getter(name='dashboardDescription')\n def dashboard_description(self) ->pulumi.Output[str]:\n \"\"\"\n A description for the dashboard.\n \"\"\"\n return pulumi.get(self, 'dashboard_description')\n\n @property\n @pulumi.getter(name='dashboardId')\n def dashboard_id(self) ->pulumi.Output[str]:\n \"\"\"\n The ID of the dashboard.\n \"\"\"\n return pulumi.get(self, 'dashboard_id')\n\n @property\n @pulumi.getter(name='dashboardName')\n def dashboard_name(self) ->pulumi.Output[str]:\n \"\"\"\n A friendly name for the dashboard.\n \"\"\"\n return pulumi.get(self, 'dashboard_name')\n\n @property\n @pulumi.getter(name='projectId')\n def project_id(self) ->pulumi.Output[Optional[str]]:\n \"\"\"\n The ID of the project in which to create the dashboard.\n \"\"\"\n return pulumi.get(self, 'project_id')\n\n @property\n @pulumi.getter\n def tags(self) ->pulumi.Output[Optional[Sequence['outputs.DashboardTag']]]:\n \"\"\"\n A list of key-value pairs that contain metadata for the dashboard.\n \"\"\"\n return pulumi.get(self, 'tags')\n", "step-2": "<mask token>\n\n\n@pulumi.input_type\nclass DashboardArgs:\n\n def __init__(__self__, *, dashboard_definition: pulumi.Input[str],\n dashboard_description: pulumi.Input[str], dashboard_name: Optional[\n pulumi.Input[str]]=None, project_id: Optional[pulumi.Input[str]]=\n None, tags: Optional[pulumi.Input[Sequence[pulumi.Input[\n 'DashboardTagArgs']]]]=None):\n \"\"\"\n The set of arguments for constructing a Dashboard resource.\n :param pulumi.Input[str] dashboard_definition: The dashboard definition specified in a JSON literal.\n :param pulumi.Input[str] dashboard_description: A description for the dashboard.\n :param pulumi.Input[str] dashboard_name: A friendly name for the dashboard.\n :param pulumi.Input[str] project_id: The ID of the project in which to create the dashboard.\n :param pulumi.Input[Sequence[pulumi.Input['DashboardTagArgs']]] tags: A list of key-value pairs that contain metadata for the dashboard.\n \"\"\"\n pulumi.set(__self__, 'dashboard_definition', dashboard_definition)\n pulumi.set(__self__, 'dashboard_description', dashboard_description)\n if dashboard_name is not None:\n pulumi.set(__self__, 'dashboard_name', dashboard_name)\n if project_id is not None:\n pulumi.set(__self__, 'project_id', project_id)\n if tags is not None:\n pulumi.set(__self__, 'tags', tags)\n\n @property\n @pulumi.getter(name='dashboardDefinition')\n def dashboard_definition(self) ->pulumi.Input[str]:\n \"\"\"\n The dashboard definition specified in a JSON literal.\n \"\"\"\n return pulumi.get(self, 'dashboard_definition')\n\n @dashboard_definition.setter\n def dashboard_definition(self, value: pulumi.Input[str]):\n pulumi.set(self, 'dashboard_definition', value)\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n @property\n @pulumi.getter(name='projectId')\n def project_id(self) ->Optional[pulumi.Input[str]]:\n \"\"\"\n The ID of the project in which to create the dashboard.\n \"\"\"\n return pulumi.get(self, 'project_id')\n\n @project_id.setter\n def project_id(self, value: Optional[pulumi.Input[str]]):\n pulumi.set(self, 'project_id', value)\n\n @property\n @pulumi.getter\n def tags(self) ->Optional[pulumi.Input[Sequence[pulumi.Input[\n 'DashboardTagArgs']]]]:\n \"\"\"\n A list of key-value pairs that contain metadata for the dashboard.\n \"\"\"\n return pulumi.get(self, 'tags')\n\n @tags.setter\n def tags(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[\n 'DashboardTagArgs']]]]):\n pulumi.set(self, 'tags', value)\n\n\nclass Dashboard(pulumi.CustomResource):\n\n @overload\n def __init__(__self__, resource_name: str, opts: Optional[pulumi.\n ResourceOptions]=None, dashboard_definition: Optional[pulumi.Input[\n str]]=None, dashboard_description: Optional[pulumi.Input[str]]=None,\n dashboard_name: Optional[pulumi.Input[str]]=None, project_id:\n Optional[pulumi.Input[str]]=None, tags: Optional[pulumi.Input[\n Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]]]=None,\n __props__=None):\n \"\"\"\n Resource schema for AWS::IoTSiteWise::Dashboard\n\n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] dashboard_definition: The dashboard definition specified in a JSON literal.\n :param pulumi.Input[str] dashboard_description: A description for the dashboard.\n :param pulumi.Input[str] dashboard_name: A friendly name for the dashboard.\n :param pulumi.Input[str] project_id: The ID of the project in which to create the dashboard.\n :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]] tags: A list of key-value pairs that contain metadata for the dashboard.\n \"\"\"\n ...\n\n @overload\n def __init__(__self__, resource_name: str, args: DashboardArgs, opts:\n Optional[pulumi.ResourceOptions]=None):\n \"\"\"\n Resource schema for AWS::IoTSiteWise::Dashboard\n\n :param str resource_name: The name of the resource.\n :param DashboardArgs args: The arguments to use to populate this resource's properties.\n :param pulumi.ResourceOptions opts: Options for the resource.\n \"\"\"\n ...\n\n def __init__(__self__, resource_name: str, *args, **kwargs):\n resource_args, opts = _utilities.get_resource_args_opts(DashboardArgs,\n pulumi.ResourceOptions, *args, **kwargs)\n if resource_args is not None:\n __self__._internal_init(resource_name, opts, **resource_args.\n __dict__)\n else:\n __self__._internal_init(resource_name, *args, **kwargs)\n\n def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.\n ResourceOptions]=None, dashboard_definition: Optional[pulumi.Input[\n str]]=None, dashboard_description: Optional[pulumi.Input[str]]=None,\n dashboard_name: Optional[pulumi.Input[str]]=None, project_id:\n Optional[pulumi.Input[str]]=None, tags: Optional[pulumi.Input[\n Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]]]=None,\n __props__=None):\n opts = pulumi.ResourceOptions.merge(_utilities.\n get_resource_opts_defaults(), opts)\n if not isinstance(opts, pulumi.ResourceOptions):\n raise TypeError(\n 'Expected resource options to be a ResourceOptions instance')\n if opts.id is None:\n if __props__ is not None:\n raise TypeError(\n '__props__ is only valid when passed in combination with a valid opts.id to get an existing resource'\n )\n __props__ = DashboardArgs.__new__(DashboardArgs)\n if dashboard_definition is None and not opts.urn:\n raise TypeError(\n \"Missing required property 'dashboard_definition'\")\n __props__.__dict__['dashboard_definition'] = dashboard_definition\n if dashboard_description is None and not opts.urn:\n raise TypeError(\n \"Missing required property 'dashboard_description'\")\n __props__.__dict__['dashboard_description'] = dashboard_description\n __props__.__dict__['dashboard_name'] = dashboard_name\n __props__.__dict__['project_id'] = project_id\n __props__.__dict__['tags'] = tags\n __props__.__dict__['dashboard_arn'] = None\n __props__.__dict__['dashboard_id'] = None\n super(Dashboard, __self__).__init__('aws-native:iotsitewise:Dashboard',\n resource_name, __props__, opts)\n\n @staticmethod\n def get(resource_name: str, id: pulumi.Input[str], opts: Optional[\n pulumi.ResourceOptions]=None) ->'Dashboard':\n \"\"\"\n Get an existing Dashboard resource's state with the given name, id, and optional extra\n properties used to qualify the lookup.\n\n :param str resource_name: The unique name of the resulting resource.\n :param pulumi.Input[str] id: The unique provider ID of the resource to lookup.\n :param pulumi.ResourceOptions opts: Options for the resource.\n \"\"\"\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)\n )\n __props__ = DashboardArgs.__new__(DashboardArgs)\n __props__.__dict__['dashboard_arn'] = None\n __props__.__dict__['dashboard_definition'] = None\n __props__.__dict__['dashboard_description'] = None\n __props__.__dict__['dashboard_id'] = None\n __props__.__dict__['dashboard_name'] = None\n __props__.__dict__['project_id'] = None\n __props__.__dict__['tags'] = None\n return Dashboard(resource_name, opts=opts, __props__=__props__)\n\n @property\n @pulumi.getter(name='dashboardArn')\n def dashboard_arn(self) ->pulumi.Output[str]:\n \"\"\"\n The ARN of the dashboard.\n \"\"\"\n return pulumi.get(self, 'dashboard_arn')\n\n @property\n @pulumi.getter(name='dashboardDefinition')\n def dashboard_definition(self) ->pulumi.Output[str]:\n \"\"\"\n The dashboard definition specified in a JSON literal.\n \"\"\"\n return pulumi.get(self, 'dashboard_definition')\n\n @property\n @pulumi.getter(name='dashboardDescription')\n def dashboard_description(self) ->pulumi.Output[str]:\n \"\"\"\n A description for the dashboard.\n \"\"\"\n return pulumi.get(self, 'dashboard_description')\n\n @property\n @pulumi.getter(name='dashboardId')\n def dashboard_id(self) ->pulumi.Output[str]:\n \"\"\"\n The ID of the dashboard.\n \"\"\"\n return pulumi.get(self, 'dashboard_id')\n\n @property\n @pulumi.getter(name='dashboardName')\n def dashboard_name(self) ->pulumi.Output[str]:\n \"\"\"\n A friendly name for the dashboard.\n \"\"\"\n return pulumi.get(self, 'dashboard_name')\n\n @property\n @pulumi.getter(name='projectId')\n def project_id(self) ->pulumi.Output[Optional[str]]:\n \"\"\"\n The ID of the project in which to create the dashboard.\n \"\"\"\n return pulumi.get(self, 'project_id')\n\n @property\n @pulumi.getter\n def tags(self) ->pulumi.Output[Optional[Sequence['outputs.DashboardTag']]]:\n \"\"\"\n A list of key-value pairs that contain metadata for the dashboard.\n \"\"\"\n return pulumi.get(self, 'tags')\n", "step-3": "<mask token>\n\n\n@pulumi.input_type\nclass DashboardArgs:\n\n def __init__(__self__, *, dashboard_definition: pulumi.Input[str],\n dashboard_description: pulumi.Input[str], dashboard_name: Optional[\n pulumi.Input[str]]=None, project_id: Optional[pulumi.Input[str]]=\n None, tags: Optional[pulumi.Input[Sequence[pulumi.Input[\n 'DashboardTagArgs']]]]=None):\n \"\"\"\n The set of arguments for constructing a Dashboard resource.\n :param pulumi.Input[str] dashboard_definition: The dashboard definition specified in a JSON literal.\n :param pulumi.Input[str] dashboard_description: A description for the dashboard.\n :param pulumi.Input[str] dashboard_name: A friendly name for the dashboard.\n :param pulumi.Input[str] project_id: The ID of the project in which to create the dashboard.\n :param pulumi.Input[Sequence[pulumi.Input['DashboardTagArgs']]] tags: A list of key-value pairs that contain metadata for the dashboard.\n \"\"\"\n pulumi.set(__self__, 'dashboard_definition', dashboard_definition)\n pulumi.set(__self__, 'dashboard_description', dashboard_description)\n if dashboard_name is not None:\n pulumi.set(__self__, 'dashboard_name', dashboard_name)\n if project_id is not None:\n pulumi.set(__self__, 'project_id', project_id)\n if tags is not None:\n pulumi.set(__self__, 'tags', tags)\n\n @property\n @pulumi.getter(name='dashboardDefinition')\n def dashboard_definition(self) ->pulumi.Input[str]:\n \"\"\"\n The dashboard definition specified in a JSON literal.\n \"\"\"\n return pulumi.get(self, 'dashboard_definition')\n\n @dashboard_definition.setter\n def dashboard_definition(self, value: pulumi.Input[str]):\n pulumi.set(self, 'dashboard_definition', value)\n <mask token>\n <mask token>\n <mask token>\n\n @dashboard_name.setter\n def dashboard_name(self, value: Optional[pulumi.Input[str]]):\n pulumi.set(self, 'dashboard_name', value)\n\n @property\n @pulumi.getter(name='projectId')\n def project_id(self) ->Optional[pulumi.Input[str]]:\n \"\"\"\n The ID of the project in which to create the dashboard.\n \"\"\"\n return pulumi.get(self, 'project_id')\n\n @project_id.setter\n def project_id(self, value: Optional[pulumi.Input[str]]):\n pulumi.set(self, 'project_id', value)\n\n @property\n @pulumi.getter\n def tags(self) ->Optional[pulumi.Input[Sequence[pulumi.Input[\n 'DashboardTagArgs']]]]:\n \"\"\"\n A list of key-value pairs that contain metadata for the dashboard.\n \"\"\"\n return pulumi.get(self, 'tags')\n\n @tags.setter\n def tags(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[\n 'DashboardTagArgs']]]]):\n pulumi.set(self, 'tags', value)\n\n\nclass Dashboard(pulumi.CustomResource):\n\n @overload\n def __init__(__self__, resource_name: str, opts: Optional[pulumi.\n ResourceOptions]=None, dashboard_definition: Optional[pulumi.Input[\n str]]=None, dashboard_description: Optional[pulumi.Input[str]]=None,\n dashboard_name: Optional[pulumi.Input[str]]=None, project_id:\n Optional[pulumi.Input[str]]=None, tags: Optional[pulumi.Input[\n Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]]]=None,\n __props__=None):\n \"\"\"\n Resource schema for AWS::IoTSiteWise::Dashboard\n\n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] dashboard_definition: The dashboard definition specified in a JSON literal.\n :param pulumi.Input[str] dashboard_description: A description for the dashboard.\n :param pulumi.Input[str] dashboard_name: A friendly name for the dashboard.\n :param pulumi.Input[str] project_id: The ID of the project in which to create the dashboard.\n :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]] tags: A list of key-value pairs that contain metadata for the dashboard.\n \"\"\"\n ...\n\n @overload\n def __init__(__self__, resource_name: str, args: DashboardArgs, opts:\n Optional[pulumi.ResourceOptions]=None):\n \"\"\"\n Resource schema for AWS::IoTSiteWise::Dashboard\n\n :param str resource_name: The name of the resource.\n :param DashboardArgs args: The arguments to use to populate this resource's properties.\n :param pulumi.ResourceOptions opts: Options for the resource.\n \"\"\"\n ...\n\n def __init__(__self__, resource_name: str, *args, **kwargs):\n resource_args, opts = _utilities.get_resource_args_opts(DashboardArgs,\n pulumi.ResourceOptions, *args, **kwargs)\n if resource_args is not None:\n __self__._internal_init(resource_name, opts, **resource_args.\n __dict__)\n else:\n __self__._internal_init(resource_name, *args, **kwargs)\n\n def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.\n ResourceOptions]=None, dashboard_definition: Optional[pulumi.Input[\n str]]=None, dashboard_description: Optional[pulumi.Input[str]]=None,\n dashboard_name: Optional[pulumi.Input[str]]=None, project_id:\n Optional[pulumi.Input[str]]=None, tags: Optional[pulumi.Input[\n Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]]]=None,\n __props__=None):\n opts = pulumi.ResourceOptions.merge(_utilities.\n get_resource_opts_defaults(), opts)\n if not isinstance(opts, pulumi.ResourceOptions):\n raise TypeError(\n 'Expected resource options to be a ResourceOptions instance')\n if opts.id is None:\n if __props__ is not None:\n raise TypeError(\n '__props__ is only valid when passed in combination with a valid opts.id to get an existing resource'\n )\n __props__ = DashboardArgs.__new__(DashboardArgs)\n if dashboard_definition is None and not opts.urn:\n raise TypeError(\n \"Missing required property 'dashboard_definition'\")\n __props__.__dict__['dashboard_definition'] = dashboard_definition\n if dashboard_description is None and not opts.urn:\n raise TypeError(\n \"Missing required property 'dashboard_description'\")\n __props__.__dict__['dashboard_description'] = dashboard_description\n __props__.__dict__['dashboard_name'] = dashboard_name\n __props__.__dict__['project_id'] = project_id\n __props__.__dict__['tags'] = tags\n __props__.__dict__['dashboard_arn'] = None\n __props__.__dict__['dashboard_id'] = None\n super(Dashboard, __self__).__init__('aws-native:iotsitewise:Dashboard',\n resource_name, __props__, opts)\n\n @staticmethod\n def get(resource_name: str, id: pulumi.Input[str], opts: Optional[\n pulumi.ResourceOptions]=None) ->'Dashboard':\n \"\"\"\n Get an existing Dashboard resource's state with the given name, id, and optional extra\n properties used to qualify the lookup.\n\n :param str resource_name: The unique name of the resulting resource.\n :param pulumi.Input[str] id: The unique provider ID of the resource to lookup.\n :param pulumi.ResourceOptions opts: Options for the resource.\n \"\"\"\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)\n )\n __props__ = DashboardArgs.__new__(DashboardArgs)\n __props__.__dict__['dashboard_arn'] = None\n __props__.__dict__['dashboard_definition'] = None\n __props__.__dict__['dashboard_description'] = None\n __props__.__dict__['dashboard_id'] = None\n __props__.__dict__['dashboard_name'] = None\n __props__.__dict__['project_id'] = None\n __props__.__dict__['tags'] = None\n return Dashboard(resource_name, opts=opts, __props__=__props__)\n\n @property\n @pulumi.getter(name='dashboardArn')\n def dashboard_arn(self) ->pulumi.Output[str]:\n \"\"\"\n The ARN of the dashboard.\n \"\"\"\n return pulumi.get(self, 'dashboard_arn')\n\n @property\n @pulumi.getter(name='dashboardDefinition')\n def dashboard_definition(self) ->pulumi.Output[str]:\n \"\"\"\n The dashboard definition specified in a JSON literal.\n \"\"\"\n return pulumi.get(self, 'dashboard_definition')\n\n @property\n @pulumi.getter(name='dashboardDescription')\n def dashboard_description(self) ->pulumi.Output[str]:\n \"\"\"\n A description for the dashboard.\n \"\"\"\n return pulumi.get(self, 'dashboard_description')\n\n @property\n @pulumi.getter(name='dashboardId')\n def dashboard_id(self) ->pulumi.Output[str]:\n \"\"\"\n The ID of the dashboard.\n \"\"\"\n return pulumi.get(self, 'dashboard_id')\n\n @property\n @pulumi.getter(name='dashboardName')\n def dashboard_name(self) ->pulumi.Output[str]:\n \"\"\"\n A friendly name for the dashboard.\n \"\"\"\n return pulumi.get(self, 'dashboard_name')\n\n @property\n @pulumi.getter(name='projectId')\n def project_id(self) ->pulumi.Output[Optional[str]]:\n \"\"\"\n The ID of the project in which to create the dashboard.\n \"\"\"\n return pulumi.get(self, 'project_id')\n\n @property\n @pulumi.getter\n def tags(self) ->pulumi.Output[Optional[Sequence['outputs.DashboardTag']]]:\n \"\"\"\n A list of key-value pairs that contain metadata for the dashboard.\n \"\"\"\n return pulumi.get(self, 'tags')\n", "step-4": "<mask token>\n\n\n@pulumi.input_type\nclass DashboardArgs:\n\n def __init__(__self__, *, dashboard_definition: pulumi.Input[str],\n dashboard_description: pulumi.Input[str], dashboard_name: Optional[\n pulumi.Input[str]]=None, project_id: Optional[pulumi.Input[str]]=\n None, tags: Optional[pulumi.Input[Sequence[pulumi.Input[\n 'DashboardTagArgs']]]]=None):\n \"\"\"\n The set of arguments for constructing a Dashboard resource.\n :param pulumi.Input[str] dashboard_definition: The dashboard definition specified in a JSON literal.\n :param pulumi.Input[str] dashboard_description: A description for the dashboard.\n :param pulumi.Input[str] dashboard_name: A friendly name for the dashboard.\n :param pulumi.Input[str] project_id: The ID of the project in which to create the dashboard.\n :param pulumi.Input[Sequence[pulumi.Input['DashboardTagArgs']]] tags: A list of key-value pairs that contain metadata for the dashboard.\n \"\"\"\n pulumi.set(__self__, 'dashboard_definition', dashboard_definition)\n pulumi.set(__self__, 'dashboard_description', dashboard_description)\n if dashboard_name is not None:\n pulumi.set(__self__, 'dashboard_name', dashboard_name)\n if project_id is not None:\n pulumi.set(__self__, 'project_id', project_id)\n if tags is not None:\n pulumi.set(__self__, 'tags', tags)\n\n @property\n @pulumi.getter(name='dashboardDefinition')\n def dashboard_definition(self) ->pulumi.Input[str]:\n \"\"\"\n The dashboard definition specified in a JSON literal.\n \"\"\"\n return pulumi.get(self, 'dashboard_definition')\n\n @dashboard_definition.setter\n def dashboard_definition(self, value: pulumi.Input[str]):\n pulumi.set(self, 'dashboard_definition', value)\n <mask token>\n <mask token>\n\n @property\n @pulumi.getter(name='dashboardName')\n def dashboard_name(self) ->Optional[pulumi.Input[str]]:\n \"\"\"\n A friendly name for the dashboard.\n \"\"\"\n return pulumi.get(self, 'dashboard_name')\n\n @dashboard_name.setter\n def dashboard_name(self, value: Optional[pulumi.Input[str]]):\n pulumi.set(self, 'dashboard_name', value)\n\n @property\n @pulumi.getter(name='projectId')\n def project_id(self) ->Optional[pulumi.Input[str]]:\n \"\"\"\n The ID of the project in which to create the dashboard.\n \"\"\"\n return pulumi.get(self, 'project_id')\n\n @project_id.setter\n def project_id(self, value: Optional[pulumi.Input[str]]):\n pulumi.set(self, 'project_id', value)\n\n @property\n @pulumi.getter\n def tags(self) ->Optional[pulumi.Input[Sequence[pulumi.Input[\n 'DashboardTagArgs']]]]:\n \"\"\"\n A list of key-value pairs that contain metadata for the dashboard.\n \"\"\"\n return pulumi.get(self, 'tags')\n\n @tags.setter\n def tags(self, value: Optional[pulumi.Input[Sequence[pulumi.Input[\n 'DashboardTagArgs']]]]):\n pulumi.set(self, 'tags', value)\n\n\nclass Dashboard(pulumi.CustomResource):\n\n @overload\n def __init__(__self__, resource_name: str, opts: Optional[pulumi.\n ResourceOptions]=None, dashboard_definition: Optional[pulumi.Input[\n str]]=None, dashboard_description: Optional[pulumi.Input[str]]=None,\n dashboard_name: Optional[pulumi.Input[str]]=None, project_id:\n Optional[pulumi.Input[str]]=None, tags: Optional[pulumi.Input[\n Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]]]=None,\n __props__=None):\n \"\"\"\n Resource schema for AWS::IoTSiteWise::Dashboard\n\n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] dashboard_definition: The dashboard definition specified in a JSON literal.\n :param pulumi.Input[str] dashboard_description: A description for the dashboard.\n :param pulumi.Input[str] dashboard_name: A friendly name for the dashboard.\n :param pulumi.Input[str] project_id: The ID of the project in which to create the dashboard.\n :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]] tags: A list of key-value pairs that contain metadata for the dashboard.\n \"\"\"\n ...\n\n @overload\n def __init__(__self__, resource_name: str, args: DashboardArgs, opts:\n Optional[pulumi.ResourceOptions]=None):\n \"\"\"\n Resource schema for AWS::IoTSiteWise::Dashboard\n\n :param str resource_name: The name of the resource.\n :param DashboardArgs args: The arguments to use to populate this resource's properties.\n :param pulumi.ResourceOptions opts: Options for the resource.\n \"\"\"\n ...\n\n def __init__(__self__, resource_name: str, *args, **kwargs):\n resource_args, opts = _utilities.get_resource_args_opts(DashboardArgs,\n pulumi.ResourceOptions, *args, **kwargs)\n if resource_args is not None:\n __self__._internal_init(resource_name, opts, **resource_args.\n __dict__)\n else:\n __self__._internal_init(resource_name, *args, **kwargs)\n\n def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.\n ResourceOptions]=None, dashboard_definition: Optional[pulumi.Input[\n str]]=None, dashboard_description: Optional[pulumi.Input[str]]=None,\n dashboard_name: Optional[pulumi.Input[str]]=None, project_id:\n Optional[pulumi.Input[str]]=None, tags: Optional[pulumi.Input[\n Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]]]=None,\n __props__=None):\n opts = pulumi.ResourceOptions.merge(_utilities.\n get_resource_opts_defaults(), opts)\n if not isinstance(opts, pulumi.ResourceOptions):\n raise TypeError(\n 'Expected resource options to be a ResourceOptions instance')\n if opts.id is None:\n if __props__ is not None:\n raise TypeError(\n '__props__ is only valid when passed in combination with a valid opts.id to get an existing resource'\n )\n __props__ = DashboardArgs.__new__(DashboardArgs)\n if dashboard_definition is None and not opts.urn:\n raise TypeError(\n \"Missing required property 'dashboard_definition'\")\n __props__.__dict__['dashboard_definition'] = dashboard_definition\n if dashboard_description is None and not opts.urn:\n raise TypeError(\n \"Missing required property 'dashboard_description'\")\n __props__.__dict__['dashboard_description'] = dashboard_description\n __props__.__dict__['dashboard_name'] = dashboard_name\n __props__.__dict__['project_id'] = project_id\n __props__.__dict__['tags'] = tags\n __props__.__dict__['dashboard_arn'] = None\n __props__.__dict__['dashboard_id'] = None\n super(Dashboard, __self__).__init__('aws-native:iotsitewise:Dashboard',\n resource_name, __props__, opts)\n\n @staticmethod\n def get(resource_name: str, id: pulumi.Input[str], opts: Optional[\n pulumi.ResourceOptions]=None) ->'Dashboard':\n \"\"\"\n Get an existing Dashboard resource's state with the given name, id, and optional extra\n properties used to qualify the lookup.\n\n :param str resource_name: The unique name of the resulting resource.\n :param pulumi.Input[str] id: The unique provider ID of the resource to lookup.\n :param pulumi.ResourceOptions opts: Options for the resource.\n \"\"\"\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)\n )\n __props__ = DashboardArgs.__new__(DashboardArgs)\n __props__.__dict__['dashboard_arn'] = None\n __props__.__dict__['dashboard_definition'] = None\n __props__.__dict__['dashboard_description'] = None\n __props__.__dict__['dashboard_id'] = None\n __props__.__dict__['dashboard_name'] = None\n __props__.__dict__['project_id'] = None\n __props__.__dict__['tags'] = None\n return Dashboard(resource_name, opts=opts, __props__=__props__)\n\n @property\n @pulumi.getter(name='dashboardArn')\n def dashboard_arn(self) ->pulumi.Output[str]:\n \"\"\"\n The ARN of the dashboard.\n \"\"\"\n return pulumi.get(self, 'dashboard_arn')\n\n @property\n @pulumi.getter(name='dashboardDefinition')\n def dashboard_definition(self) ->pulumi.Output[str]:\n \"\"\"\n The dashboard definition specified in a JSON literal.\n \"\"\"\n return pulumi.get(self, 'dashboard_definition')\n\n @property\n @pulumi.getter(name='dashboardDescription')\n def dashboard_description(self) ->pulumi.Output[str]:\n \"\"\"\n A description for the dashboard.\n \"\"\"\n return pulumi.get(self, 'dashboard_description')\n\n @property\n @pulumi.getter(name='dashboardId')\n def dashboard_id(self) ->pulumi.Output[str]:\n \"\"\"\n The ID of the dashboard.\n \"\"\"\n return pulumi.get(self, 'dashboard_id')\n\n @property\n @pulumi.getter(name='dashboardName')\n def dashboard_name(self) ->pulumi.Output[str]:\n \"\"\"\n A friendly name for the dashboard.\n \"\"\"\n return pulumi.get(self, 'dashboard_name')\n\n @property\n @pulumi.getter(name='projectId')\n def project_id(self) ->pulumi.Output[Optional[str]]:\n \"\"\"\n The ID of the project in which to create the dashboard.\n \"\"\"\n return pulumi.get(self, 'project_id')\n\n @property\n @pulumi.getter\n def tags(self) ->pulumi.Output[Optional[Sequence['outputs.DashboardTag']]]:\n \"\"\"\n A list of key-value pairs that contain metadata for the dashboard.\n \"\"\"\n return pulumi.get(self, 'tags')\n", "step-5": "# coding=utf-8\n# *** WARNING: this file was generated by the Pulumi SDK Generator. ***\n# *** Do not edit by hand unless you're certain you know what you are doing! ***\n\nimport copy\nimport warnings\nimport pulumi\nimport pulumi.runtime\nfrom typing import Any, Mapping, Optional, Sequence, Union, overload\nfrom .. import _utilities\nfrom . import outputs\nfrom ._inputs import *\n\n__all__ = ['DashboardArgs', 'Dashboard']\n\n@pulumi.input_type\nclass DashboardArgs:\n def __init__(__self__, *,\n dashboard_definition: pulumi.Input[str],\n dashboard_description: pulumi.Input[str],\n dashboard_name: Optional[pulumi.Input[str]] = None,\n project_id: Optional[pulumi.Input[str]] = None,\n tags: Optional[pulumi.Input[Sequence[pulumi.Input['DashboardTagArgs']]]] = None):\n \"\"\"\n The set of arguments for constructing a Dashboard resource.\n :param pulumi.Input[str] dashboard_definition: The dashboard definition specified in a JSON literal.\n :param pulumi.Input[str] dashboard_description: A description for the dashboard.\n :param pulumi.Input[str] dashboard_name: A friendly name for the dashboard.\n :param pulumi.Input[str] project_id: The ID of the project in which to create the dashboard.\n :param pulumi.Input[Sequence[pulumi.Input['DashboardTagArgs']]] tags: A list of key-value pairs that contain metadata for the dashboard.\n \"\"\"\n pulumi.set(__self__, \"dashboard_definition\", dashboard_definition)\n pulumi.set(__self__, \"dashboard_description\", dashboard_description)\n if dashboard_name is not None:\n pulumi.set(__self__, \"dashboard_name\", dashboard_name)\n if project_id is not None:\n pulumi.set(__self__, \"project_id\", project_id)\n if tags is not None:\n pulumi.set(__self__, \"tags\", tags)\n\n @property\n @pulumi.getter(name=\"dashboardDefinition\")\n def dashboard_definition(self) -> pulumi.Input[str]:\n \"\"\"\n The dashboard definition specified in a JSON literal.\n \"\"\"\n return pulumi.get(self, \"dashboard_definition\")\n\n @dashboard_definition.setter\n def dashboard_definition(self, value: pulumi.Input[str]):\n pulumi.set(self, \"dashboard_definition\", value)\n\n @property\n @pulumi.getter(name=\"dashboardDescription\")\n def dashboard_description(self) -> pulumi.Input[str]:\n \"\"\"\n A description for the dashboard.\n \"\"\"\n return pulumi.get(self, \"dashboard_description\")\n\n @dashboard_description.setter\n def dashboard_description(self, value: pulumi.Input[str]):\n pulumi.set(self, \"dashboard_description\", value)\n\n @property\n @pulumi.getter(name=\"dashboardName\")\n def dashboard_name(self) -> Optional[pulumi.Input[str]]:\n \"\"\"\n A friendly name for the dashboard.\n \"\"\"\n return pulumi.get(self, \"dashboard_name\")\n\n @dashboard_name.setter\n def dashboard_name(self, value: Optional[pulumi.Input[str]]):\n pulumi.set(self, \"dashboard_name\", value)\n\n @property\n @pulumi.getter(name=\"projectId\")\n def project_id(self) -> Optional[pulumi.Input[str]]:\n \"\"\"\n The ID of the project in which to create the dashboard.\n \"\"\"\n return pulumi.get(self, \"project_id\")\n\n @project_id.setter\n def project_id(self, value: Optional[pulumi.Input[str]]):\n pulumi.set(self, \"project_id\", value)\n\n @property\n @pulumi.getter\n def tags(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['DashboardTagArgs']]]]:\n \"\"\"\n A list of key-value pairs that contain metadata for the dashboard.\n \"\"\"\n return pulumi.get(self, \"tags\")\n\n @tags.setter\n def tags(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['DashboardTagArgs']]]]):\n pulumi.set(self, \"tags\", value)\n\n\nclass Dashboard(pulumi.CustomResource):\n @overload\n def __init__(__self__,\n resource_name: str,\n opts: Optional[pulumi.ResourceOptions] = None,\n dashboard_definition: Optional[pulumi.Input[str]] = None,\n dashboard_description: Optional[pulumi.Input[str]] = None,\n dashboard_name: Optional[pulumi.Input[str]] = None,\n project_id: Optional[pulumi.Input[str]] = None,\n tags: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]]] = None,\n __props__=None):\n \"\"\"\n Resource schema for AWS::IoTSiteWise::Dashboard\n\n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] dashboard_definition: The dashboard definition specified in a JSON literal.\n :param pulumi.Input[str] dashboard_description: A description for the dashboard.\n :param pulumi.Input[str] dashboard_name: A friendly name for the dashboard.\n :param pulumi.Input[str] project_id: The ID of the project in which to create the dashboard.\n :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]] tags: A list of key-value pairs that contain metadata for the dashboard.\n \"\"\"\n ...\n @overload\n def __init__(__self__,\n resource_name: str,\n args: DashboardArgs,\n opts: Optional[pulumi.ResourceOptions] = None):\n \"\"\"\n Resource schema for AWS::IoTSiteWise::Dashboard\n\n :param str resource_name: The name of the resource.\n :param DashboardArgs args: The arguments to use to populate this resource's properties.\n :param pulumi.ResourceOptions opts: Options for the resource.\n \"\"\"\n ...\n def __init__(__self__, resource_name: str, *args, **kwargs):\n resource_args, opts = _utilities.get_resource_args_opts(DashboardArgs, pulumi.ResourceOptions, *args, **kwargs)\n if resource_args is not None:\n __self__._internal_init(resource_name, opts, **resource_args.__dict__)\n else:\n __self__._internal_init(resource_name, *args, **kwargs)\n\n def _internal_init(__self__,\n resource_name: str,\n opts: Optional[pulumi.ResourceOptions] = None,\n dashboard_definition: Optional[pulumi.Input[str]] = None,\n dashboard_description: Optional[pulumi.Input[str]] = None,\n dashboard_name: Optional[pulumi.Input[str]] = None,\n project_id: Optional[pulumi.Input[str]] = None,\n tags: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['DashboardTagArgs']]]]] = None,\n __props__=None):\n opts = pulumi.ResourceOptions.merge(_utilities.get_resource_opts_defaults(), opts)\n if not isinstance(opts, pulumi.ResourceOptions):\n raise TypeError('Expected resource options to be a ResourceOptions instance')\n if opts.id is None:\n if __props__ is not None:\n raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')\n __props__ = DashboardArgs.__new__(DashboardArgs)\n\n if dashboard_definition is None and not opts.urn:\n raise TypeError(\"Missing required property 'dashboard_definition'\")\n __props__.__dict__[\"dashboard_definition\"] = dashboard_definition\n if dashboard_description is None and not opts.urn:\n raise TypeError(\"Missing required property 'dashboard_description'\")\n __props__.__dict__[\"dashboard_description\"] = dashboard_description\n __props__.__dict__[\"dashboard_name\"] = dashboard_name\n __props__.__dict__[\"project_id\"] = project_id\n __props__.__dict__[\"tags\"] = tags\n __props__.__dict__[\"dashboard_arn\"] = None\n __props__.__dict__[\"dashboard_id\"] = None\n super(Dashboard, __self__).__init__(\n 'aws-native:iotsitewise:Dashboard',\n resource_name,\n __props__,\n opts)\n\n @staticmethod\n def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None) -> 'Dashboard':\n \"\"\"\n Get an existing Dashboard resource's state with the given name, id, and optional extra\n properties used to qualify the lookup.\n\n :param str resource_name: The unique name of the resulting resource.\n :param pulumi.Input[str] id: The unique provider ID of the resource to lookup.\n :param pulumi.ResourceOptions opts: Options for the resource.\n \"\"\"\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = DashboardArgs.__new__(DashboardArgs)\n\n __props__.__dict__[\"dashboard_arn\"] = None\n __props__.__dict__[\"dashboard_definition\"] = None\n __props__.__dict__[\"dashboard_description\"] = None\n __props__.__dict__[\"dashboard_id\"] = None\n __props__.__dict__[\"dashboard_name\"] = None\n __props__.__dict__[\"project_id\"] = None\n __props__.__dict__[\"tags\"] = None\n return Dashboard(resource_name, opts=opts, __props__=__props__)\n\n @property\n @pulumi.getter(name=\"dashboardArn\")\n def dashboard_arn(self) -> pulumi.Output[str]:\n \"\"\"\n The ARN of the dashboard.\n \"\"\"\n return pulumi.get(self, \"dashboard_arn\")\n\n @property\n @pulumi.getter(name=\"dashboardDefinition\")\n def dashboard_definition(self) -> pulumi.Output[str]:\n \"\"\"\n The dashboard definition specified in a JSON literal.\n \"\"\"\n return pulumi.get(self, \"dashboard_definition\")\n\n @property\n @pulumi.getter(name=\"dashboardDescription\")\n def dashboard_description(self) -> pulumi.Output[str]:\n \"\"\"\n A description for the dashboard.\n \"\"\"\n return pulumi.get(self, \"dashboard_description\")\n\n @property\n @pulumi.getter(name=\"dashboardId\")\n def dashboard_id(self) -> pulumi.Output[str]:\n \"\"\"\n The ID of the dashboard.\n \"\"\"\n return pulumi.get(self, \"dashboard_id\")\n\n @property\n @pulumi.getter(name=\"dashboardName\")\n def dashboard_name(self) -> pulumi.Output[str]:\n \"\"\"\n A friendly name for the dashboard.\n \"\"\"\n return pulumi.get(self, \"dashboard_name\")\n\n @property\n @pulumi.getter(name=\"projectId\")\n def project_id(self) -> pulumi.Output[Optional[str]]:\n \"\"\"\n The ID of the project in which to create the dashboard.\n \"\"\"\n return pulumi.get(self, \"project_id\")\n\n @property\n @pulumi.getter\n def tags(self) -> pulumi.Output[Optional[Sequence['outputs.DashboardTag']]]:\n \"\"\"\n A list of key-value pairs that contain metadata for the dashboard.\n \"\"\"\n return pulumi.get(self, \"tags\")\n\n", "step-ids": [ 14, 21, 22, 23, 28 ] }
[ 14, 21, 22, 23, 28 ]
<|reserved_special_token_0|> class TestConfig: <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> <|reserved_special_token_0|> class TestFlask(Flask): def configure(self, *storages, **configs): import flask_file_system as fs for key, value in configs.items(): self.config[key] = value fs.init_app(self, *storages) <|reserved_special_token_0|> class Utils: def filestorage(self, filename, content, content_type=None): return FileStorage(self.file(content), filename, content_type= content_type) def file(self, content): if isinstance(content, bytes): return io.BytesIO(content) elif isinstance(content, str): return io.BytesIO(content.encode('utf-8')) else: return content <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class TestConfig: TESTING = True MONGODB_DB = 'flask-fs-test' MONGODB_HOST = 'localhost' MONGODB_PORT = 27017 class TestFlask(Flask): def configure(self, *storages, **configs): import flask_file_system as fs for key, value in configs.items(): self.config[key] = value fs.init_app(self, *storages) @pytest.fixture def app(): app = TestFlask('flaskfs-tests') app.config.from_object(TestConfig) yield app <|reserved_special_token_0|> @pytest.fixture def jpgfile(): return JPG_FILE class Utils: def filestorage(self, filename, content, content_type=None): return FileStorage(self.file(content), filename, content_type= content_type) def file(self, content): if isinstance(content, bytes): return io.BytesIO(content) elif isinstance(content, str): return io.BytesIO(content.encode('utf-8')) else: return content <|reserved_special_token_0|> @pytest.fixture def mock_backend(app, mocker): app.config['FS_BACKEND'] = 'mock' mock = mocker.patch('flask_file_system.backends.mock.MockBackend') yield mock <|reserved_special_token_1|> <|reserved_special_token_0|> class TestConfig: TESTING = True MONGODB_DB = 'flask-fs-test' MONGODB_HOST = 'localhost' MONGODB_PORT = 27017 class TestFlask(Flask): def configure(self, *storages, **configs): import flask_file_system as fs for key, value in configs.items(): self.config[key] = value fs.init_app(self, *storages) @pytest.fixture def app(): app = TestFlask('flaskfs-tests') app.config.from_object(TestConfig) yield app <|reserved_special_token_0|> @pytest.fixture def pngfile(): return PNG_FILE @pytest.fixture def jpgfile(): return JPG_FILE class Utils: def filestorage(self, filename, content, content_type=None): return FileStorage(self.file(content), filename, content_type= content_type) def file(self, content): if isinstance(content, bytes): return io.BytesIO(content) elif isinstance(content, str): return io.BytesIO(content.encode('utf-8')) else: return content <|reserved_special_token_0|> @pytest.fixture def mock_backend(app, mocker): app.config['FS_BACKEND'] = 'mock' mock = mocker.patch('flask_file_system.backends.mock.MockBackend') yield mock <|reserved_special_token_1|> <|reserved_special_token_0|> class TestConfig: TESTING = True MONGODB_DB = 'flask-fs-test' MONGODB_HOST = 'localhost' MONGODB_PORT = 27017 class TestFlask(Flask): def configure(self, *storages, **configs): import flask_file_system as fs for key, value in configs.items(): self.config[key] = value fs.init_app(self, *storages) @pytest.fixture def app(): app = TestFlask('flaskfs-tests') app.config.from_object(TestConfig) yield app @pytest.fixture def binfile(): return PNG_FILE @pytest.fixture def pngfile(): return PNG_FILE @pytest.fixture def jpgfile(): return JPG_FILE class Utils: def filestorage(self, filename, content, content_type=None): return FileStorage(self.file(content), filename, content_type= content_type) def file(self, content): if isinstance(content, bytes): return io.BytesIO(content) elif isinstance(content, str): return io.BytesIO(content.encode('utf-8')) else: return content @pytest.fixture def utils(faker): return Utils() @pytest.fixture def mock_backend(app, mocker): app.config['FS_BACKEND'] = 'mock' mock = mocker.patch('flask_file_system.backends.mock.MockBackend') yield mock <|reserved_special_token_1|> import io import os from flask import Flask from werkzeug.datastructures import FileStorage import pytest PNG_FILE = os.path.join(os.path.dirname(__file__), 'flask.png') JPG_FILE = os.path.join(os.path.dirname(__file__), 'flask.jpg') class TestConfig: TESTING = True MONGODB_DB = 'flask-fs-test' MONGODB_HOST = 'localhost' MONGODB_PORT = 27017 class TestFlask(Flask): def configure(self, *storages, **configs): import flask_file_system as fs for key, value in configs.items(): self.config[key] = value fs.init_app(self, *storages) @pytest.fixture def app(): app = TestFlask('flaskfs-tests') app.config.from_object(TestConfig) yield app @pytest.fixture def binfile(): return PNG_FILE @pytest.fixture def pngfile(): return PNG_FILE @pytest.fixture def jpgfile(): return JPG_FILE class Utils: def filestorage(self, filename, content, content_type=None): return FileStorage( self.file(content), filename, content_type=content_type ) def file(self, content): if isinstance(content, bytes): return io.BytesIO(content) elif isinstance(content, str): return io.BytesIO(content.encode('utf-8')) else: return content @pytest.fixture def utils(faker): return Utils() @pytest.fixture def mock_backend(app, mocker): app.config['FS_BACKEND'] = 'mock' mock = mocker.patch('flask_file_system.backends.mock.MockBackend') yield mock
flexible
{ "blob_id": "dfc412acc9b69f50396680db1b9f6feafe162996", "index": 5571, "step-1": "<mask token>\n\n\nclass TestConfig:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass TestFlask(Flask):\n\n def configure(self, *storages, **configs):\n import flask_file_system as fs\n for key, value in configs.items():\n self.config[key] = value\n fs.init_app(self, *storages)\n\n\n<mask token>\n\n\nclass Utils:\n\n def filestorage(self, filename, content, content_type=None):\n return FileStorage(self.file(content), filename, content_type=\n content_type)\n\n def file(self, content):\n if isinstance(content, bytes):\n return io.BytesIO(content)\n elif isinstance(content, str):\n return io.BytesIO(content.encode('utf-8'))\n else:\n return content\n\n\n<mask token>\n", "step-2": "<mask token>\n\n\nclass TestConfig:\n TESTING = True\n MONGODB_DB = 'flask-fs-test'\n MONGODB_HOST = 'localhost'\n MONGODB_PORT = 27017\n\n\nclass TestFlask(Flask):\n\n def configure(self, *storages, **configs):\n import flask_file_system as fs\n for key, value in configs.items():\n self.config[key] = value\n fs.init_app(self, *storages)\n\n\n@pytest.fixture\ndef app():\n app = TestFlask('flaskfs-tests')\n app.config.from_object(TestConfig)\n yield app\n\n\n<mask token>\n\n\n@pytest.fixture\ndef jpgfile():\n return JPG_FILE\n\n\nclass Utils:\n\n def filestorage(self, filename, content, content_type=None):\n return FileStorage(self.file(content), filename, content_type=\n content_type)\n\n def file(self, content):\n if isinstance(content, bytes):\n return io.BytesIO(content)\n elif isinstance(content, str):\n return io.BytesIO(content.encode('utf-8'))\n else:\n return content\n\n\n<mask token>\n\n\n@pytest.fixture\ndef mock_backend(app, mocker):\n app.config['FS_BACKEND'] = 'mock'\n mock = mocker.patch('flask_file_system.backends.mock.MockBackend')\n yield mock\n", "step-3": "<mask token>\n\n\nclass TestConfig:\n TESTING = True\n MONGODB_DB = 'flask-fs-test'\n MONGODB_HOST = 'localhost'\n MONGODB_PORT = 27017\n\n\nclass TestFlask(Flask):\n\n def configure(self, *storages, **configs):\n import flask_file_system as fs\n for key, value in configs.items():\n self.config[key] = value\n fs.init_app(self, *storages)\n\n\n@pytest.fixture\ndef app():\n app = TestFlask('flaskfs-tests')\n app.config.from_object(TestConfig)\n yield app\n\n\n<mask token>\n\n\n@pytest.fixture\ndef pngfile():\n return PNG_FILE\n\n\n@pytest.fixture\ndef jpgfile():\n return JPG_FILE\n\n\nclass Utils:\n\n def filestorage(self, filename, content, content_type=None):\n return FileStorage(self.file(content), filename, content_type=\n content_type)\n\n def file(self, content):\n if isinstance(content, bytes):\n return io.BytesIO(content)\n elif isinstance(content, str):\n return io.BytesIO(content.encode('utf-8'))\n else:\n return content\n\n\n<mask token>\n\n\n@pytest.fixture\ndef mock_backend(app, mocker):\n app.config['FS_BACKEND'] = 'mock'\n mock = mocker.patch('flask_file_system.backends.mock.MockBackend')\n yield mock\n", "step-4": "<mask token>\n\n\nclass TestConfig:\n TESTING = True\n MONGODB_DB = 'flask-fs-test'\n MONGODB_HOST = 'localhost'\n MONGODB_PORT = 27017\n\n\nclass TestFlask(Flask):\n\n def configure(self, *storages, **configs):\n import flask_file_system as fs\n for key, value in configs.items():\n self.config[key] = value\n fs.init_app(self, *storages)\n\n\n@pytest.fixture\ndef app():\n app = TestFlask('flaskfs-tests')\n app.config.from_object(TestConfig)\n yield app\n\n\n@pytest.fixture\ndef binfile():\n return PNG_FILE\n\n\n@pytest.fixture\ndef pngfile():\n return PNG_FILE\n\n\n@pytest.fixture\ndef jpgfile():\n return JPG_FILE\n\n\nclass Utils:\n\n def filestorage(self, filename, content, content_type=None):\n return FileStorage(self.file(content), filename, content_type=\n content_type)\n\n def file(self, content):\n if isinstance(content, bytes):\n return io.BytesIO(content)\n elif isinstance(content, str):\n return io.BytesIO(content.encode('utf-8'))\n else:\n return content\n\n\n@pytest.fixture\ndef utils(faker):\n return Utils()\n\n\n@pytest.fixture\ndef mock_backend(app, mocker):\n app.config['FS_BACKEND'] = 'mock'\n mock = mocker.patch('flask_file_system.backends.mock.MockBackend')\n yield mock\n", "step-5": "import io\nimport os\n\nfrom flask import Flask\nfrom werkzeug.datastructures import FileStorage\n\nimport pytest\n\nPNG_FILE = os.path.join(os.path.dirname(__file__), 'flask.png')\nJPG_FILE = os.path.join(os.path.dirname(__file__), 'flask.jpg')\n\n\nclass TestConfig:\n TESTING = True\n MONGODB_DB = 'flask-fs-test'\n MONGODB_HOST = 'localhost'\n MONGODB_PORT = 27017\n\n\nclass TestFlask(Flask):\n def configure(self, *storages, **configs):\n import flask_file_system as fs\n for key, value in configs.items():\n self.config[key] = value\n fs.init_app(self, *storages)\n\n\n@pytest.fixture\ndef app():\n app = TestFlask('flaskfs-tests')\n app.config.from_object(TestConfig)\n yield app\n\n\n@pytest.fixture\ndef binfile():\n return PNG_FILE\n\n\n@pytest.fixture\ndef pngfile():\n return PNG_FILE\n\n\n@pytest.fixture\ndef jpgfile():\n return JPG_FILE\n\n\nclass Utils:\n def filestorage(self, filename, content, content_type=None):\n return FileStorage(\n self.file(content),\n filename,\n content_type=content_type\n )\n\n def file(self, content):\n if isinstance(content, bytes):\n return io.BytesIO(content)\n elif isinstance(content, str):\n return io.BytesIO(content.encode('utf-8'))\n else:\n return content\n\n\n@pytest.fixture\ndef utils(faker):\n return Utils()\n\n\n@pytest.fixture\ndef mock_backend(app, mocker):\n app.config['FS_BACKEND'] = 'mock'\n mock = mocker.patch('flask_file_system.backends.mock.MockBackend')\n yield mock\n", "step-ids": [ 6, 10, 11, 13, 16 ] }
[ 6, 10, 11, 13, 16 ]
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'KPS_RevisitBusinessEvents.ui' # # Created: Sun May 18 14:50:49 2014 # by: PyQt4 UI code generator 4.10.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui, QtSql import sqlite3 try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Form(object): def setupUi(self, Form): Form.setObjectName(_fromUtf8("Form")) Form.resize(666, 538) palette = QtGui.QPalette() self.eventSkip = 0; self.db = Database() brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) self.inWork = True brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(8, 129, 2)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) Form.setPalette(palette) self.tb_EventViewer = QtGui.QTableView(Form) self.tb_EventViewer.setGeometry(QtCore.QRect(60, 120, 531, 351)) self.tb_EventViewer.setObjectName(_fromUtf8("tb_EventViewer")) self.tb_EventViewer.horizontalHeader().setVisible(False) self.tb_EventViewer.verticalHeader().setVisible(False) # self.tb_EventViewer.setColumnCount(0) # self.tb_EventViewer.setRowCount(0) self.bt_Earlier = QtGui.QPushButton(Form) self.bt_Earlier.setGeometry(QtCore.QRect(60, 90, 75, 23)) self.bt_Earlier.setObjectName(_fromUtf8("bt_Earlier")) self.bt_Earlier.clicked.connect(self.clicked_bt_Earlier) self.bt_Later = QtGui.QPushButton(Form) self.bt_Later.setGeometry(QtCore.QRect(510, 90, 75, 23)) self.bt_Later.setObjectName(_fromUtf8("bt_Later")) self.bt_Later.clicked.connect(self.clicked_bt_Later) self.label = QtGui.QLabel(Form) self.label.setGeometry(QtCore.QRect(70, 0, 511, 41)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush) self.label.setPalette(palette) font = QtGui.QFont() font.setFamily(_fromUtf8("Segoe UI Light")) font.setPointSize(18) font.setBold(True) font.setWeight(75) self.label.setFont(font) self.label.setObjectName(_fromUtf8("label")) self.cb_EventType = QtGui.QComboBox(Form) self.cb_EventType.setGeometry(QtCore.QRect(230, 50, 221, 22)) self.cb_EventType.setObjectName(_fromUtf8("cb_EventType")) self.cb_EventType.currentIndexChanged['QString'].connect(self.handleChanged) self.label_2 = QtGui.QLabel(Form) self.label_2.setGeometry(QtCore.QRect(70, 50, 121, 21)) self.label_3 = QtGui.QLabel(Form) self.label_3.setGeometry(QtCore.QRect(190, 90, 221, 21)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) self.label_2.setPalette(palette) self.label_3.setPalette(palette) font = QtGui.QFont() font.setFamily(_fromUtf8("Segoe UI")) font.setPointSize(12) self.label_2.setFont(font) self.label_2.setObjectName(_fromUtf8("label_2")) self.label_3.setFont(font) self.label_3.setObjectName(_fromUtf8("label_3")) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) self.initialize() def retranslateUi(self, Form): Form.setWindowTitle(_translate("Form", "Revisit business events", None)) self.bt_Earlier.setText(_translate("Form", "<<", None)) self.bt_Later.setText(_translate("Form", ">>", None)) self.label.setText(_translate("Form", "Revisit business events", None)) self.label_2.setText(_translate("Form", "Select Event Type", None)) def initialize(self): self.cb_EventType.addItems(self.getBusinessEventsType()) # self.cb_Destination.addItems(RH.getLocations()) def getBusinessEventsType(self): conn = sqlite3.connect("../Database/Business.db") conn.text_factory = str c = conn.cursor() c.execute('SELECT Event FROM EventTypes') locs = [r[0] for r in c.fetchall()] conn.close() return locs def handleChanged(self, text): modelView = QtGui.QStandardItemModel() query = QtSql.QSqlQuery() query.exec_("Select * from BusinessEvents a, EventTypes b where b.Event = '" + text + "' and b.EventTypeID = a.EventTypeID order by ID DESC LIMIT " + str(self.eventSkip) + ",1") recCount = 0; while query.next(): recCount = recCount + 1 if query.value(2).toString() != '': query_Origin = QtSql.QSqlQuery() query_Origin.exec_("Select Name from Cities where ID = '" + query.value(2).toString() + "' LIMIT 1") query_Origin.next() modelInputItem = QtGui.QStandardItem("Origin") modelInputValue = QtGui.QStandardItem(query_Origin.value(0).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(3).toString() != '': query_Destination = QtSql.QSqlQuery() query_Destination.exec_("Select Name from Cities where ID = '" + query.value(3).toString() + "' LIMIT 1") query_Destination.next() modelInputItem = QtGui.QStandardItem("Destination") modelInputValue = QtGui.QStandardItem(query_Destination.value(0).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(4).toString() != '': modelInputItem = QtGui.QStandardItem("Weight") modelInputValue = QtGui.QStandardItem(query.value(4).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(5).toString() != '': modelInputItem = QtGui.QStandardItem("Volume") modelInputValue = QtGui.QStandardItem(query.value(5).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(6).toString() != '': modelInputItem = QtGui.QStandardItem("Time of Entry") modelInputValue = QtGui.QStandardItem(query.value(6).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(7).toString() != '': modelInputItem = QtGui.QStandardItem("Priority") modelInputValue = QtGui.QStandardItem(query.value(7).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(8).toString() != '': modelInputItem = QtGui.QStandardItem("Price Per Gram") modelInputValue = QtGui.QStandardItem(query.value(8).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(9).toString() != '': modelInputItem = QtGui.QStandardItem("Price Per CC") modelInputValue = QtGui.QStandardItem(query.value(9).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(10).toString() != '': modelInputItem = QtGui.QStandardItem("Company") modelInputValue = QtGui.QStandardItem(query.value(10).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(11).toString() != '': modelInputItem = QtGui.QStandardItem("Transport Type") modelInputValue = QtGui.QStandardItem(query.value(11).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(12).toString() != '': modelInputItem = QtGui.QStandardItem("Day of the Week") modelInputValue = QtGui.QStandardItem(query.value(12).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(13).toString() != '': modelInputItem = QtGui.QStandardItem("Frequency") modelInputValue = QtGui.QStandardItem(query.value(13).toString()) modelView.appendRow([modelInputItem,modelInputValue]) if query.value(14).toString() != '': modelInputItem = QtGui.QStandardItem("Duration") modelInputValue = QtGui.QStandardItem(query.value(14).toString()) modelView.appendRow([modelInputItem,modelInputValue]) #modelInputValue = QtGui.QStandardItem('Value') # modelView.appendRow([modelInputItem,modelInputValue]) if recCount == 0: self.label_3.setText(_translate("Form", "No Records found", None)) self.inWork = False else: self.label_3.setText(_translate("Form", "", None)) self.inWork = True self.tb_EventViewer.setModel(modelView) def clicked_bt_Earlier(self): self.eventSkip = self.eventSkip + 1 self.handleChanged(self.cb_EventType.currentText()) def clicked_bt_Later(self): if self.eventSkip > 0: self.eventSkip = self.eventSkip - 1 self.handleChanged(self.cb_EventType.currentText()) class Database: def __init__(self, parent = None): self.data = QtSql.QSqlDatabase.addDatabase("QSQLITE") self.data.setDatabaseName("../Database/Business.db") self.data.open()
normal
{ "blob_id": "8339113fd6b0c286cc48ec04e6e24978e2a4b44e", "index": 9991, "step-1": "<mask token>\n\n\nclass Ui_Form(object):\n\n def setupUi(self, Form):\n Form.setObjectName(_fromUtf8('Form'))\n Form.resize(666, 538)\n palette = QtGui.QPalette()\n self.eventSkip = 0\n self.db = Database()\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)\n self.inWork = True\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)\n Form.setPalette(palette)\n self.tb_EventViewer = QtGui.QTableView(Form)\n self.tb_EventViewer.setGeometry(QtCore.QRect(60, 120, 531, 351))\n self.tb_EventViewer.setObjectName(_fromUtf8('tb_EventViewer'))\n self.tb_EventViewer.horizontalHeader().setVisible(False)\n self.tb_EventViewer.verticalHeader().setVisible(False)\n self.bt_Earlier = QtGui.QPushButton(Form)\n self.bt_Earlier.setGeometry(QtCore.QRect(60, 90, 75, 23))\n self.bt_Earlier.setObjectName(_fromUtf8('bt_Earlier'))\n self.bt_Earlier.clicked.connect(self.clicked_bt_Earlier)\n self.bt_Later = QtGui.QPushButton(Form)\n self.bt_Later.setGeometry(QtCore.QRect(510, 90, 75, 23))\n self.bt_Later.setObjectName(_fromUtf8('bt_Later'))\n self.bt_Later.clicked.connect(self.clicked_bt_Later)\n self.label = QtGui.QLabel(Form)\n self.label.setGeometry(QtCore.QRect(70, 0, 511, 41))\n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText,\n brush)\n self.label.setPalette(palette)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8('Segoe UI Light'))\n font.setPointSize(18)\n font.setBold(True)\n font.setWeight(75)\n self.label.setFont(font)\n self.label.setObjectName(_fromUtf8('label'))\n self.cb_EventType = QtGui.QComboBox(Form)\n self.cb_EventType.setGeometry(QtCore.QRect(230, 50, 221, 22))\n self.cb_EventType.setObjectName(_fromUtf8('cb_EventType'))\n self.cb_EventType.currentIndexChanged['QString'].connect(self.\n handleChanged)\n self.label_2 = QtGui.QLabel(Form)\n self.label_2.setGeometry(QtCore.QRect(70, 50, 121, 21))\n self.label_3 = QtGui.QLabel(Form)\n self.label_3.setGeometry(QtCore.QRect(190, 90, 221, 21))\n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText,\n brush)\n self.label_2.setPalette(palette)\n self.label_3.setPalette(palette)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8('Segoe UI'))\n font.setPointSize(12)\n self.label_2.setFont(font)\n self.label_2.setObjectName(_fromUtf8('label_2'))\n self.label_3.setFont(font)\n self.label_3.setObjectName(_fromUtf8('label_3'))\n self.retranslateUi(Form)\n QtCore.QMetaObject.connectSlotsByName(Form)\n self.initialize()\n\n def retranslateUi(self, Form):\n Form.setWindowTitle(_translate('Form', 'Revisit business events', None)\n )\n self.bt_Earlier.setText(_translate('Form', '<<', None))\n self.bt_Later.setText(_translate('Form', '>>', None))\n self.label.setText(_translate('Form', 'Revisit business events', None))\n self.label_2.setText(_translate('Form', 'Select Event Type', None))\n <mask token>\n\n def getBusinessEventsType(self):\n conn = sqlite3.connect('../Database/Business.db')\n conn.text_factory = str\n c = conn.cursor()\n c.execute('SELECT Event FROM EventTypes')\n locs = [r[0] for r in c.fetchall()]\n conn.close()\n return locs\n\n def handleChanged(self, text):\n modelView = QtGui.QStandardItemModel()\n query = QtSql.QSqlQuery()\n query.exec_(\n \"Select * from BusinessEvents a, EventTypes b where b.Event = '\" +\n text +\n \"' and b.EventTypeID = a.EventTypeID order by ID DESC LIMIT \" +\n str(self.eventSkip) + ',1')\n recCount = 0\n while query.next():\n recCount = recCount + 1\n if query.value(2).toString() != '':\n query_Origin = QtSql.QSqlQuery()\n query_Origin.exec_(\"Select Name from Cities where ID = '\" +\n query.value(2).toString() + \"' LIMIT 1\")\n query_Origin.next()\n modelInputItem = QtGui.QStandardItem('Origin')\n modelInputValue = QtGui.QStandardItem(query_Origin.value(0)\n .toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(3).toString() != '':\n query_Destination = QtSql.QSqlQuery()\n query_Destination.exec_(\n \"Select Name from Cities where ID = '\" + query.value(3)\n .toString() + \"' LIMIT 1\")\n query_Destination.next()\n modelInputItem = QtGui.QStandardItem('Destination')\n modelInputValue = QtGui.QStandardItem(query_Destination.\n value(0).toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(4).toString() != '':\n modelInputItem = QtGui.QStandardItem('Weight')\n modelInputValue = QtGui.QStandardItem(query.value(4).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(5).toString() != '':\n modelInputItem = QtGui.QStandardItem('Volume')\n modelInputValue = QtGui.QStandardItem(query.value(5).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(6).toString() != '':\n modelInputItem = QtGui.QStandardItem('Time of Entry')\n modelInputValue = QtGui.QStandardItem(query.value(6).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(7).toString() != '':\n modelInputItem = QtGui.QStandardItem('Priority')\n modelInputValue = QtGui.QStandardItem(query.value(7).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(8).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per Gram')\n modelInputValue = QtGui.QStandardItem(query.value(8).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(9).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per CC')\n modelInputValue = QtGui.QStandardItem(query.value(9).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(10).toString() != '':\n modelInputItem = QtGui.QStandardItem('Company')\n modelInputValue = QtGui.QStandardItem(query.value(10).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(11).toString() != '':\n modelInputItem = QtGui.QStandardItem('Transport Type')\n modelInputValue = QtGui.QStandardItem(query.value(11).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(12).toString() != '':\n modelInputItem = QtGui.QStandardItem('Day of the Week')\n modelInputValue = QtGui.QStandardItem(query.value(12).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(13).toString() != '':\n modelInputItem = QtGui.QStandardItem('Frequency')\n modelInputValue = QtGui.QStandardItem(query.value(13).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(14).toString() != '':\n modelInputItem = QtGui.QStandardItem('Duration')\n modelInputValue = QtGui.QStandardItem(query.value(14).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if recCount == 0:\n self.label_3.setText(_translate('Form', 'No Records found', None))\n self.inWork = False\n else:\n self.label_3.setText(_translate('Form', '', None))\n self.inWork = True\n self.tb_EventViewer.setModel(modelView)\n\n def clicked_bt_Earlier(self):\n self.eventSkip = self.eventSkip + 1\n self.handleChanged(self.cb_EventType.currentText())\n <mask token>\n\n\nclass Database:\n\n def __init__(self, parent=None):\n self.data = QtSql.QSqlDatabase.addDatabase('QSQLITE')\n self.data.setDatabaseName('../Database/Business.db')\n self.data.open()\n", "step-2": "<mask token>\n\n\nclass Ui_Form(object):\n\n def setupUi(self, Form):\n Form.setObjectName(_fromUtf8('Form'))\n Form.resize(666, 538)\n palette = QtGui.QPalette()\n self.eventSkip = 0\n self.db = Database()\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)\n self.inWork = True\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)\n Form.setPalette(palette)\n self.tb_EventViewer = QtGui.QTableView(Form)\n self.tb_EventViewer.setGeometry(QtCore.QRect(60, 120, 531, 351))\n self.tb_EventViewer.setObjectName(_fromUtf8('tb_EventViewer'))\n self.tb_EventViewer.horizontalHeader().setVisible(False)\n self.tb_EventViewer.verticalHeader().setVisible(False)\n self.bt_Earlier = QtGui.QPushButton(Form)\n self.bt_Earlier.setGeometry(QtCore.QRect(60, 90, 75, 23))\n self.bt_Earlier.setObjectName(_fromUtf8('bt_Earlier'))\n self.bt_Earlier.clicked.connect(self.clicked_bt_Earlier)\n self.bt_Later = QtGui.QPushButton(Form)\n self.bt_Later.setGeometry(QtCore.QRect(510, 90, 75, 23))\n self.bt_Later.setObjectName(_fromUtf8('bt_Later'))\n self.bt_Later.clicked.connect(self.clicked_bt_Later)\n self.label = QtGui.QLabel(Form)\n self.label.setGeometry(QtCore.QRect(70, 0, 511, 41))\n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText,\n brush)\n self.label.setPalette(palette)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8('Segoe UI Light'))\n font.setPointSize(18)\n font.setBold(True)\n font.setWeight(75)\n self.label.setFont(font)\n self.label.setObjectName(_fromUtf8('label'))\n self.cb_EventType = QtGui.QComboBox(Form)\n self.cb_EventType.setGeometry(QtCore.QRect(230, 50, 221, 22))\n self.cb_EventType.setObjectName(_fromUtf8('cb_EventType'))\n self.cb_EventType.currentIndexChanged['QString'].connect(self.\n handleChanged)\n self.label_2 = QtGui.QLabel(Form)\n self.label_2.setGeometry(QtCore.QRect(70, 50, 121, 21))\n self.label_3 = QtGui.QLabel(Form)\n self.label_3.setGeometry(QtCore.QRect(190, 90, 221, 21))\n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText,\n brush)\n self.label_2.setPalette(palette)\n self.label_3.setPalette(palette)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8('Segoe UI'))\n font.setPointSize(12)\n self.label_2.setFont(font)\n self.label_2.setObjectName(_fromUtf8('label_2'))\n self.label_3.setFont(font)\n self.label_3.setObjectName(_fromUtf8('label_3'))\n self.retranslateUi(Form)\n QtCore.QMetaObject.connectSlotsByName(Form)\n self.initialize()\n\n def retranslateUi(self, Form):\n Form.setWindowTitle(_translate('Form', 'Revisit business events', None)\n )\n self.bt_Earlier.setText(_translate('Form', '<<', None))\n self.bt_Later.setText(_translate('Form', '>>', None))\n self.label.setText(_translate('Form', 'Revisit business events', None))\n self.label_2.setText(_translate('Form', 'Select Event Type', None))\n\n def initialize(self):\n self.cb_EventType.addItems(self.getBusinessEventsType())\n\n def getBusinessEventsType(self):\n conn = sqlite3.connect('../Database/Business.db')\n conn.text_factory = str\n c = conn.cursor()\n c.execute('SELECT Event FROM EventTypes')\n locs = [r[0] for r in c.fetchall()]\n conn.close()\n return locs\n\n def handleChanged(self, text):\n modelView = QtGui.QStandardItemModel()\n query = QtSql.QSqlQuery()\n query.exec_(\n \"Select * from BusinessEvents a, EventTypes b where b.Event = '\" +\n text +\n \"' and b.EventTypeID = a.EventTypeID order by ID DESC LIMIT \" +\n str(self.eventSkip) + ',1')\n recCount = 0\n while query.next():\n recCount = recCount + 1\n if query.value(2).toString() != '':\n query_Origin = QtSql.QSqlQuery()\n query_Origin.exec_(\"Select Name from Cities where ID = '\" +\n query.value(2).toString() + \"' LIMIT 1\")\n query_Origin.next()\n modelInputItem = QtGui.QStandardItem('Origin')\n modelInputValue = QtGui.QStandardItem(query_Origin.value(0)\n .toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(3).toString() != '':\n query_Destination = QtSql.QSqlQuery()\n query_Destination.exec_(\n \"Select Name from Cities where ID = '\" + query.value(3)\n .toString() + \"' LIMIT 1\")\n query_Destination.next()\n modelInputItem = QtGui.QStandardItem('Destination')\n modelInputValue = QtGui.QStandardItem(query_Destination.\n value(0).toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(4).toString() != '':\n modelInputItem = QtGui.QStandardItem('Weight')\n modelInputValue = QtGui.QStandardItem(query.value(4).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(5).toString() != '':\n modelInputItem = QtGui.QStandardItem('Volume')\n modelInputValue = QtGui.QStandardItem(query.value(5).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(6).toString() != '':\n modelInputItem = QtGui.QStandardItem('Time of Entry')\n modelInputValue = QtGui.QStandardItem(query.value(6).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(7).toString() != '':\n modelInputItem = QtGui.QStandardItem('Priority')\n modelInputValue = QtGui.QStandardItem(query.value(7).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(8).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per Gram')\n modelInputValue = QtGui.QStandardItem(query.value(8).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(9).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per CC')\n modelInputValue = QtGui.QStandardItem(query.value(9).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(10).toString() != '':\n modelInputItem = QtGui.QStandardItem('Company')\n modelInputValue = QtGui.QStandardItem(query.value(10).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(11).toString() != '':\n modelInputItem = QtGui.QStandardItem('Transport Type')\n modelInputValue = QtGui.QStandardItem(query.value(11).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(12).toString() != '':\n modelInputItem = QtGui.QStandardItem('Day of the Week')\n modelInputValue = QtGui.QStandardItem(query.value(12).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(13).toString() != '':\n modelInputItem = QtGui.QStandardItem('Frequency')\n modelInputValue = QtGui.QStandardItem(query.value(13).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(14).toString() != '':\n modelInputItem = QtGui.QStandardItem('Duration')\n modelInputValue = QtGui.QStandardItem(query.value(14).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if recCount == 0:\n self.label_3.setText(_translate('Form', 'No Records found', None))\n self.inWork = False\n else:\n self.label_3.setText(_translate('Form', '', None))\n self.inWork = True\n self.tb_EventViewer.setModel(modelView)\n\n def clicked_bt_Earlier(self):\n self.eventSkip = self.eventSkip + 1\n self.handleChanged(self.cb_EventType.currentText())\n\n def clicked_bt_Later(self):\n if self.eventSkip > 0:\n self.eventSkip = self.eventSkip - 1\n self.handleChanged(self.cb_EventType.currentText())\n\n\nclass Database:\n\n def __init__(self, parent=None):\n self.data = QtSql.QSqlDatabase.addDatabase('QSQLITE')\n self.data.setDatabaseName('../Database/Business.db')\n self.data.open()\n", "step-3": "<mask token>\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n\n def _fromUtf8(s):\n return s\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\n\nclass Ui_Form(object):\n\n def setupUi(self, Form):\n Form.setObjectName(_fromUtf8('Form'))\n Form.resize(666, 538)\n palette = QtGui.QPalette()\n self.eventSkip = 0\n self.db = Database()\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)\n self.inWork = True\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)\n Form.setPalette(palette)\n self.tb_EventViewer = QtGui.QTableView(Form)\n self.tb_EventViewer.setGeometry(QtCore.QRect(60, 120, 531, 351))\n self.tb_EventViewer.setObjectName(_fromUtf8('tb_EventViewer'))\n self.tb_EventViewer.horizontalHeader().setVisible(False)\n self.tb_EventViewer.verticalHeader().setVisible(False)\n self.bt_Earlier = QtGui.QPushButton(Form)\n self.bt_Earlier.setGeometry(QtCore.QRect(60, 90, 75, 23))\n self.bt_Earlier.setObjectName(_fromUtf8('bt_Earlier'))\n self.bt_Earlier.clicked.connect(self.clicked_bt_Earlier)\n self.bt_Later = QtGui.QPushButton(Form)\n self.bt_Later.setGeometry(QtCore.QRect(510, 90, 75, 23))\n self.bt_Later.setObjectName(_fromUtf8('bt_Later'))\n self.bt_Later.clicked.connect(self.clicked_bt_Later)\n self.label = QtGui.QLabel(Form)\n self.label.setGeometry(QtCore.QRect(70, 0, 511, 41))\n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText,\n brush)\n self.label.setPalette(palette)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8('Segoe UI Light'))\n font.setPointSize(18)\n font.setBold(True)\n font.setWeight(75)\n self.label.setFont(font)\n self.label.setObjectName(_fromUtf8('label'))\n self.cb_EventType = QtGui.QComboBox(Form)\n self.cb_EventType.setGeometry(QtCore.QRect(230, 50, 221, 22))\n self.cb_EventType.setObjectName(_fromUtf8('cb_EventType'))\n self.cb_EventType.currentIndexChanged['QString'].connect(self.\n handleChanged)\n self.label_2 = QtGui.QLabel(Form)\n self.label_2.setGeometry(QtCore.QRect(70, 50, 121, 21))\n self.label_3 = QtGui.QLabel(Form)\n self.label_3.setGeometry(QtCore.QRect(190, 90, 221, 21))\n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText,\n brush)\n self.label_2.setPalette(palette)\n self.label_3.setPalette(palette)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8('Segoe UI'))\n font.setPointSize(12)\n self.label_2.setFont(font)\n self.label_2.setObjectName(_fromUtf8('label_2'))\n self.label_3.setFont(font)\n self.label_3.setObjectName(_fromUtf8('label_3'))\n self.retranslateUi(Form)\n QtCore.QMetaObject.connectSlotsByName(Form)\n self.initialize()\n\n def retranslateUi(self, Form):\n Form.setWindowTitle(_translate('Form', 'Revisit business events', None)\n )\n self.bt_Earlier.setText(_translate('Form', '<<', None))\n self.bt_Later.setText(_translate('Form', '>>', None))\n self.label.setText(_translate('Form', 'Revisit business events', None))\n self.label_2.setText(_translate('Form', 'Select Event Type', None))\n\n def initialize(self):\n self.cb_EventType.addItems(self.getBusinessEventsType())\n\n def getBusinessEventsType(self):\n conn = sqlite3.connect('../Database/Business.db')\n conn.text_factory = str\n c = conn.cursor()\n c.execute('SELECT Event FROM EventTypes')\n locs = [r[0] for r in c.fetchall()]\n conn.close()\n return locs\n\n def handleChanged(self, text):\n modelView = QtGui.QStandardItemModel()\n query = QtSql.QSqlQuery()\n query.exec_(\n \"Select * from BusinessEvents a, EventTypes b where b.Event = '\" +\n text +\n \"' and b.EventTypeID = a.EventTypeID order by ID DESC LIMIT \" +\n str(self.eventSkip) + ',1')\n recCount = 0\n while query.next():\n recCount = recCount + 1\n if query.value(2).toString() != '':\n query_Origin = QtSql.QSqlQuery()\n query_Origin.exec_(\"Select Name from Cities where ID = '\" +\n query.value(2).toString() + \"' LIMIT 1\")\n query_Origin.next()\n modelInputItem = QtGui.QStandardItem('Origin')\n modelInputValue = QtGui.QStandardItem(query_Origin.value(0)\n .toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(3).toString() != '':\n query_Destination = QtSql.QSqlQuery()\n query_Destination.exec_(\n \"Select Name from Cities where ID = '\" + query.value(3)\n .toString() + \"' LIMIT 1\")\n query_Destination.next()\n modelInputItem = QtGui.QStandardItem('Destination')\n modelInputValue = QtGui.QStandardItem(query_Destination.\n value(0).toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(4).toString() != '':\n modelInputItem = QtGui.QStandardItem('Weight')\n modelInputValue = QtGui.QStandardItem(query.value(4).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(5).toString() != '':\n modelInputItem = QtGui.QStandardItem('Volume')\n modelInputValue = QtGui.QStandardItem(query.value(5).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(6).toString() != '':\n modelInputItem = QtGui.QStandardItem('Time of Entry')\n modelInputValue = QtGui.QStandardItem(query.value(6).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(7).toString() != '':\n modelInputItem = QtGui.QStandardItem('Priority')\n modelInputValue = QtGui.QStandardItem(query.value(7).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(8).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per Gram')\n modelInputValue = QtGui.QStandardItem(query.value(8).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(9).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per CC')\n modelInputValue = QtGui.QStandardItem(query.value(9).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(10).toString() != '':\n modelInputItem = QtGui.QStandardItem('Company')\n modelInputValue = QtGui.QStandardItem(query.value(10).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(11).toString() != '':\n modelInputItem = QtGui.QStandardItem('Transport Type')\n modelInputValue = QtGui.QStandardItem(query.value(11).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(12).toString() != '':\n modelInputItem = QtGui.QStandardItem('Day of the Week')\n modelInputValue = QtGui.QStandardItem(query.value(12).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(13).toString() != '':\n modelInputItem = QtGui.QStandardItem('Frequency')\n modelInputValue = QtGui.QStandardItem(query.value(13).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(14).toString() != '':\n modelInputItem = QtGui.QStandardItem('Duration')\n modelInputValue = QtGui.QStandardItem(query.value(14).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if recCount == 0:\n self.label_3.setText(_translate('Form', 'No Records found', None))\n self.inWork = False\n else:\n self.label_3.setText(_translate('Form', '', None))\n self.inWork = True\n self.tb_EventViewer.setModel(modelView)\n\n def clicked_bt_Earlier(self):\n self.eventSkip = self.eventSkip + 1\n self.handleChanged(self.cb_EventType.currentText())\n\n def clicked_bt_Later(self):\n if self.eventSkip > 0:\n self.eventSkip = self.eventSkip - 1\n self.handleChanged(self.cb_EventType.currentText())\n\n\nclass Database:\n\n def __init__(self, parent=None):\n self.data = QtSql.QSqlDatabase.addDatabase('QSQLITE')\n self.data.setDatabaseName('../Database/Business.db')\n self.data.open()\n", "step-4": "from PyQt4 import QtCore, QtGui, QtSql\nimport sqlite3\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n\n def _fromUtf8(s):\n return s\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\n\nclass Ui_Form(object):\n\n def setupUi(self, Form):\n Form.setObjectName(_fromUtf8('Form'))\n Form.resize(666, 538)\n palette = QtGui.QPalette()\n self.eventSkip = 0\n self.db = Database()\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)\n self.inWork = True\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)\n Form.setPalette(palette)\n self.tb_EventViewer = QtGui.QTableView(Form)\n self.tb_EventViewer.setGeometry(QtCore.QRect(60, 120, 531, 351))\n self.tb_EventViewer.setObjectName(_fromUtf8('tb_EventViewer'))\n self.tb_EventViewer.horizontalHeader().setVisible(False)\n self.tb_EventViewer.verticalHeader().setVisible(False)\n self.bt_Earlier = QtGui.QPushButton(Form)\n self.bt_Earlier.setGeometry(QtCore.QRect(60, 90, 75, 23))\n self.bt_Earlier.setObjectName(_fromUtf8('bt_Earlier'))\n self.bt_Earlier.clicked.connect(self.clicked_bt_Earlier)\n self.bt_Later = QtGui.QPushButton(Form)\n self.bt_Later.setGeometry(QtCore.QRect(510, 90, 75, 23))\n self.bt_Later.setObjectName(_fromUtf8('bt_Later'))\n self.bt_Later.clicked.connect(self.clicked_bt_Later)\n self.label = QtGui.QLabel(Form)\n self.label.setGeometry(QtCore.QRect(70, 0, 511, 41))\n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText,\n brush)\n self.label.setPalette(palette)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8('Segoe UI Light'))\n font.setPointSize(18)\n font.setBold(True)\n font.setWeight(75)\n self.label.setFont(font)\n self.label.setObjectName(_fromUtf8('label'))\n self.cb_EventType = QtGui.QComboBox(Form)\n self.cb_EventType.setGeometry(QtCore.QRect(230, 50, 221, 22))\n self.cb_EventType.setObjectName(_fromUtf8('cb_EventType'))\n self.cb_EventType.currentIndexChanged['QString'].connect(self.\n handleChanged)\n self.label_2 = QtGui.QLabel(Form)\n self.label_2.setGeometry(QtCore.QRect(70, 50, 121, 21))\n self.label_3 = QtGui.QLabel(Form)\n self.label_3.setGeometry(QtCore.QRect(190, 90, 221, 21))\n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText,\n brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText,\n brush)\n self.label_2.setPalette(palette)\n self.label_3.setPalette(palette)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8('Segoe UI'))\n font.setPointSize(12)\n self.label_2.setFont(font)\n self.label_2.setObjectName(_fromUtf8('label_2'))\n self.label_3.setFont(font)\n self.label_3.setObjectName(_fromUtf8('label_3'))\n self.retranslateUi(Form)\n QtCore.QMetaObject.connectSlotsByName(Form)\n self.initialize()\n\n def retranslateUi(self, Form):\n Form.setWindowTitle(_translate('Form', 'Revisit business events', None)\n )\n self.bt_Earlier.setText(_translate('Form', '<<', None))\n self.bt_Later.setText(_translate('Form', '>>', None))\n self.label.setText(_translate('Form', 'Revisit business events', None))\n self.label_2.setText(_translate('Form', 'Select Event Type', None))\n\n def initialize(self):\n self.cb_EventType.addItems(self.getBusinessEventsType())\n\n def getBusinessEventsType(self):\n conn = sqlite3.connect('../Database/Business.db')\n conn.text_factory = str\n c = conn.cursor()\n c.execute('SELECT Event FROM EventTypes')\n locs = [r[0] for r in c.fetchall()]\n conn.close()\n return locs\n\n def handleChanged(self, text):\n modelView = QtGui.QStandardItemModel()\n query = QtSql.QSqlQuery()\n query.exec_(\n \"Select * from BusinessEvents a, EventTypes b where b.Event = '\" +\n text +\n \"' and b.EventTypeID = a.EventTypeID order by ID DESC LIMIT \" +\n str(self.eventSkip) + ',1')\n recCount = 0\n while query.next():\n recCount = recCount + 1\n if query.value(2).toString() != '':\n query_Origin = QtSql.QSqlQuery()\n query_Origin.exec_(\"Select Name from Cities where ID = '\" +\n query.value(2).toString() + \"' LIMIT 1\")\n query_Origin.next()\n modelInputItem = QtGui.QStandardItem('Origin')\n modelInputValue = QtGui.QStandardItem(query_Origin.value(0)\n .toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(3).toString() != '':\n query_Destination = QtSql.QSqlQuery()\n query_Destination.exec_(\n \"Select Name from Cities where ID = '\" + query.value(3)\n .toString() + \"' LIMIT 1\")\n query_Destination.next()\n modelInputItem = QtGui.QStandardItem('Destination')\n modelInputValue = QtGui.QStandardItem(query_Destination.\n value(0).toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(4).toString() != '':\n modelInputItem = QtGui.QStandardItem('Weight')\n modelInputValue = QtGui.QStandardItem(query.value(4).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(5).toString() != '':\n modelInputItem = QtGui.QStandardItem('Volume')\n modelInputValue = QtGui.QStandardItem(query.value(5).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(6).toString() != '':\n modelInputItem = QtGui.QStandardItem('Time of Entry')\n modelInputValue = QtGui.QStandardItem(query.value(6).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(7).toString() != '':\n modelInputItem = QtGui.QStandardItem('Priority')\n modelInputValue = QtGui.QStandardItem(query.value(7).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(8).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per Gram')\n modelInputValue = QtGui.QStandardItem(query.value(8).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(9).toString() != '':\n modelInputItem = QtGui.QStandardItem('Price Per CC')\n modelInputValue = QtGui.QStandardItem(query.value(9).toString()\n )\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(10).toString() != '':\n modelInputItem = QtGui.QStandardItem('Company')\n modelInputValue = QtGui.QStandardItem(query.value(10).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(11).toString() != '':\n modelInputItem = QtGui.QStandardItem('Transport Type')\n modelInputValue = QtGui.QStandardItem(query.value(11).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(12).toString() != '':\n modelInputItem = QtGui.QStandardItem('Day of the Week')\n modelInputValue = QtGui.QStandardItem(query.value(12).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(13).toString() != '':\n modelInputItem = QtGui.QStandardItem('Frequency')\n modelInputValue = QtGui.QStandardItem(query.value(13).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if query.value(14).toString() != '':\n modelInputItem = QtGui.QStandardItem('Duration')\n modelInputValue = QtGui.QStandardItem(query.value(14).\n toString())\n modelView.appendRow([modelInputItem, modelInputValue])\n if recCount == 0:\n self.label_3.setText(_translate('Form', 'No Records found', None))\n self.inWork = False\n else:\n self.label_3.setText(_translate('Form', '', None))\n self.inWork = True\n self.tb_EventViewer.setModel(modelView)\n\n def clicked_bt_Earlier(self):\n self.eventSkip = self.eventSkip + 1\n self.handleChanged(self.cb_EventType.currentText())\n\n def clicked_bt_Later(self):\n if self.eventSkip > 0:\n self.eventSkip = self.eventSkip - 1\n self.handleChanged(self.cb_EventType.currentText())\n\n\nclass Database:\n\n def __init__(self, parent=None):\n self.data = QtSql.QSqlDatabase.addDatabase('QSQLITE')\n self.data.setDatabaseName('../Database/Business.db')\n self.data.open()\n", "step-5": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'KPS_RevisitBusinessEvents.ui'\n#\n# Created: Sun May 18 14:50:49 2014\n# by: PyQt4 UI code generator 4.10.4\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui, QtSql\nimport sqlite3\n\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_Form(object):\n \n \n def setupUi(self, Form):\n Form.setObjectName(_fromUtf8(\"Form\"))\n Form.resize(666, 538)\n palette = QtGui.QPalette()\n self.eventSkip = 0;\n self.db = Database()\n \n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern) \n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush)\n \n self.inWork = True\n \n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern) \n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush)\n \n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n \n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n \n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)\n brush = QtGui.QBrush(QtGui.QColor(8, 129, 2))\n brush.setStyle(QtCore.Qt.SolidPattern)\n \n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush)\n Form.setPalette(palette)\n self.tb_EventViewer = QtGui.QTableView(Form)\n self.tb_EventViewer.setGeometry(QtCore.QRect(60, 120, 531, 351))\n self.tb_EventViewer.setObjectName(_fromUtf8(\"tb_EventViewer\"))\n self.tb_EventViewer.horizontalHeader().setVisible(False)\n self.tb_EventViewer.verticalHeader().setVisible(False)\n # self.tb_EventViewer.setColumnCount(0)\n # self.tb_EventViewer.setRowCount(0)\n self.bt_Earlier = QtGui.QPushButton(Form)\n self.bt_Earlier.setGeometry(QtCore.QRect(60, 90, 75, 23))\n self.bt_Earlier.setObjectName(_fromUtf8(\"bt_Earlier\"))\n self.bt_Earlier.clicked.connect(self.clicked_bt_Earlier)\n \n \n self.bt_Later = QtGui.QPushButton(Form)\n self.bt_Later.setGeometry(QtCore.QRect(510, 90, 75, 23))\n self.bt_Later.setObjectName(_fromUtf8(\"bt_Later\"))\n self.bt_Later.clicked.connect(self.clicked_bt_Later)\n \n self.label = QtGui.QLabel(Form)\n self.label.setGeometry(QtCore.QRect(70, 0, 511, 41))\n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.ButtonText, brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.ButtonText, brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.ButtonText, brush)\n self.label.setPalette(palette)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"Segoe UI Light\"))\n font.setPointSize(18)\n font.setBold(True)\n font.setWeight(75)\n self.label.setFont(font)\n self.label.setObjectName(_fromUtf8(\"label\"))\n self.cb_EventType = QtGui.QComboBox(Form)\n self.cb_EventType.setGeometry(QtCore.QRect(230, 50, 221, 22))\n self.cb_EventType.setObjectName(_fromUtf8(\"cb_EventType\")) \n self.cb_EventType.currentIndexChanged['QString'].connect(self.handleChanged) \n self.label_2 = QtGui.QLabel(Form)\n self.label_2.setGeometry(QtCore.QRect(70, 50, 121, 21))\n \n self.label_3 = QtGui.QLabel(Form)\n self.label_3.setGeometry(QtCore.QRect(190, 90, 221, 21))\n \n palette = QtGui.QPalette()\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)\n brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)\n brush = QtGui.QBrush(QtGui.QColor(120, 120, 120))\n brush.setStyle(QtCore.Qt.SolidPattern)\n palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)\n self.label_2.setPalette(palette)\n self.label_3.setPalette(palette)\n font = QtGui.QFont()\n font.setFamily(_fromUtf8(\"Segoe UI\"))\n font.setPointSize(12)\n self.label_2.setFont(font)\n self.label_2.setObjectName(_fromUtf8(\"label_2\"))\n self.label_3.setFont(font)\n self.label_3.setObjectName(_fromUtf8(\"label_3\"))\n\n self.retranslateUi(Form)\n QtCore.QMetaObject.connectSlotsByName(Form)\n self.initialize()\n\n def retranslateUi(self, Form):\n Form.setWindowTitle(_translate(\"Form\", \"Revisit business events\", None))\n self.bt_Earlier.setText(_translate(\"Form\", \"<<\", None))\n self.bt_Later.setText(_translate(\"Form\", \">>\", None))\n self.label.setText(_translate(\"Form\", \"Revisit business events\", None))\n self.label_2.setText(_translate(\"Form\", \"Select Event Type\", None))\n \n \n def initialize(self):\n self.cb_EventType.addItems(self.getBusinessEventsType())\n # self.cb_Destination.addItems(RH.getLocations())\n \n def getBusinessEventsType(self):\n conn = sqlite3.connect(\"../Database/Business.db\")\n conn.text_factory = str\n c = conn.cursor()\n c.execute('SELECT Event FROM EventTypes')\n locs = [r[0] for r in c.fetchall()]\n conn.close()\n return locs\n \n def handleChanged(self, text):\n modelView = QtGui.QStandardItemModel()\n query = QtSql.QSqlQuery()\n\n query.exec_(\"Select * from BusinessEvents a, EventTypes b where b.Event = '\" + text + \"' and b.EventTypeID = a.EventTypeID order by ID DESC LIMIT \" + str(self.eventSkip) + \",1\")\n recCount = 0;\n \n while query.next():\n recCount = recCount + 1\n if query.value(2).toString() != '':\n query_Origin = QtSql.QSqlQuery()\n query_Origin.exec_(\"Select Name from Cities where ID = '\" + query.value(2).toString() + \"' LIMIT 1\")\n query_Origin.next()\n modelInputItem = QtGui.QStandardItem(\"Origin\")\n modelInputValue = QtGui.QStandardItem(query_Origin.value(0).toString())\n modelView.appendRow([modelInputItem,modelInputValue])\n if query.value(3).toString() != '':\n query_Destination = QtSql.QSqlQuery()\n query_Destination.exec_(\"Select Name from Cities where ID = '\" + query.value(3).toString() + \"' LIMIT 1\")\n query_Destination.next()\n modelInputItem = QtGui.QStandardItem(\"Destination\")\n modelInputValue = QtGui.QStandardItem(query_Destination.value(0).toString())\n modelView.appendRow([modelInputItem,modelInputValue]) \n if query.value(4).toString() != '':\n modelInputItem = QtGui.QStandardItem(\"Weight\")\n modelInputValue = QtGui.QStandardItem(query.value(4).toString())\n modelView.appendRow([modelInputItem,modelInputValue]) \n if query.value(5).toString() != '':\n modelInputItem = QtGui.QStandardItem(\"Volume\")\n modelInputValue = QtGui.QStandardItem(query.value(5).toString())\n modelView.appendRow([modelInputItem,modelInputValue]) \n if query.value(6).toString() != '':\n modelInputItem = QtGui.QStandardItem(\"Time of Entry\")\n modelInputValue = QtGui.QStandardItem(query.value(6).toString())\n modelView.appendRow([modelInputItem,modelInputValue])\n if query.value(7).toString() != '':\n modelInputItem = QtGui.QStandardItem(\"Priority\")\n modelInputValue = QtGui.QStandardItem(query.value(7).toString())\n modelView.appendRow([modelInputItem,modelInputValue])\n if query.value(8).toString() != '':\n modelInputItem = QtGui.QStandardItem(\"Price Per Gram\")\n modelInputValue = QtGui.QStandardItem(query.value(8).toString())\n modelView.appendRow([modelInputItem,modelInputValue])\n if query.value(9).toString() != '':\n modelInputItem = QtGui.QStandardItem(\"Price Per CC\")\n modelInputValue = QtGui.QStandardItem(query.value(9).toString())\n modelView.appendRow([modelInputItem,modelInputValue]) \n if query.value(10).toString() != '':\n modelInputItem = QtGui.QStandardItem(\"Company\")\n modelInputValue = QtGui.QStandardItem(query.value(10).toString())\n modelView.appendRow([modelInputItem,modelInputValue]) \n if query.value(11).toString() != '':\n modelInputItem = QtGui.QStandardItem(\"Transport Type\")\n modelInputValue = QtGui.QStandardItem(query.value(11).toString())\n modelView.appendRow([modelInputItem,modelInputValue]) \n if query.value(12).toString() != '':\n modelInputItem = QtGui.QStandardItem(\"Day of the Week\")\n modelInputValue = QtGui.QStandardItem(query.value(12).toString())\n modelView.appendRow([modelInputItem,modelInputValue]) \n if query.value(13).toString() != '':\n modelInputItem = QtGui.QStandardItem(\"Frequency\")\n modelInputValue = QtGui.QStandardItem(query.value(13).toString())\n modelView.appendRow([modelInputItem,modelInputValue]) \n if query.value(14).toString() != '':\n modelInputItem = QtGui.QStandardItem(\"Duration\")\n modelInputValue = QtGui.QStandardItem(query.value(14).toString())\n modelView.appendRow([modelInputItem,modelInputValue]) \n #modelInputValue = QtGui.QStandardItem('Value')\n # modelView.appendRow([modelInputItem,modelInputValue])\n if recCount == 0:\n self.label_3.setText(_translate(\"Form\", \"No Records found\", None))\n self.inWork = False\n else:\n self.label_3.setText(_translate(\"Form\", \"\", None))\n self.inWork = True\n \n self.tb_EventViewer.setModel(modelView)\n \n def clicked_bt_Earlier(self):\n self.eventSkip = self.eventSkip + 1\n self.handleChanged(self.cb_EventType.currentText())\n \n def clicked_bt_Later(self):\n if self.eventSkip > 0:\n self.eventSkip = self.eventSkip - 1 \n self.handleChanged(self.cb_EventType.currentText())\n \nclass Database:\n def __init__(self, parent = None):\n self.data = QtSql.QSqlDatabase.addDatabase(\"QSQLITE\")\n self.data.setDatabaseName(\"../Database/Business.db\")\n self.data.open()\n", "step-ids": [ 8, 10, 11, 12, 13 ] }
[ 8, 10, 11, 12, 13 ]
import numpy as np from math import * from visual import * from visual.graph import * def energy2(n): return ((n*h/L)**2)/(8*m)*convert def factorial(n): out=1 for x in range(n): out=out*(x+1) return out def bosonconfigs(numelvl,numpart): x=numpart n=numelvl out=choose(x+n-1,x) return out def choose(choices,x): if choices>=x: out=int(factorial(choices)/((factorial(x)*factorial(choices-x)))) else: out=0 return out def configs(x,elvl,particle="boson",out=None): """ Generate configs for bosons or fermions. Parameters ---------- x : positive integer Number of particles in the system Energylvls : 1-D array List of valid energy states of the system particle : "boson" or "fermion" out : 1-D array Array to put configs in Returns ------- out : 1-D array array of total energys of all valid configurations """ dtype = elvl.dtype n=elvl.size #number of energy levels if particle=="boson": if out is None: out=None out = np.zeros(bosonconfigs(n,x), dtype=dtype) if x==1: for i in range(n): out[i]=elvl[i] if x>1: k=0 #index for end of last input added for m in range(n): #m is the energy level index end=k+bosonconfigs(n-m,x-1) #last energy level configs(x-1, elvl[m:],particle,out[k:end]) for i in range(k,end): out[i]+= elvl[m] k=end return out if particle=="fermion": if out is None: out=None out = np.zeros(choose(n,x), dtype=dtype) if x==1: for i in range(n): out[i]=elvl[i] if x>1: k=0 #index for end of last input added for m in range(n): #m is the energy level index end=k+choose(n-(m+1),x-1) #last energy level configs(x-1, elvl[m+1:],particle,out[k:end]) for i in range(k,end): out[i]+= elvl[m] k=end return out h = 6.62606957 * 10 ** -34 #Plank's constant #m = 1.67492735174 * 10 ** -27 #this is mass of neutron m = 9.11 * 10**-31 #this is mass of electron L = 0.39 * 10**-9 #size of box convert = 6.24150934 * 10**18 maximum = 100 kb = 1.3806488 * 10**-23 energylevels = np.fromiter((((x*h/L)**2)/(8*m)*convert for x in range(maximum+1)),dtype=float) #this creates the entire table of energy levels as a single list def oneDEnergy(n): energylevels = np.fromiter((((x*h/L)**2)/(8*m) for x in range(1,n+1)),dtype=float) return energylevels #this creates the entire table of energy levels as a single list def ThreeDEnergy(n): out=np.empty(n**3) index=0 for i in range(1,n+1): for j in range(1,n+1): for k in range(1,n+1): out[index]=((i*h/L)**2+(j*h/L)**2+(k*h/L)**2)/(8*m)*convert index=index+1 return np.sort(out) def fermion(n): energycount = [] energy = oneDEnergy(maximum) fermionlist = configs(n,energy,'fermion') for config in np.nditer(fermionlist): if config < energy[-1] + (n-1)*energy[0]: energycount.append(config) #return number of configurations in energy range fnc1 = ghistogram(bins = np.linspace(min(energycount), max(energycount), 100), color = color.red) fnc1.plot(data=energycount) hist, binedges = np.histogram(energycount,bins = 100,weights = None, density = False) return (hist,binedges) def boson(n,nthElvl,acc): ''' n is the number of particles nthElvl is the nth energy level to go up to acc is integer of histogram(s) ''' Elvl= oneDEnergy(nthElvl) #print Elvl econf= np.sort(configs(n, Elvl, particle="boson")) max_energy=Elvl[-1]+(n-1)*Elvl[0] #np.sort(econf) fcn1 = ghistogram(bins = np.linspace(econf[0],max_energy,acc)) bound=True m=0 while bound==True: if econf[m]>max_energy: bound=False else: m=m+1 if m==econf.size: break fcn1.plot(data=econf[:m]) hist, binedges = np.histogram(econf[:m],bins = 100,weights = None, density = False) return (hist,binedges) def boltzfit(xvalues,yvalues,degree): xlist = [] #ylist = [] for i in range(len(xvalues)-1): xlist.append((xvalues[i] + xvalues[i+1])/(2)) #Average energy in joules #for j in range(len(yvalues)): #ylist.append(kb*log(yvalues[j])) #Convert to boltzmann entropy return np.polyfit(xlist,yvalues,degree) def gibbsfit(xvalues,yvalues,degree): for j in range(len(yvalues)): #generate gibbs configurations if j > 0: yvalues[j] = yvalues[j-1] + yvalues[j] #for j in range(len(yvalues)): #ylist.append(kb*log(yvalues[j])) #Convert to entropy return np.polyfit(xvalues[1:],yvalues,degree) def conequation(n,degree,particle ='boson',method ='gibbs'): if particle == 'boson': data = boson(n, maximum, 100) if particle == 'fermion': data = fermion(n) print (data) if method == 'boltzmann': return (boltzfit(data[1],data[0],degree)) if method == 'gibbs': return (gibbsfit(data[1],data[0],degree))
normal
{ "blob_id": "42f656898481768ea0bf1ca0b6afbe06de9dd597", "index": 4132, "step-1": "<mask token>\n\n\ndef energy2(n):\n return (n * h / L) ** 2 / (8 * m) * convert\n\n\ndef factorial(n):\n out = 1\n for x in range(n):\n out = out * (x + 1)\n return out\n\n\n<mask token>\n\n\ndef configs(x, elvl, particle='boson', out=None):\n \"\"\"\n Generate configs for bosons or fermions.\n\n Parameters\n ----------\n x : positive integer\n Number of particles in the system\n Energylvls : 1-D array\n List of valid energy states of the system\n particle : \"boson\" or \"fermion\"\n out : 1-D array\n Array to put configs in\n\n Returns\n -------\n out : 1-D array\n array of total energys of all valid configurations\n\n \"\"\"\n dtype = elvl.dtype\n n = elvl.size\n if particle == 'boson':\n if out is None:\n out = None\n out = np.zeros(bosonconfigs(n, x), dtype=dtype)\n if x == 1:\n for i in range(n):\n out[i] = elvl[i]\n if x > 1:\n k = 0\n for m in range(n):\n end = k + bosonconfigs(n - m, x - 1)\n configs(x - 1, elvl[m:], particle, out[k:end])\n for i in range(k, end):\n out[i] += elvl[m]\n k = end\n return out\n if particle == 'fermion':\n if out is None:\n out = None\n out = np.zeros(choose(n, x), dtype=dtype)\n if x == 1:\n for i in range(n):\n out[i] = elvl[i]\n if x > 1:\n k = 0\n for m in range(n):\n end = k + choose(n - (m + 1), x - 1)\n configs(x - 1, elvl[m + 1:], particle, out[k:end])\n for i in range(k, end):\n out[i] += elvl[m]\n k = end\n return out\n\n\n<mask token>\n\n\ndef oneDEnergy(n):\n energylevels = np.fromiter(((x * h / L) ** 2 / (8 * m) for x in range(1,\n n + 1)), dtype=float)\n return energylevels\n\n\ndef ThreeDEnergy(n):\n out = np.empty(n ** 3)\n index = 0\n for i in range(1, n + 1):\n for j in range(1, n + 1):\n for k in range(1, n + 1):\n out[index] = ((i * h / L) ** 2 + (j * h / L) ** 2 + (k * h /\n L) ** 2) / (8 * m) * convert\n index = index + 1\n return np.sort(out)\n\n\ndef fermion(n):\n energycount = []\n energy = oneDEnergy(maximum)\n fermionlist = configs(n, energy, 'fermion')\n for config in np.nditer(fermionlist):\n if config < energy[-1] + (n - 1) * energy[0]:\n energycount.append(config)\n fnc1 = ghistogram(bins=np.linspace(min(energycount), max(energycount), \n 100), color=color.red)\n fnc1.plot(data=energycount)\n hist, binedges = np.histogram(energycount, bins=100, weights=None,\n density=False)\n return hist, binedges\n\n\n<mask token>\n\n\ndef conequation(n, degree, particle='boson', method='gibbs'):\n if particle == 'boson':\n data = boson(n, maximum, 100)\n if particle == 'fermion':\n data = fermion(n)\n print(data)\n if method == 'boltzmann':\n return boltzfit(data[1], data[0], degree)\n if method == 'gibbs':\n return gibbsfit(data[1], data[0], degree)\n", "step-2": "<mask token>\n\n\ndef energy2(n):\n return (n * h / L) ** 2 / (8 * m) * convert\n\n\ndef factorial(n):\n out = 1\n for x in range(n):\n out = out * (x + 1)\n return out\n\n\ndef bosonconfigs(numelvl, numpart):\n x = numpart\n n = numelvl\n out = choose(x + n - 1, x)\n return out\n\n\ndef choose(choices, x):\n if choices >= x:\n out = int(factorial(choices) / (factorial(x) * factorial(choices - x)))\n else:\n out = 0\n return out\n\n\ndef configs(x, elvl, particle='boson', out=None):\n \"\"\"\n Generate configs for bosons or fermions.\n\n Parameters\n ----------\n x : positive integer\n Number of particles in the system\n Energylvls : 1-D array\n List of valid energy states of the system\n particle : \"boson\" or \"fermion\"\n out : 1-D array\n Array to put configs in\n\n Returns\n -------\n out : 1-D array\n array of total energys of all valid configurations\n\n \"\"\"\n dtype = elvl.dtype\n n = elvl.size\n if particle == 'boson':\n if out is None:\n out = None\n out = np.zeros(bosonconfigs(n, x), dtype=dtype)\n if x == 1:\n for i in range(n):\n out[i] = elvl[i]\n if x > 1:\n k = 0\n for m in range(n):\n end = k + bosonconfigs(n - m, x - 1)\n configs(x - 1, elvl[m:], particle, out[k:end])\n for i in range(k, end):\n out[i] += elvl[m]\n k = end\n return out\n if particle == 'fermion':\n if out is None:\n out = None\n out = np.zeros(choose(n, x), dtype=dtype)\n if x == 1:\n for i in range(n):\n out[i] = elvl[i]\n if x > 1:\n k = 0\n for m in range(n):\n end = k + choose(n - (m + 1), x - 1)\n configs(x - 1, elvl[m + 1:], particle, out[k:end])\n for i in range(k, end):\n out[i] += elvl[m]\n k = end\n return out\n\n\n<mask token>\n\n\ndef oneDEnergy(n):\n energylevels = np.fromiter(((x * h / L) ** 2 / (8 * m) for x in range(1,\n n + 1)), dtype=float)\n return energylevels\n\n\ndef ThreeDEnergy(n):\n out = np.empty(n ** 3)\n index = 0\n for i in range(1, n + 1):\n for j in range(1, n + 1):\n for k in range(1, n + 1):\n out[index] = ((i * h / L) ** 2 + (j * h / L) ** 2 + (k * h /\n L) ** 2) / (8 * m) * convert\n index = index + 1\n return np.sort(out)\n\n\ndef fermion(n):\n energycount = []\n energy = oneDEnergy(maximum)\n fermionlist = configs(n, energy, 'fermion')\n for config in np.nditer(fermionlist):\n if config < energy[-1] + (n - 1) * energy[0]:\n energycount.append(config)\n fnc1 = ghistogram(bins=np.linspace(min(energycount), max(energycount), \n 100), color=color.red)\n fnc1.plot(data=energycount)\n hist, binedges = np.histogram(energycount, bins=100, weights=None,\n density=False)\n return hist, binedges\n\n\n<mask token>\n\n\ndef gibbsfit(xvalues, yvalues, degree):\n for j in range(len(yvalues)):\n if j > 0:\n yvalues[j] = yvalues[j - 1] + yvalues[j]\n return np.polyfit(xvalues[1:], yvalues, degree)\n\n\ndef conequation(n, degree, particle='boson', method='gibbs'):\n if particle == 'boson':\n data = boson(n, maximum, 100)\n if particle == 'fermion':\n data = fermion(n)\n print(data)\n if method == 'boltzmann':\n return boltzfit(data[1], data[0], degree)\n if method == 'gibbs':\n return gibbsfit(data[1], data[0], degree)\n", "step-3": "<mask token>\n\n\ndef energy2(n):\n return (n * h / L) ** 2 / (8 * m) * convert\n\n\ndef factorial(n):\n out = 1\n for x in range(n):\n out = out * (x + 1)\n return out\n\n\ndef bosonconfigs(numelvl, numpart):\n x = numpart\n n = numelvl\n out = choose(x + n - 1, x)\n return out\n\n\ndef choose(choices, x):\n if choices >= x:\n out = int(factorial(choices) / (factorial(x) * factorial(choices - x)))\n else:\n out = 0\n return out\n\n\ndef configs(x, elvl, particle='boson', out=None):\n \"\"\"\n Generate configs for bosons or fermions.\n\n Parameters\n ----------\n x : positive integer\n Number of particles in the system\n Energylvls : 1-D array\n List of valid energy states of the system\n particle : \"boson\" or \"fermion\"\n out : 1-D array\n Array to put configs in\n\n Returns\n -------\n out : 1-D array\n array of total energys of all valid configurations\n\n \"\"\"\n dtype = elvl.dtype\n n = elvl.size\n if particle == 'boson':\n if out is None:\n out = None\n out = np.zeros(bosonconfigs(n, x), dtype=dtype)\n if x == 1:\n for i in range(n):\n out[i] = elvl[i]\n if x > 1:\n k = 0\n for m in range(n):\n end = k + bosonconfigs(n - m, x - 1)\n configs(x - 1, elvl[m:], particle, out[k:end])\n for i in range(k, end):\n out[i] += elvl[m]\n k = end\n return out\n if particle == 'fermion':\n if out is None:\n out = None\n out = np.zeros(choose(n, x), dtype=dtype)\n if x == 1:\n for i in range(n):\n out[i] = elvl[i]\n if x > 1:\n k = 0\n for m in range(n):\n end = k + choose(n - (m + 1), x - 1)\n configs(x - 1, elvl[m + 1:], particle, out[k:end])\n for i in range(k, end):\n out[i] += elvl[m]\n k = end\n return out\n\n\n<mask token>\n\n\ndef oneDEnergy(n):\n energylevels = np.fromiter(((x * h / L) ** 2 / (8 * m) for x in range(1,\n n + 1)), dtype=float)\n return energylevels\n\n\ndef ThreeDEnergy(n):\n out = np.empty(n ** 3)\n index = 0\n for i in range(1, n + 1):\n for j in range(1, n + 1):\n for k in range(1, n + 1):\n out[index] = ((i * h / L) ** 2 + (j * h / L) ** 2 + (k * h /\n L) ** 2) / (8 * m) * convert\n index = index + 1\n return np.sort(out)\n\n\ndef fermion(n):\n energycount = []\n energy = oneDEnergy(maximum)\n fermionlist = configs(n, energy, 'fermion')\n for config in np.nditer(fermionlist):\n if config < energy[-1] + (n - 1) * energy[0]:\n energycount.append(config)\n fnc1 = ghistogram(bins=np.linspace(min(energycount), max(energycount), \n 100), color=color.red)\n fnc1.plot(data=energycount)\n hist, binedges = np.histogram(energycount, bins=100, weights=None,\n density=False)\n return hist, binedges\n\n\ndef boson(n, nthElvl, acc):\n \"\"\"\n n is the number of particles\n nthElvl is the nth energy level to go up to\n acc is integer of histogram(s)\n \"\"\"\n Elvl = oneDEnergy(nthElvl)\n econf = np.sort(configs(n, Elvl, particle='boson'))\n max_energy = Elvl[-1] + (n - 1) * Elvl[0]\n fcn1 = ghistogram(bins=np.linspace(econf[0], max_energy, acc))\n bound = True\n m = 0\n while bound == True:\n if econf[m] > max_energy:\n bound = False\n else:\n m = m + 1\n if m == econf.size:\n break\n fcn1.plot(data=econf[:m])\n hist, binedges = np.histogram(econf[:m], bins=100, weights=None,\n density=False)\n return hist, binedges\n\n\ndef boltzfit(xvalues, yvalues, degree):\n xlist = []\n for i in range(len(xvalues) - 1):\n xlist.append((xvalues[i] + xvalues[i + 1]) / 2)\n return np.polyfit(xlist, yvalues, degree)\n\n\ndef gibbsfit(xvalues, yvalues, degree):\n for j in range(len(yvalues)):\n if j > 0:\n yvalues[j] = yvalues[j - 1] + yvalues[j]\n return np.polyfit(xvalues[1:], yvalues, degree)\n\n\ndef conequation(n, degree, particle='boson', method='gibbs'):\n if particle == 'boson':\n data = boson(n, maximum, 100)\n if particle == 'fermion':\n data = fermion(n)\n print(data)\n if method == 'boltzmann':\n return boltzfit(data[1], data[0], degree)\n if method == 'gibbs':\n return gibbsfit(data[1], data[0], degree)\n", "step-4": "import numpy as np\nfrom math import *\nfrom visual import *\nfrom visual.graph import *\n\n\ndef energy2(n):\n return (n * h / L) ** 2 / (8 * m) * convert\n\n\ndef factorial(n):\n out = 1\n for x in range(n):\n out = out * (x + 1)\n return out\n\n\ndef bosonconfigs(numelvl, numpart):\n x = numpart\n n = numelvl\n out = choose(x + n - 1, x)\n return out\n\n\ndef choose(choices, x):\n if choices >= x:\n out = int(factorial(choices) / (factorial(x) * factorial(choices - x)))\n else:\n out = 0\n return out\n\n\ndef configs(x, elvl, particle='boson', out=None):\n \"\"\"\n Generate configs for bosons or fermions.\n\n Parameters\n ----------\n x : positive integer\n Number of particles in the system\n Energylvls : 1-D array\n List of valid energy states of the system\n particle : \"boson\" or \"fermion\"\n out : 1-D array\n Array to put configs in\n\n Returns\n -------\n out : 1-D array\n array of total energys of all valid configurations\n\n \"\"\"\n dtype = elvl.dtype\n n = elvl.size\n if particle == 'boson':\n if out is None:\n out = None\n out = np.zeros(bosonconfigs(n, x), dtype=dtype)\n if x == 1:\n for i in range(n):\n out[i] = elvl[i]\n if x > 1:\n k = 0\n for m in range(n):\n end = k + bosonconfigs(n - m, x - 1)\n configs(x - 1, elvl[m:], particle, out[k:end])\n for i in range(k, end):\n out[i] += elvl[m]\n k = end\n return out\n if particle == 'fermion':\n if out is None:\n out = None\n out = np.zeros(choose(n, x), dtype=dtype)\n if x == 1:\n for i in range(n):\n out[i] = elvl[i]\n if x > 1:\n k = 0\n for m in range(n):\n end = k + choose(n - (m + 1), x - 1)\n configs(x - 1, elvl[m + 1:], particle, out[k:end])\n for i in range(k, end):\n out[i] += elvl[m]\n k = end\n return out\n\n\nh = 6.62606957 * 10 ** -34\nm = 9.11 * 10 ** -31\nL = 0.39 * 10 ** -9\nconvert = 6.24150934 * 10 ** 18\nmaximum = 100\nkb = 1.3806488 * 10 ** -23\nenergylevels = np.fromiter(((x * h / L) ** 2 / (8 * m) * convert for x in\n range(maximum + 1)), dtype=float)\n\n\ndef oneDEnergy(n):\n energylevels = np.fromiter(((x * h / L) ** 2 / (8 * m) for x in range(1,\n n + 1)), dtype=float)\n return energylevels\n\n\ndef ThreeDEnergy(n):\n out = np.empty(n ** 3)\n index = 0\n for i in range(1, n + 1):\n for j in range(1, n + 1):\n for k in range(1, n + 1):\n out[index] = ((i * h / L) ** 2 + (j * h / L) ** 2 + (k * h /\n L) ** 2) / (8 * m) * convert\n index = index + 1\n return np.sort(out)\n\n\ndef fermion(n):\n energycount = []\n energy = oneDEnergy(maximum)\n fermionlist = configs(n, energy, 'fermion')\n for config in np.nditer(fermionlist):\n if config < energy[-1] + (n - 1) * energy[0]:\n energycount.append(config)\n fnc1 = ghistogram(bins=np.linspace(min(energycount), max(energycount), \n 100), color=color.red)\n fnc1.plot(data=energycount)\n hist, binedges = np.histogram(energycount, bins=100, weights=None,\n density=False)\n return hist, binedges\n\n\ndef boson(n, nthElvl, acc):\n \"\"\"\n n is the number of particles\n nthElvl is the nth energy level to go up to\n acc is integer of histogram(s)\n \"\"\"\n Elvl = oneDEnergy(nthElvl)\n econf = np.sort(configs(n, Elvl, particle='boson'))\n max_energy = Elvl[-1] + (n - 1) * Elvl[0]\n fcn1 = ghistogram(bins=np.linspace(econf[0], max_energy, acc))\n bound = True\n m = 0\n while bound == True:\n if econf[m] > max_energy:\n bound = False\n else:\n m = m + 1\n if m == econf.size:\n break\n fcn1.plot(data=econf[:m])\n hist, binedges = np.histogram(econf[:m], bins=100, weights=None,\n density=False)\n return hist, binedges\n\n\ndef boltzfit(xvalues, yvalues, degree):\n xlist = []\n for i in range(len(xvalues) - 1):\n xlist.append((xvalues[i] + xvalues[i + 1]) / 2)\n return np.polyfit(xlist, yvalues, degree)\n\n\ndef gibbsfit(xvalues, yvalues, degree):\n for j in range(len(yvalues)):\n if j > 0:\n yvalues[j] = yvalues[j - 1] + yvalues[j]\n return np.polyfit(xvalues[1:], yvalues, degree)\n\n\ndef conequation(n, degree, particle='boson', method='gibbs'):\n if particle == 'boson':\n data = boson(n, maximum, 100)\n if particle == 'fermion':\n data = fermion(n)\n print(data)\n if method == 'boltzmann':\n return boltzfit(data[1], data[0], degree)\n if method == 'gibbs':\n return gibbsfit(data[1], data[0], degree)\n", "step-5": "import numpy as np\nfrom math import *\nfrom visual import *\nfrom visual.graph import *\n\n\ndef energy2(n):\n return ((n*h/L)**2)/(8*m)*convert\n\ndef factorial(n):\n out=1\n for x in range(n):\n out=out*(x+1)\n return out\n\ndef bosonconfigs(numelvl,numpart):\n x=numpart\n n=numelvl\n out=choose(x+n-1,x)\n return out\n\ndef choose(choices,x):\n if choices>=x:\n out=int(factorial(choices)/((factorial(x)*factorial(choices-x))))\n else:\n out=0\n return out\n\ndef configs(x,elvl,particle=\"boson\",out=None):\n \"\"\"\n Generate configs for bosons or fermions.\n\n Parameters\n ----------\n x : positive integer\n Number of particles in the system\n Energylvls : 1-D array\n List of valid energy states of the system\n particle : \"boson\" or \"fermion\"\n out : 1-D array\n Array to put configs in\n\n Returns\n -------\n out : 1-D array\n array of total energys of all valid configurations\n\n \"\"\"\n\n dtype = elvl.dtype \n n=elvl.size #number of energy levels\n \n if particle==\"boson\":\n if out is None:\n out=None\n out = np.zeros(bosonconfigs(n,x), dtype=dtype)\n if x==1:\n for i in range(n):\n out[i]=elvl[i]\n if x>1:\n k=0 #index for end of last input added\n for m in range(n): #m is the energy level index\n end=k+bosonconfigs(n-m,x-1) #last energy level \n configs(x-1, elvl[m:],particle,out[k:end])\n for i in range(k,end):\n out[i]+= elvl[m]\n k=end\n return out\n\n if particle==\"fermion\":\n if out is None:\n out=None\n out = np.zeros(choose(n,x), dtype=dtype)\n if x==1:\n for i in range(n):\n out[i]=elvl[i]\n if x>1:\n k=0 #index for end of last input added\n for m in range(n): #m is the energy level index\n end=k+choose(n-(m+1),x-1) #last energy level \n configs(x-1, elvl[m+1:],particle,out[k:end])\n for i in range(k,end):\n out[i]+= elvl[m]\n k=end\n return out\n\nh = 6.62606957 * 10 ** -34 #Plank's constant\n#m = 1.67492735174 * 10 ** -27 #this is mass of neutron\nm = 9.11 * 10**-31 #this is mass of electron\nL = 0.39 * 10**-9 #size of box\nconvert = 6.24150934 * 10**18\nmaximum = 100\nkb = 1.3806488 * 10**-23\n\nenergylevels = np.fromiter((((x*h/L)**2)/(8*m)*convert for x in range(maximum+1)),dtype=float)\n#this creates the entire table of energy levels as a single list\n\ndef oneDEnergy(n):\n energylevels = np.fromiter((((x*h/L)**2)/(8*m) for x in range(1,n+1)),dtype=float)\n return energylevels\n #this creates the entire table of energy levels as a single list\n\ndef ThreeDEnergy(n):\n out=np.empty(n**3)\n index=0\n for i in range(1,n+1):\n for j in range(1,n+1):\n for k in range(1,n+1):\n out[index]=((i*h/L)**2+(j*h/L)**2+(k*h/L)**2)/(8*m)*convert\n index=index+1\n return np.sort(out)\n\ndef fermion(n):\n energycount = []\n energy = oneDEnergy(maximum)\n fermionlist = configs(n,energy,'fermion')\n for config in np.nditer(fermionlist):\n if config < energy[-1] + (n-1)*energy[0]:\n energycount.append(config)\n #return number of configurations in energy range\n fnc1 = ghistogram(bins = np.linspace(min(energycount), max(energycount), 100), color = color.red)\n fnc1.plot(data=energycount)\n hist, binedges = np.histogram(energycount,bins = 100,weights = None, density = False)\n return (hist,binedges)\n \ndef boson(n,nthElvl,acc):\n '''\n n is the number of particles\n nthElvl is the nth energy level to go up to\n acc is integer of histogram(s)\n '''\n Elvl= oneDEnergy(nthElvl)\n #print Elvl\n econf= np.sort(configs(n, Elvl, particle=\"boson\"))\n max_energy=Elvl[-1]+(n-1)*Elvl[0]\n #np.sort(econf)\n fcn1 = ghistogram(bins = np.linspace(econf[0],max_energy,acc))\n bound=True\n m=0\n while bound==True:\n if econf[m]>max_energy:\n bound=False\n else:\n m=m+1\n if m==econf.size:\n break\n fcn1.plot(data=econf[:m])\n hist, binedges = np.histogram(econf[:m],bins = 100,weights = None, density = False)\n return (hist,binedges)\n\ndef boltzfit(xvalues,yvalues,degree):\n xlist = []\n #ylist = []\n for i in range(len(xvalues)-1):\n xlist.append((xvalues[i] + xvalues[i+1])/(2)) #Average energy in joules\n #for j in range(len(yvalues)):\n #ylist.append(kb*log(yvalues[j])) #Convert to boltzmann entropy\n return np.polyfit(xlist,yvalues,degree)\n\ndef gibbsfit(xvalues,yvalues,degree):\n for j in range(len(yvalues)): #generate gibbs configurations\n if j > 0:\n yvalues[j] = yvalues[j-1] + yvalues[j]\n #for j in range(len(yvalues)):\n #ylist.append(kb*log(yvalues[j])) #Convert to entropy\n return np.polyfit(xvalues[1:],yvalues,degree)\n\ndef conequation(n,degree,particle ='boson',method ='gibbs'):\n if particle == 'boson':\n data = boson(n, maximum, 100)\n if particle == 'fermion':\n data = fermion(n)\n print (data)\n if method == 'boltzmann':\n return (boltzfit(data[1],data[0],degree))\n if method == 'gibbs':\n return (gibbsfit(data[1],data[0],degree)) \n \n\n\n \n \n\n\n\n", "step-ids": [ 7, 10, 12, 14, 15 ] }
[ 7, 10, 12, 14, 15 ]
<|reserved_special_token_0|> def get_cachefile(filename): """ Return full path to filename within cache dir. """ if not os.path.exists(cachedir): os.makedirs(cachedir) return os.path.join(cachedir, filename) <|reserved_special_token_0|> def get_cached_data(name): if name not in _cachedict: load_cachedict(name) return _cachedict[name] def cache_data(name, data): """ Save data to cache under name name: name of datastore data: data to store """ cache_path = get_cachefile('%s.cache' % name) with open(cache_path, 'wb') as f: pickle.dump(data, f) def cached_data_fresh(name, max_age): """ Is data cached at name less than max_age old? name: name of datastore max_age: maximum age of data in seconds returns True if data is less than max_age old, else False """ age = get_cached_data_age(name) if not age: return False return age < max_age def get_cached_data_age(name): """ Return age of data cached at name in seconds or 0 if cache doesn't exist name: name of datastore returns age of datastore in seconds """ cache_path = get_cachefile('%s.cache' % name) if not os.path.exists(cache_path): return 0 return time.time() - os.stat(cache_path).st_mtime def clear_cache(): """ Delete all files in cache directory.""" if os.path.exists(get_cachedir()): for filename in os.listdir(get_cachedir()): if not filename.endswith('.cache'): continue path = os.path.join(get_cachedir(), filename) os.unlink(path) def clear_cachedict(): _cachedict.clear() <|reserved_special_token_1|> <|reserved_special_token_0|> def get_cachefile(filename): """ Return full path to filename within cache dir. """ if not os.path.exists(cachedir): os.makedirs(cachedir) return os.path.join(cachedir, filename) def load_cachedict(name): cache_path = get_cachefile('%s.cache' % name) if os.path.isfile(cache_path): with open(cache_path, 'rb') as f: _cachedict[name] = pickle.load(f) def get_cached_data(name): if name not in _cachedict: load_cachedict(name) return _cachedict[name] def cache_data(name, data): """ Save data to cache under name name: name of datastore data: data to store """ cache_path = get_cachefile('%s.cache' % name) with open(cache_path, 'wb') as f: pickle.dump(data, f) def cached_data_fresh(name, max_age): """ Is data cached at name less than max_age old? name: name of datastore max_age: maximum age of data in seconds returns True if data is less than max_age old, else False """ age = get_cached_data_age(name) if not age: return False return age < max_age def get_cached_data_age(name): """ Return age of data cached at name in seconds or 0 if cache doesn't exist name: name of datastore returns age of datastore in seconds """ cache_path = get_cachefile('%s.cache' % name) if not os.path.exists(cache_path): return 0 return time.time() - os.stat(cache_path).st_mtime def clear_cache(): """ Delete all files in cache directory.""" if os.path.exists(get_cachedir()): for filename in os.listdir(get_cachedir()): if not filename.endswith('.cache'): continue path = os.path.join(get_cachedir(), filename) os.unlink(path) def clear_cachedict(): _cachedict.clear() <|reserved_special_token_1|> <|reserved_special_token_0|> try: import cPickle as pickle except: import pickle <|reserved_special_token_0|> def get_cachefile(filename): """ Return full path to filename within cache dir. """ if not os.path.exists(cachedir): os.makedirs(cachedir) return os.path.join(cachedir, filename) def load_cachedict(name): cache_path = get_cachefile('%s.cache' % name) if os.path.isfile(cache_path): with open(cache_path, 'rb') as f: _cachedict[name] = pickle.load(f) def get_cached_data(name): if name not in _cachedict: load_cachedict(name) return _cachedict[name] def cache_data(name, data): """ Save data to cache under name name: name of datastore data: data to store """ cache_path = get_cachefile('%s.cache' % name) with open(cache_path, 'wb') as f: pickle.dump(data, f) def cached_data_fresh(name, max_age): """ Is data cached at name less than max_age old? name: name of datastore max_age: maximum age of data in seconds returns True if data is less than max_age old, else False """ age = get_cached_data_age(name) if not age: return False return age < max_age def get_cached_data_age(name): """ Return age of data cached at name in seconds or 0 if cache doesn't exist name: name of datastore returns age of datastore in seconds """ cache_path = get_cachefile('%s.cache' % name) if not os.path.exists(cache_path): return 0 return time.time() - os.stat(cache_path).st_mtime def clear_cache(): """ Delete all files in cache directory.""" if os.path.exists(get_cachedir()): for filename in os.listdir(get_cachedir()): if not filename.endswith('.cache'): continue path = os.path.join(get_cachedir(), filename) os.unlink(path) def clear_cachedict(): _cachedict.clear() <|reserved_special_token_1|> <|reserved_special_token_0|> try: import cPickle as pickle except: import pickle cachedir = os.path.expanduser('~/.cache/sherlock/') _cachedict = {} def get_cachefile(filename): """ Return full path to filename within cache dir. """ if not os.path.exists(cachedir): os.makedirs(cachedir) return os.path.join(cachedir, filename) def load_cachedict(name): cache_path = get_cachefile('%s.cache' % name) if os.path.isfile(cache_path): with open(cache_path, 'rb') as f: _cachedict[name] = pickle.load(f) def get_cached_data(name): if name not in _cachedict: load_cachedict(name) return _cachedict[name] def cache_data(name, data): """ Save data to cache under name name: name of datastore data: data to store """ cache_path = get_cachefile('%s.cache' % name) with open(cache_path, 'wb') as f: pickle.dump(data, f) def cached_data_fresh(name, max_age): """ Is data cached at name less than max_age old? name: name of datastore max_age: maximum age of data in seconds returns True if data is less than max_age old, else False """ age = get_cached_data_age(name) if not age: return False return age < max_age def get_cached_data_age(name): """ Return age of data cached at name in seconds or 0 if cache doesn't exist name: name of datastore returns age of datastore in seconds """ cache_path = get_cachefile('%s.cache' % name) if not os.path.exists(cache_path): return 0 return time.time() - os.stat(cache_path).st_mtime def clear_cache(): """ Delete all files in cache directory.""" if os.path.exists(get_cachedir()): for filename in os.listdir(get_cachedir()): if not filename.endswith('.cache'): continue path = os.path.join(get_cachedir(), filename) os.unlink(path) def clear_cachedict(): _cachedict.clear() <|reserved_special_token_1|> import os import time try: import cPickle as pickle except: import pickle #-------------# # Cache utils # #-------------# cachedir = os.path.expanduser('~/.cache/sherlock/') _cachedict = {} def get_cachefile(filename): """ Return full path to filename within cache dir. """ if not os.path.exists(cachedir): os.makedirs(cachedir) return os.path.join(cachedir, filename) def load_cachedict(name): cache_path = get_cachefile('%s.cache' % name) if os.path.isfile(cache_path): with open(cache_path, 'rb') as f: _cachedict[name] = pickle.load(f) def get_cached_data(name): if name not in _cachedict: load_cachedict(name) return _cachedict[name] def cache_data(name, data): """ Save data to cache under name name: name of datastore data: data to store """ cache_path = get_cachefile('%s.cache' % name) with open(cache_path, 'wb') as f: pickle.dump(data, f) def cached_data_fresh(name, max_age): """ Is data cached at name less than max_age old? name: name of datastore max_age: maximum age of data in seconds returns True if data is less than max_age old, else False """ age = get_cached_data_age(name) if not age: return False return age < max_age def get_cached_data_age(name): """ Return age of data cached at name in seconds or 0 if cache doesn't exist name: name of datastore returns age of datastore in seconds """ cache_path = get_cachefile('%s.cache' % name) if not os.path.exists(cache_path): return 0 return time.time() - os.stat(cache_path).st_mtime def clear_cache(): """ Delete all files in cache directory.""" if os.path.exists(get_cachedir()): for filename in os.listdir(get_cachedir()): if not filename.endswith('.cache'): continue path = os.path.join(get_cachedir(), filename) os.unlink(path) def clear_cachedict(): _cachedict.clear()
flexible
{ "blob_id": "05cfd9d239b63c9b1e0c93a09e89cceb8d8e99e4", "index": 2462, "step-1": "<mask token>\n\n\ndef get_cachefile(filename):\n \"\"\"\n Return full path to filename within cache dir.\n \"\"\"\n if not os.path.exists(cachedir):\n os.makedirs(cachedir)\n return os.path.join(cachedir, filename)\n\n\n<mask token>\n\n\ndef get_cached_data(name):\n if name not in _cachedict:\n load_cachedict(name)\n return _cachedict[name]\n\n\ndef cache_data(name, data):\n \"\"\" Save data to cache under name\n name: name of datastore\n data: data to store\n \"\"\"\n cache_path = get_cachefile('%s.cache' % name)\n with open(cache_path, 'wb') as f:\n pickle.dump(data, f)\n\n\ndef cached_data_fresh(name, max_age):\n \"\"\" Is data cached at name less than max_age old?\n name: name of datastore\n max_age: maximum age of data in seconds\n returns True if data is less than max_age old, else False\n \"\"\"\n age = get_cached_data_age(name)\n if not age:\n return False\n return age < max_age\n\n\ndef get_cached_data_age(name):\n \"\"\" Return age of data cached at name in seconds or 0 if\n cache doesn't exist\n name: name of datastore\n returns age of datastore in seconds\n \"\"\"\n cache_path = get_cachefile('%s.cache' % name)\n if not os.path.exists(cache_path):\n return 0\n return time.time() - os.stat(cache_path).st_mtime\n\n\ndef clear_cache():\n \"\"\" Delete all files in cache directory.\"\"\"\n if os.path.exists(get_cachedir()):\n for filename in os.listdir(get_cachedir()):\n if not filename.endswith('.cache'):\n continue\n path = os.path.join(get_cachedir(), filename)\n os.unlink(path)\n\n\ndef clear_cachedict():\n _cachedict.clear()\n", "step-2": "<mask token>\n\n\ndef get_cachefile(filename):\n \"\"\"\n Return full path to filename within cache dir.\n \"\"\"\n if not os.path.exists(cachedir):\n os.makedirs(cachedir)\n return os.path.join(cachedir, filename)\n\n\ndef load_cachedict(name):\n cache_path = get_cachefile('%s.cache' % name)\n if os.path.isfile(cache_path):\n with open(cache_path, 'rb') as f:\n _cachedict[name] = pickle.load(f)\n\n\ndef get_cached_data(name):\n if name not in _cachedict:\n load_cachedict(name)\n return _cachedict[name]\n\n\ndef cache_data(name, data):\n \"\"\" Save data to cache under name\n name: name of datastore\n data: data to store\n \"\"\"\n cache_path = get_cachefile('%s.cache' % name)\n with open(cache_path, 'wb') as f:\n pickle.dump(data, f)\n\n\ndef cached_data_fresh(name, max_age):\n \"\"\" Is data cached at name less than max_age old?\n name: name of datastore\n max_age: maximum age of data in seconds\n returns True if data is less than max_age old, else False\n \"\"\"\n age = get_cached_data_age(name)\n if not age:\n return False\n return age < max_age\n\n\ndef get_cached_data_age(name):\n \"\"\" Return age of data cached at name in seconds or 0 if\n cache doesn't exist\n name: name of datastore\n returns age of datastore in seconds\n \"\"\"\n cache_path = get_cachefile('%s.cache' % name)\n if not os.path.exists(cache_path):\n return 0\n return time.time() - os.stat(cache_path).st_mtime\n\n\ndef clear_cache():\n \"\"\" Delete all files in cache directory.\"\"\"\n if os.path.exists(get_cachedir()):\n for filename in os.listdir(get_cachedir()):\n if not filename.endswith('.cache'):\n continue\n path = os.path.join(get_cachedir(), filename)\n os.unlink(path)\n\n\ndef clear_cachedict():\n _cachedict.clear()\n", "step-3": "<mask token>\ntry:\n import cPickle as pickle\nexcept:\n import pickle\n<mask token>\n\n\ndef get_cachefile(filename):\n \"\"\"\n Return full path to filename within cache dir.\n \"\"\"\n if not os.path.exists(cachedir):\n os.makedirs(cachedir)\n return os.path.join(cachedir, filename)\n\n\ndef load_cachedict(name):\n cache_path = get_cachefile('%s.cache' % name)\n if os.path.isfile(cache_path):\n with open(cache_path, 'rb') as f:\n _cachedict[name] = pickle.load(f)\n\n\ndef get_cached_data(name):\n if name not in _cachedict:\n load_cachedict(name)\n return _cachedict[name]\n\n\ndef cache_data(name, data):\n \"\"\" Save data to cache under name\n name: name of datastore\n data: data to store\n \"\"\"\n cache_path = get_cachefile('%s.cache' % name)\n with open(cache_path, 'wb') as f:\n pickle.dump(data, f)\n\n\ndef cached_data_fresh(name, max_age):\n \"\"\" Is data cached at name less than max_age old?\n name: name of datastore\n max_age: maximum age of data in seconds\n returns True if data is less than max_age old, else False\n \"\"\"\n age = get_cached_data_age(name)\n if not age:\n return False\n return age < max_age\n\n\ndef get_cached_data_age(name):\n \"\"\" Return age of data cached at name in seconds or 0 if\n cache doesn't exist\n name: name of datastore\n returns age of datastore in seconds\n \"\"\"\n cache_path = get_cachefile('%s.cache' % name)\n if not os.path.exists(cache_path):\n return 0\n return time.time() - os.stat(cache_path).st_mtime\n\n\ndef clear_cache():\n \"\"\" Delete all files in cache directory.\"\"\"\n if os.path.exists(get_cachedir()):\n for filename in os.listdir(get_cachedir()):\n if not filename.endswith('.cache'):\n continue\n path = os.path.join(get_cachedir(), filename)\n os.unlink(path)\n\n\ndef clear_cachedict():\n _cachedict.clear()\n", "step-4": "<mask token>\ntry:\n import cPickle as pickle\nexcept:\n import pickle\ncachedir = os.path.expanduser('~/.cache/sherlock/')\n_cachedict = {}\n\n\ndef get_cachefile(filename):\n \"\"\"\n Return full path to filename within cache dir.\n \"\"\"\n if not os.path.exists(cachedir):\n os.makedirs(cachedir)\n return os.path.join(cachedir, filename)\n\n\ndef load_cachedict(name):\n cache_path = get_cachefile('%s.cache' % name)\n if os.path.isfile(cache_path):\n with open(cache_path, 'rb') as f:\n _cachedict[name] = pickle.load(f)\n\n\ndef get_cached_data(name):\n if name not in _cachedict:\n load_cachedict(name)\n return _cachedict[name]\n\n\ndef cache_data(name, data):\n \"\"\" Save data to cache under name\n name: name of datastore\n data: data to store\n \"\"\"\n cache_path = get_cachefile('%s.cache' % name)\n with open(cache_path, 'wb') as f:\n pickle.dump(data, f)\n\n\ndef cached_data_fresh(name, max_age):\n \"\"\" Is data cached at name less than max_age old?\n name: name of datastore\n max_age: maximum age of data in seconds\n returns True if data is less than max_age old, else False\n \"\"\"\n age = get_cached_data_age(name)\n if not age:\n return False\n return age < max_age\n\n\ndef get_cached_data_age(name):\n \"\"\" Return age of data cached at name in seconds or 0 if\n cache doesn't exist\n name: name of datastore\n returns age of datastore in seconds\n \"\"\"\n cache_path = get_cachefile('%s.cache' % name)\n if not os.path.exists(cache_path):\n return 0\n return time.time() - os.stat(cache_path).st_mtime\n\n\ndef clear_cache():\n \"\"\" Delete all files in cache directory.\"\"\"\n if os.path.exists(get_cachedir()):\n for filename in os.listdir(get_cachedir()):\n if not filename.endswith('.cache'):\n continue\n path = os.path.join(get_cachedir(), filename)\n os.unlink(path)\n\n\ndef clear_cachedict():\n _cachedict.clear()\n", "step-5": "import os\nimport time\n\ntry:\n import cPickle as pickle\nexcept:\n import pickle\n\n\n#-------------#\n# Cache utils #\n#-------------#\n\ncachedir = os.path.expanduser('~/.cache/sherlock/')\n\n_cachedict = {}\n\ndef get_cachefile(filename):\n \"\"\"\n Return full path to filename within cache dir.\n \"\"\"\n if not os.path.exists(cachedir):\n os.makedirs(cachedir)\n return os.path.join(cachedir, filename)\n\ndef load_cachedict(name):\n\n cache_path = get_cachefile('%s.cache' % name)\n if os.path.isfile(cache_path):\n with open(cache_path, 'rb') as f:\n _cachedict[name] = pickle.load(f)\n\n\ndef get_cached_data(name):\n if name not in _cachedict:\n load_cachedict(name)\n\n return _cachedict[name]\n\ndef cache_data(name, data):\n \"\"\" Save data to cache under name\n name: name of datastore\n data: data to store\n \"\"\"\n cache_path = get_cachefile('%s.cache' % name)\n with open(cache_path, 'wb') as f:\n pickle.dump(data, f)\n\ndef cached_data_fresh(name, max_age):\n \"\"\" Is data cached at name less than max_age old?\n name: name of datastore\n max_age: maximum age of data in seconds\n returns True if data is less than max_age old, else False\n \"\"\"\n age = get_cached_data_age(name)\n if not age:\n return False\n return age < max_age\n\ndef get_cached_data_age(name):\n \"\"\" Return age of data cached at name in seconds or 0 if\n cache doesn't exist\n name: name of datastore\n returns age of datastore in seconds\n \"\"\"\n cache_path = get_cachefile('%s.cache' % name)\n if not os.path.exists(cache_path):\n return 0\n return time.time() - os.stat(cache_path).st_mtime\n\ndef clear_cache():\n \"\"\" Delete all files in cache directory.\"\"\"\n if os.path.exists(get_cachedir()):\n for filename in os.listdir(get_cachedir()):\n if not filename.endswith('.cache'):\n continue\n\n path = os.path.join(get_cachedir(), filename)\n os.unlink(path)\n\ndef clear_cachedict():\n _cachedict.clear()\n", "step-ids": [ 7, 8, 9, 10, 12 ] }
[ 7, 8, 9, 10, 12 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> n.sort() <|reserved_special_token_0|> for i in range(n): if i.isalpha(): alpa.append(i) else: num.append(i) result.append(str(alpa)) result.append(str(num)) print(n) <|reserved_special_token_1|> n = input() n = list(n) n.sort() alph = [] num = [] for i in range(n): if i.isalpha(): alpa.append(i) else: num.append(i) result.append(str(alpa)) result.append(str(num)) print(n)
flexible
{ "blob_id": "e364a4e6e1c4e0fd6805515a1149adaf92e9c8fb", "index": 5584, "step-1": "<mask token>\n", "step-2": "<mask token>\nn.sort()\n<mask token>\nfor i in range(n):\n if i.isalpha():\n alpa.append(i)\n else:\n num.append(i)\nresult.append(str(alpa))\nresult.append(str(num))\nprint(n)\n", "step-3": "n = input()\nn = list(n)\nn.sort()\nalph = []\nnum = []\nfor i in range(n):\n if i.isalpha():\n alpa.append(i)\n else:\n num.append(i)\nresult.append(str(alpa))\nresult.append(str(num))\nprint(n)\n", "step-4": null, "step-5": null, "step-ids": [ 0, 1, 2 ] }
[ 0, 1, 2 ]
<|reserved_special_token_0|> def gen_label(uid1, uid2): if same_line_dict[uid1].__contains__(uid2) and same_line_dict[uid2 ].__contains__(uid1): return '1' else: return '-1' <|reserved_special_token_0|> def gen_flw(uid1, uid2): if not valid_flw.__contains__(uid1) and not valid_flw.__contains__(uid2): return 0, 0 elif valid_flw.__contains__(uid1) and not valid_flw.__contains__(uid2): return flw_dict[uid1].__contains__(uid2), 0 elif not valid_flw.__contains__(uid1) and valid_flw.__contains__(uid2): return flw_dict[uid2].__contains__(uid1), 0 else: return 2, len(list(a for a in flw_dict[uid1] if a in flw_dict[uid2]) ) / (len(flw_dict[uid1]) + len(flw_dict[uid2]) - len(list(a for a in flw_dict[uid1] if a in flw_dict[uid2]))) <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> logging.basicConfig(level=logging.INFO) <|reserved_special_token_0|> user_file.close() <|reserved_special_token_0|> for items in user_gp: users = items.strip().split() same_line_dict.update({x: users for x in users}) <|reserved_special_token_0|> info_file.close() <|reserved_special_token_0|> for line in info_data: tmp_str = line.strip() try: tmp_dict = json.loads(tmp_str) k = list(tmp_dict.keys()) v = tmp_dict[k[0]] info_dict.update({k[0]: v}) except: logging.warning('Invalid Data!') continue <|reserved_special_token_0|> print(user_num) <|reserved_special_token_0|> flw_file.close() <|reserved_special_token_0|> for lines in flw_data: items = lines.strip().split() flw_dict[items[0]] = items[2:] <|reserved_special_token_0|> print(len(flw_dict)) def gen_label(uid1, uid2): if same_line_dict[uid1].__contains__(uid2) and same_line_dict[uid2 ].__contains__(uid1): return '1' else: return '-1' <|reserved_special_token_0|> def get_info(uid): if info_dict[uid] == []: return False, {} tdict = {'text': '', 'textLength': 0, 'source': '', 'id': '', 'screen_name': '', 'statuses_count': 0, 'verified': False, 'verified_type': -1, 'description': '', 'gender': '', 'urank': 0, 'followers_count': 0, 'follow_count': 0, 'reposts_count': 0, 'comments_count': 0, 'attitudes_count': 0, 'isLongText': False} latest_po = info_dict[uid][0]['mblog'] user_info = latest_po['user'] for elem in info_keys[0:3]: if list(latest_po.keys()).__contains__(elem): tdict.update({elem: latest_po[elem]}) for elem in info_keys[3:]: if list(user_info.keys()).__contains__(elem): tdict.update({elem: user_info[elem]}) return True, tdict def gen_data(dict1, dict2): result = [] if dict1['verified'] and dict2['verified']: verified = -1 elif dict1['verified'] or dict2['verified']: verified = 1 else: verified = 0 result.append(verified) bool_style = ['verified_type', 'gender', 'isLongText'] for items in bool_style: result.append(1 if dict1[items] == dict2[items] else 0) result.append(abs(dict1['urank'] - dict2['urank'])) result.append(abs(dict1['statuses_count'] - dict2['statuses_count'])) result.append(abs(dict1['followers_count'] - dict2['followers_count']) / abs(dict1['followers_count'] + dict2['followers_count']) if abs( dict1['followers_count'] + dict2['followers_count']) != 0 else 1) result.append(abs(dict1['follow_count'] - dict2['follow_count']) / abs( dict1['follow_count'] + dict2['follow_count']) if abs(dict1[ 'follow_count'] + dict2['follow_count']) != 0 else 1) result.append(abs(dict1['reposts_count'] - dict2['reposts_count'])) result.append(abs(dict1['comments_count'] - dict2['comments_count'])) result.append(abs(dict1['attitudes_count'] - dict2['attitudes_count'])) result.append(Levenshtein.jaro_winkler(dict1['screen_name'], dict2[ 'screen_name'])) result.append(Levenshtein.jaro_winkler(dict1['description'], dict2[ 'description'])) result.append(Levenshtein.jaro_winkler(dict1['text'], dict2['text'])) return result def gen_flw(uid1, uid2): if not valid_flw.__contains__(uid1) and not valid_flw.__contains__(uid2): return 0, 0 elif valid_flw.__contains__(uid1) and not valid_flw.__contains__(uid2): return flw_dict[uid1].__contains__(uid2), 0 elif not valid_flw.__contains__(uid1) and valid_flw.__contains__(uid2): return flw_dict[uid2].__contains__(uid1), 0 else: return 2, len(list(a for a in flw_dict[uid1] if a in flw_dict[uid2]) ) / (len(flw_dict[uid1]) + len(flw_dict[uid2]) - len(list(a for a in flw_dict[uid1] if a in flw_dict[uid2]))) logging.info('Prepare Data!') <|reserved_special_token_0|> for i in range(0, train_num): order1 = random.randint(0, user_num - 1) order2 = random.randint(0, user_num - 1) uid1 = valid_users[order1] uid2 = same_line_dict[uid1][random.randint(0, len(same_line_dict[uid1]) - 1)] flag1, dict1 = get_info(uid1) flag2, dict2 = get_info(uid2) while uid1 == uid2 or uidpool.__contains__([uid1, uid2] ) or not flag1 or not flag2: order1 = random.randint(0, user_num - 1) order2 = random.randint(0, user_num - 1) uid1 = valid_users[order1] uid2 = valid_users[order2] flag1, dict1 = get_info(uid1) flag2, dict2 = get_info(uid2) uidpool.append([uid1, uid2]) uidpool.append([uid2, uid1]) tmp_data = gen_data(dict1, dict2) flw1, flw2 = gen_flw(uid1, uid2) tmp_data.append(flw1) tmp_data.append(flw2) data.append(tmp_data) labels.append(gen_label(uid1, uid2)) print(data) print(labels) print('total number:', train_num) print('total positive samples:', labels.count('1')) logging.info('Start Training!') <|reserved_special_token_0|> for order in range(0, 10): ratio = 9 / 10 train_data = [] train_labels = [] test_data = [] test_labels = [] for i in range(0, train_num): if random.random() > ratio: test_data.append(data[i]) test_labels.append(labels[i]) else: train_data.append(data[i]) train_labels.append(labels[i]) rf.fit(train_data, train_labels) logging.info('Train Done!') acc = rf.score(data, labels) accur.append(acc) <|reserved_special_token_0|> print('Feature Weight:') <|reserved_special_token_0|> for i in range(0, 16): print(features[i], ':', rf.feature_importances_[i]) print('Total accuracy', rf.score(data, labels)) <|reserved_special_token_0|> print(sum(scores) / 10) print('time:', end_time - begin_time) <|reserved_special_token_1|> <|reserved_special_token_0|> logging.basicConfig(level=logging.INFO) user_file = open('groundtruth.txt') user_gp = user_file.readlines() user_file.close() same_line_dict = {} for items in user_gp: users = items.strip().split() same_line_dict.update({x: users for x in users}) info_file = codecs.open('new_posts.txt', 'r', 'utf-8') info_data = info_file.readlines() info_file.close() info_dict = {} for line in info_data: tmp_str = line.strip() try: tmp_dict = json.loads(tmp_str) k = list(tmp_dict.keys()) v = tmp_dict[k[0]] info_dict.update({k[0]: v}) except: logging.warning('Invalid Data!') continue valid_users = list(info_dict.keys()) user_num = len(valid_users) print(user_num) flw_file = open('new_followings.txt') flw_data = flw_file.readlines() flw_file.close() flw_dict = {} for lines in flw_data: items = lines.strip().split() flw_dict[items[0]] = items[2:] valid_flw = list(flw_dict.keys()) print(len(flw_dict)) def gen_label(uid1, uid2): if same_line_dict[uid1].__contains__(uid2) and same_line_dict[uid2 ].__contains__(uid1): return '1' else: return '-1' info_keys = ['text', 'textLength', 'source', 'id', 'screen_name', 'statuses_count', 'verified', 'verified_type', 'description', 'gender', 'urank', 'followers_count', 'follow_count', 'reposts_count', 'comments_count', 'attitudes_count', 'isLongText'] def get_info(uid): if info_dict[uid] == []: return False, {} tdict = {'text': '', 'textLength': 0, 'source': '', 'id': '', 'screen_name': '', 'statuses_count': 0, 'verified': False, 'verified_type': -1, 'description': '', 'gender': '', 'urank': 0, 'followers_count': 0, 'follow_count': 0, 'reposts_count': 0, 'comments_count': 0, 'attitudes_count': 0, 'isLongText': False} latest_po = info_dict[uid][0]['mblog'] user_info = latest_po['user'] for elem in info_keys[0:3]: if list(latest_po.keys()).__contains__(elem): tdict.update({elem: latest_po[elem]}) for elem in info_keys[3:]: if list(user_info.keys()).__contains__(elem): tdict.update({elem: user_info[elem]}) return True, tdict def gen_data(dict1, dict2): result = [] if dict1['verified'] and dict2['verified']: verified = -1 elif dict1['verified'] or dict2['verified']: verified = 1 else: verified = 0 result.append(verified) bool_style = ['verified_type', 'gender', 'isLongText'] for items in bool_style: result.append(1 if dict1[items] == dict2[items] else 0) result.append(abs(dict1['urank'] - dict2['urank'])) result.append(abs(dict1['statuses_count'] - dict2['statuses_count'])) result.append(abs(dict1['followers_count'] - dict2['followers_count']) / abs(dict1['followers_count'] + dict2['followers_count']) if abs( dict1['followers_count'] + dict2['followers_count']) != 0 else 1) result.append(abs(dict1['follow_count'] - dict2['follow_count']) / abs( dict1['follow_count'] + dict2['follow_count']) if abs(dict1[ 'follow_count'] + dict2['follow_count']) != 0 else 1) result.append(abs(dict1['reposts_count'] - dict2['reposts_count'])) result.append(abs(dict1['comments_count'] - dict2['comments_count'])) result.append(abs(dict1['attitudes_count'] - dict2['attitudes_count'])) result.append(Levenshtein.jaro_winkler(dict1['screen_name'], dict2[ 'screen_name'])) result.append(Levenshtein.jaro_winkler(dict1['description'], dict2[ 'description'])) result.append(Levenshtein.jaro_winkler(dict1['text'], dict2['text'])) return result def gen_flw(uid1, uid2): if not valid_flw.__contains__(uid1) and not valid_flw.__contains__(uid2): return 0, 0 elif valid_flw.__contains__(uid1) and not valid_flw.__contains__(uid2): return flw_dict[uid1].__contains__(uid2), 0 elif not valid_flw.__contains__(uid1) and valid_flw.__contains__(uid2): return flw_dict[uid2].__contains__(uid1), 0 else: return 2, len(list(a for a in flw_dict[uid1] if a in flw_dict[uid2]) ) / (len(flw_dict[uid1]) + len(flw_dict[uid2]) - len(list(a for a in flw_dict[uid1] if a in flw_dict[uid2]))) logging.info('Prepare Data!') train_num = 8000 data = [] labels = [] uidpool = [] for i in range(0, train_num): order1 = random.randint(0, user_num - 1) order2 = random.randint(0, user_num - 1) uid1 = valid_users[order1] uid2 = same_line_dict[uid1][random.randint(0, len(same_line_dict[uid1]) - 1)] flag1, dict1 = get_info(uid1) flag2, dict2 = get_info(uid2) while uid1 == uid2 or uidpool.__contains__([uid1, uid2] ) or not flag1 or not flag2: order1 = random.randint(0, user_num - 1) order2 = random.randint(0, user_num - 1) uid1 = valid_users[order1] uid2 = valid_users[order2] flag1, dict1 = get_info(uid1) flag2, dict2 = get_info(uid2) uidpool.append([uid1, uid2]) uidpool.append([uid2, uid1]) tmp_data = gen_data(dict1, dict2) flw1, flw2 = gen_flw(uid1, uid2) tmp_data.append(flw1) tmp_data.append(flw2) data.append(tmp_data) labels.append(gen_label(uid1, uid2)) print(data) print(labels) print('total number:', train_num) print('total positive samples:', labels.count('1')) logging.info('Start Training!') rf = RandomForestClassifier(n_estimators=40, n_jobs=4, verbose=0) accur = [] begin_time = time.time() for order in range(0, 10): ratio = 9 / 10 train_data = [] train_labels = [] test_data = [] test_labels = [] for i in range(0, train_num): if random.random() > ratio: test_data.append(data[i]) test_labels.append(labels[i]) else: train_data.append(data[i]) train_labels.append(labels[i]) rf.fit(train_data, train_labels) logging.info('Train Done!') acc = rf.score(data, labels) accur.append(acc) end_time = time.time() print('Feature Weight:') features = ['verified', 'verified_type', 'gender', 'isLongText', 'urank', 'statuses_diff', 'followers_diff', 'follows_diff', 'reposts_diff', 'comment_diff', 'attitudes_diff', 'screen_name_similarity', 'description_similarity', 'text_similarity', 'co_follow', 'in_follows'] for i in range(0, 16): print(features[i], ':', rf.feature_importances_[i]) print('Total accuracy', rf.score(data, labels)) scores = cross_val_score(rf, data, labels, cv=10) print(sum(scores) / 10) print('time:', end_time - begin_time) <|reserved_special_token_1|> import json import codecs import Levenshtein import logging import random from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import cross_val_score import time from sklearn.model_selection import KFold import numpy as np import scipy.io as scio from matplotlib import pyplot as plt logging.basicConfig(level=logging.INFO) user_file = open('groundtruth.txt') user_gp = user_file.readlines() user_file.close() same_line_dict = {} for items in user_gp: users = items.strip().split() same_line_dict.update({x: users for x in users}) info_file = codecs.open('new_posts.txt', 'r', 'utf-8') info_data = info_file.readlines() info_file.close() info_dict = {} for line in info_data: tmp_str = line.strip() try: tmp_dict = json.loads(tmp_str) k = list(tmp_dict.keys()) v = tmp_dict[k[0]] info_dict.update({k[0]: v}) except: logging.warning('Invalid Data!') continue valid_users = list(info_dict.keys()) user_num = len(valid_users) print(user_num) flw_file = open('new_followings.txt') flw_data = flw_file.readlines() flw_file.close() flw_dict = {} for lines in flw_data: items = lines.strip().split() flw_dict[items[0]] = items[2:] valid_flw = list(flw_dict.keys()) print(len(flw_dict)) def gen_label(uid1, uid2): if same_line_dict[uid1].__contains__(uid2) and same_line_dict[uid2 ].__contains__(uid1): return '1' else: return '-1' info_keys = ['text', 'textLength', 'source', 'id', 'screen_name', 'statuses_count', 'verified', 'verified_type', 'description', 'gender', 'urank', 'followers_count', 'follow_count', 'reposts_count', 'comments_count', 'attitudes_count', 'isLongText'] def get_info(uid): if info_dict[uid] == []: return False, {} tdict = {'text': '', 'textLength': 0, 'source': '', 'id': '', 'screen_name': '', 'statuses_count': 0, 'verified': False, 'verified_type': -1, 'description': '', 'gender': '', 'urank': 0, 'followers_count': 0, 'follow_count': 0, 'reposts_count': 0, 'comments_count': 0, 'attitudes_count': 0, 'isLongText': False} latest_po = info_dict[uid][0]['mblog'] user_info = latest_po['user'] for elem in info_keys[0:3]: if list(latest_po.keys()).__contains__(elem): tdict.update({elem: latest_po[elem]}) for elem in info_keys[3:]: if list(user_info.keys()).__contains__(elem): tdict.update({elem: user_info[elem]}) return True, tdict def gen_data(dict1, dict2): result = [] if dict1['verified'] and dict2['verified']: verified = -1 elif dict1['verified'] or dict2['verified']: verified = 1 else: verified = 0 result.append(verified) bool_style = ['verified_type', 'gender', 'isLongText'] for items in bool_style: result.append(1 if dict1[items] == dict2[items] else 0) result.append(abs(dict1['urank'] - dict2['urank'])) result.append(abs(dict1['statuses_count'] - dict2['statuses_count'])) result.append(abs(dict1['followers_count'] - dict2['followers_count']) / abs(dict1['followers_count'] + dict2['followers_count']) if abs( dict1['followers_count'] + dict2['followers_count']) != 0 else 1) result.append(abs(dict1['follow_count'] - dict2['follow_count']) / abs( dict1['follow_count'] + dict2['follow_count']) if abs(dict1[ 'follow_count'] + dict2['follow_count']) != 0 else 1) result.append(abs(dict1['reposts_count'] - dict2['reposts_count'])) result.append(abs(dict1['comments_count'] - dict2['comments_count'])) result.append(abs(dict1['attitudes_count'] - dict2['attitudes_count'])) result.append(Levenshtein.jaro_winkler(dict1['screen_name'], dict2[ 'screen_name'])) result.append(Levenshtein.jaro_winkler(dict1['description'], dict2[ 'description'])) result.append(Levenshtein.jaro_winkler(dict1['text'], dict2['text'])) return result def gen_flw(uid1, uid2): if not valid_flw.__contains__(uid1) and not valid_flw.__contains__(uid2): return 0, 0 elif valid_flw.__contains__(uid1) and not valid_flw.__contains__(uid2): return flw_dict[uid1].__contains__(uid2), 0 elif not valid_flw.__contains__(uid1) and valid_flw.__contains__(uid2): return flw_dict[uid2].__contains__(uid1), 0 else: return 2, len(list(a for a in flw_dict[uid1] if a in flw_dict[uid2]) ) / (len(flw_dict[uid1]) + len(flw_dict[uid2]) - len(list(a for a in flw_dict[uid1] if a in flw_dict[uid2]))) logging.info('Prepare Data!') train_num = 8000 data = [] labels = [] uidpool = [] for i in range(0, train_num): order1 = random.randint(0, user_num - 1) order2 = random.randint(0, user_num - 1) uid1 = valid_users[order1] uid2 = same_line_dict[uid1][random.randint(0, len(same_line_dict[uid1]) - 1)] flag1, dict1 = get_info(uid1) flag2, dict2 = get_info(uid2) while uid1 == uid2 or uidpool.__contains__([uid1, uid2] ) or not flag1 or not flag2: order1 = random.randint(0, user_num - 1) order2 = random.randint(0, user_num - 1) uid1 = valid_users[order1] uid2 = valid_users[order2] flag1, dict1 = get_info(uid1) flag2, dict2 = get_info(uid2) uidpool.append([uid1, uid2]) uidpool.append([uid2, uid1]) tmp_data = gen_data(dict1, dict2) flw1, flw2 = gen_flw(uid1, uid2) tmp_data.append(flw1) tmp_data.append(flw2) data.append(tmp_data) labels.append(gen_label(uid1, uid2)) print(data) print(labels) print('total number:', train_num) print('total positive samples:', labels.count('1')) logging.info('Start Training!') rf = RandomForestClassifier(n_estimators=40, n_jobs=4, verbose=0) accur = [] begin_time = time.time() for order in range(0, 10): ratio = 9 / 10 train_data = [] train_labels = [] test_data = [] test_labels = [] for i in range(0, train_num): if random.random() > ratio: test_data.append(data[i]) test_labels.append(labels[i]) else: train_data.append(data[i]) train_labels.append(labels[i]) rf.fit(train_data, train_labels) logging.info('Train Done!') acc = rf.score(data, labels) accur.append(acc) end_time = time.time() print('Feature Weight:') features = ['verified', 'verified_type', 'gender', 'isLongText', 'urank', 'statuses_diff', 'followers_diff', 'follows_diff', 'reposts_diff', 'comment_diff', 'attitudes_diff', 'screen_name_similarity', 'description_similarity', 'text_similarity', 'co_follow', 'in_follows'] for i in range(0, 16): print(features[i], ':', rf.feature_importances_[i]) print('Total accuracy', rf.score(data, labels)) scores = cross_val_score(rf, data, labels, cv=10) print(sum(scores) / 10) print('time:', end_time - begin_time) <|reserved_special_token_1|> #!/usr/bin/env python3 # -*- coding: utf-8 -*- import json import codecs import Levenshtein import logging import random from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import cross_val_score import time from sklearn.model_selection import KFold import numpy as np import scipy.io as scio from matplotlib import pyplot as plt logging.basicConfig(level=logging.INFO) user_file = open('groundtruth.txt') user_gp = user_file.readlines() user_file.close() same_line_dict = {} for items in user_gp: users = items.strip().split() same_line_dict.update({x: users for x in users}) # print(same_line_dict) info_file = codecs.open('new_posts.txt', 'r', 'utf-8') info_data = info_file.readlines() info_file.close() info_dict = {} for line in info_data: tmp_str = line.strip() # print(tmp_str) try: tmp_dict = json.loads(tmp_str) k = list(tmp_dict.keys()) # print(k) v = tmp_dict[k[0]] info_dict.update({k[0]: v}) except: logging.warning('Invalid Data!') continue valid_users = list(info_dict.keys()) user_num = len(valid_users) print(user_num) flw_file = open('new_followings.txt') flw_data = flw_file.readlines() flw_file.close() flw_dict = {} for lines in flw_data: items = lines.strip().split() flw_dict[items[0]] = items[2:] valid_flw = list(flw_dict.keys()) print(len(flw_dict)) def gen_label(uid1, uid2): if same_line_dict[uid1].__contains__(uid2) and same_line_dict[uid2].__contains__(uid1): return '1' else: return '-1' info_keys = ['text', 'textLength', 'source', 'id', 'screen_name', 'statuses_count', 'verified', 'verified_type', 'description', 'gender', 'urank', 'followers_count', 'follow_count', 'reposts_count', 'comments_count', 'attitudes_count', 'isLongText'] def get_info(uid): if info_dict[uid] == []: return False, {} tdict = { 'text': '', 'textLength': 0, 'source': '', 'id': '', 'screen_name': '', 'statuses_count': 0, 'verified': False, 'verified_type': -1, 'description': '', 'gender': '', 'urank': 0, 'followers_count': 0, 'follow_count': 0, 'reposts_count': 0, 'comments_count': 0, 'attitudes_count': 0, 'isLongText': False } # print(info_dict[uid]) latest_po = info_dict[uid][0]['mblog'] user_info = latest_po['user'] # print(latest_po) # print(user_info) for elem in info_keys[0:3]: if list(latest_po.keys()).__contains__(elem): tdict.update({elem: latest_po[elem]}) for elem in info_keys[3:]: if list(user_info.keys()).__contains__(elem): tdict.update({elem: user_info[elem]}) return True, tdict def gen_data(dict1, dict2): result = [] if dict1['verified'] and dict2['verified']: verified = -1 elif dict1['verified'] or dict2['verified']: verified = 1 else: verified = 0 result.append(verified) bool_style = ['verified_type', 'gender', 'isLongText'] for items in bool_style: result.append(1 if dict1[items] == dict2[items] else 0) result.append(abs(dict1['urank'] - dict2['urank'])) result.append(abs(dict1['statuses_count'] - dict2['statuses_count'])) result.append(abs(dict1['followers_count'] - dict2['followers_count']) / abs(dict1['followers_count'] + dict2['followers_count']) if abs(dict1['followers_count'] + dict2['followers_count']) != 0 else 1) result.append(abs(dict1['follow_count'] - dict2['follow_count']) / abs(dict1['follow_count'] + dict2['follow_count']) if abs(dict1['follow_count'] + dict2['follow_count']) != 0 else 1 ) result.append(abs(dict1['reposts_count'] - dict2['reposts_count'])) result.append(abs(dict1['comments_count'] - dict2['comments_count'])) result.append(abs(dict1['attitudes_count'] - dict2['attitudes_count'])) result.append(Levenshtein.jaro_winkler(dict1['screen_name'], dict2['screen_name'])) result.append(Levenshtein.jaro_winkler(dict1['description'], dict2['description'])) result.append(Levenshtein.jaro_winkler(dict1['text'], dict2['text'])) return result def gen_flw(uid1, uid2): if not valid_flw.__contains__(uid1) and not valid_flw.__contains__(uid2): return 0, 0 elif valid_flw.__contains__(uid1) and not valid_flw.__contains__(uid2): return flw_dict[uid1].__contains__(uid2), 0 elif not valid_flw.__contains__(uid1) and valid_flw.__contains__(uid2): return flw_dict[uid2].__contains__(uid1), 0 else: return 2, len(list(a for a in flw_dict[uid1] if a in flw_dict[uid2])) \ / ( len(flw_dict[uid1]) + len(flw_dict[uid2]) - len( list(a for a in flw_dict[uid1] if a in flw_dict[uid2]))) logging.info('Prepare Data!') train_num = 8000 data = [] labels = [] uidpool = [] for i in range(0, train_num): order1 = random.randint(0, user_num - 1) order2 = random.randint(0, user_num - 1) uid1 = valid_users[order1] uid2 = same_line_dict[uid1][random.randint(0, len(same_line_dict[uid1]) - 1)] # uid2 = valid_users[order2] # if random.random() >= 0: # # print('+-1') # uid2 = same_line_dict[uid1][random.randint(0, len(same_line_dict[uid1]) - 1)] flag1, dict1 = get_info(uid1) flag2, dict2 = get_info(uid2) while (uid1 == uid2 or uidpool.__contains__([uid1, uid2]) or not flag1 or not flag2): order1 = random.randint(0, user_num - 1) order2 = random.randint(0, user_num - 1) uid1 = valid_users[order1] uid2 = valid_users[order2] flag1, dict1 = get_info(uid1) flag2, dict2 = get_info(uid2) uidpool.append([uid1, uid2]) uidpool.append([uid2, uid1]) tmp_data = gen_data(dict1, dict2) flw1, flw2 = gen_flw(uid1, uid2) # data.append(gen_data(dict1, dict2)) tmp_data.append(flw1) tmp_data.append(flw2) data.append(tmp_data) labels.append(gen_label(uid1, uid2)) # print(uid1, uid2) print(data) print(labels) print('total number:', train_num) print('total positive samples:', labels.count('1')) logging.info('Start Training!') rf = RandomForestClassifier(n_estimators=40, n_jobs=4, verbose=0) accur = [] begin_time=time.time() for order in range(0, 10): ratio = 9 / 10 train_data = [] train_labels = [] test_data = [] test_labels = [] for i in range(0, train_num): if random.random() > ratio: test_data.append(data[i]) test_labels.append(labels[i]) else: train_data.append(data[i]) train_labels.append(labels[i]) # print('train number:', len(train_labels)) # print('train positive samples:', train_labels.count('1')) rf.fit(train_data, train_labels) logging.info('Train Done!') # print('Train accuracy:', # rf.score(train_data, train_labels)) # print('Test accuracy:', # rf.score(test_data, test_labels)) acc = rf.score(data, labels) # print('Total accuracy:', acc) accur.append(acc) end_time=time.time() print('Feature Weight:') # print('Feature Weight:', rf.feature_importances_) features = ['verified', 'verified_type', 'gender', 'isLongText', 'urank', 'statuses_diff', 'followers_diff', 'follows_diff', 'reposts_diff', 'comment_diff', 'attitudes_diff', 'screen_name_similarity', 'description_similarity', 'text_similarity', 'co_follow', 'in_follows'] for i in range(0, 16): print(features[i], ':', rf.feature_importances_[i]) print('Total accuracy', rf.score(data, labels)) scores = cross_val_score(rf, data, labels, cv=10) print(sum(scores) / 10) print('time:',end_time-begin_time)
flexible
{ "blob_id": "37804c92b69d366cc1774335b6a2295dfd5b98f3", "index": 6592, "step-1": "<mask token>\n\n\ndef gen_label(uid1, uid2):\n if same_line_dict[uid1].__contains__(uid2) and same_line_dict[uid2\n ].__contains__(uid1):\n return '1'\n else:\n return '-1'\n\n\n<mask token>\n\n\ndef gen_flw(uid1, uid2):\n if not valid_flw.__contains__(uid1) and not valid_flw.__contains__(uid2):\n return 0, 0\n elif valid_flw.__contains__(uid1) and not valid_flw.__contains__(uid2):\n return flw_dict[uid1].__contains__(uid2), 0\n elif not valid_flw.__contains__(uid1) and valid_flw.__contains__(uid2):\n return flw_dict[uid2].__contains__(uid1), 0\n else:\n return 2, len(list(a for a in flw_dict[uid1] if a in flw_dict[uid2])\n ) / (len(flw_dict[uid1]) + len(flw_dict[uid2]) - len(list(a for\n a in flw_dict[uid1] if a in flw_dict[uid2])))\n\n\n<mask token>\n", "step-2": "<mask token>\nlogging.basicConfig(level=logging.INFO)\n<mask token>\nuser_file.close()\n<mask token>\nfor items in user_gp:\n users = items.strip().split()\n same_line_dict.update({x: users for x in users})\n<mask token>\ninfo_file.close()\n<mask token>\nfor line in info_data:\n tmp_str = line.strip()\n try:\n tmp_dict = json.loads(tmp_str)\n k = list(tmp_dict.keys())\n v = tmp_dict[k[0]]\n info_dict.update({k[0]: v})\n except:\n logging.warning('Invalid Data!')\n continue\n<mask token>\nprint(user_num)\n<mask token>\nflw_file.close()\n<mask token>\nfor lines in flw_data:\n items = lines.strip().split()\n flw_dict[items[0]] = items[2:]\n<mask token>\nprint(len(flw_dict))\n\n\ndef gen_label(uid1, uid2):\n if same_line_dict[uid1].__contains__(uid2) and same_line_dict[uid2\n ].__contains__(uid1):\n return '1'\n else:\n return '-1'\n\n\n<mask token>\n\n\ndef get_info(uid):\n if info_dict[uid] == []:\n return False, {}\n tdict = {'text': '', 'textLength': 0, 'source': '', 'id': '',\n 'screen_name': '', 'statuses_count': 0, 'verified': False,\n 'verified_type': -1, 'description': '', 'gender': '', 'urank': 0,\n 'followers_count': 0, 'follow_count': 0, 'reposts_count': 0,\n 'comments_count': 0, 'attitudes_count': 0, 'isLongText': False}\n latest_po = info_dict[uid][0]['mblog']\n user_info = latest_po['user']\n for elem in info_keys[0:3]:\n if list(latest_po.keys()).__contains__(elem):\n tdict.update({elem: latest_po[elem]})\n for elem in info_keys[3:]:\n if list(user_info.keys()).__contains__(elem):\n tdict.update({elem: user_info[elem]})\n return True, tdict\n\n\ndef gen_data(dict1, dict2):\n result = []\n if dict1['verified'] and dict2['verified']:\n verified = -1\n elif dict1['verified'] or dict2['verified']:\n verified = 1\n else:\n verified = 0\n result.append(verified)\n bool_style = ['verified_type', 'gender', 'isLongText']\n for items in bool_style:\n result.append(1 if dict1[items] == dict2[items] else 0)\n result.append(abs(dict1['urank'] - dict2['urank']))\n result.append(abs(dict1['statuses_count'] - dict2['statuses_count']))\n result.append(abs(dict1['followers_count'] - dict2['followers_count']) /\n abs(dict1['followers_count'] + dict2['followers_count']) if abs(\n dict1['followers_count'] + dict2['followers_count']) != 0 else 1)\n result.append(abs(dict1['follow_count'] - dict2['follow_count']) / abs(\n dict1['follow_count'] + dict2['follow_count']) if abs(dict1[\n 'follow_count'] + dict2['follow_count']) != 0 else 1)\n result.append(abs(dict1['reposts_count'] - dict2['reposts_count']))\n result.append(abs(dict1['comments_count'] - dict2['comments_count']))\n result.append(abs(dict1['attitudes_count'] - dict2['attitudes_count']))\n result.append(Levenshtein.jaro_winkler(dict1['screen_name'], dict2[\n 'screen_name']))\n result.append(Levenshtein.jaro_winkler(dict1['description'], dict2[\n 'description']))\n result.append(Levenshtein.jaro_winkler(dict1['text'], dict2['text']))\n return result\n\n\ndef gen_flw(uid1, uid2):\n if not valid_flw.__contains__(uid1) and not valid_flw.__contains__(uid2):\n return 0, 0\n elif valid_flw.__contains__(uid1) and not valid_flw.__contains__(uid2):\n return flw_dict[uid1].__contains__(uid2), 0\n elif not valid_flw.__contains__(uid1) and valid_flw.__contains__(uid2):\n return flw_dict[uid2].__contains__(uid1), 0\n else:\n return 2, len(list(a for a in flw_dict[uid1] if a in flw_dict[uid2])\n ) / (len(flw_dict[uid1]) + len(flw_dict[uid2]) - len(list(a for\n a in flw_dict[uid1] if a in flw_dict[uid2])))\n\n\nlogging.info('Prepare Data!')\n<mask token>\nfor i in range(0, train_num):\n order1 = random.randint(0, user_num - 1)\n order2 = random.randint(0, user_num - 1)\n uid1 = valid_users[order1]\n uid2 = same_line_dict[uid1][random.randint(0, len(same_line_dict[uid1]) -\n 1)]\n flag1, dict1 = get_info(uid1)\n flag2, dict2 = get_info(uid2)\n while uid1 == uid2 or uidpool.__contains__([uid1, uid2]\n ) or not flag1 or not flag2:\n order1 = random.randint(0, user_num - 1)\n order2 = random.randint(0, user_num - 1)\n uid1 = valid_users[order1]\n uid2 = valid_users[order2]\n flag1, dict1 = get_info(uid1)\n flag2, dict2 = get_info(uid2)\n uidpool.append([uid1, uid2])\n uidpool.append([uid2, uid1])\n tmp_data = gen_data(dict1, dict2)\n flw1, flw2 = gen_flw(uid1, uid2)\n tmp_data.append(flw1)\n tmp_data.append(flw2)\n data.append(tmp_data)\n labels.append(gen_label(uid1, uid2))\nprint(data)\nprint(labels)\nprint('total number:', train_num)\nprint('total positive samples:', labels.count('1'))\nlogging.info('Start Training!')\n<mask token>\nfor order in range(0, 10):\n ratio = 9 / 10\n train_data = []\n train_labels = []\n test_data = []\n test_labels = []\n for i in range(0, train_num):\n if random.random() > ratio:\n test_data.append(data[i])\n test_labels.append(labels[i])\n else:\n train_data.append(data[i])\n train_labels.append(labels[i])\n rf.fit(train_data, train_labels)\n logging.info('Train Done!')\n acc = rf.score(data, labels)\n accur.append(acc)\n<mask token>\nprint('Feature Weight:')\n<mask token>\nfor i in range(0, 16):\n print(features[i], ':', rf.feature_importances_[i])\nprint('Total accuracy', rf.score(data, labels))\n<mask token>\nprint(sum(scores) / 10)\nprint('time:', end_time - begin_time)\n", "step-3": "<mask token>\nlogging.basicConfig(level=logging.INFO)\nuser_file = open('groundtruth.txt')\nuser_gp = user_file.readlines()\nuser_file.close()\nsame_line_dict = {}\nfor items in user_gp:\n users = items.strip().split()\n same_line_dict.update({x: users for x in users})\ninfo_file = codecs.open('new_posts.txt', 'r', 'utf-8')\ninfo_data = info_file.readlines()\ninfo_file.close()\ninfo_dict = {}\nfor line in info_data:\n tmp_str = line.strip()\n try:\n tmp_dict = json.loads(tmp_str)\n k = list(tmp_dict.keys())\n v = tmp_dict[k[0]]\n info_dict.update({k[0]: v})\n except:\n logging.warning('Invalid Data!')\n continue\nvalid_users = list(info_dict.keys())\nuser_num = len(valid_users)\nprint(user_num)\nflw_file = open('new_followings.txt')\nflw_data = flw_file.readlines()\nflw_file.close()\nflw_dict = {}\nfor lines in flw_data:\n items = lines.strip().split()\n flw_dict[items[0]] = items[2:]\nvalid_flw = list(flw_dict.keys())\nprint(len(flw_dict))\n\n\ndef gen_label(uid1, uid2):\n if same_line_dict[uid1].__contains__(uid2) and same_line_dict[uid2\n ].__contains__(uid1):\n return '1'\n else:\n return '-1'\n\n\ninfo_keys = ['text', 'textLength', 'source', 'id', 'screen_name',\n 'statuses_count', 'verified', 'verified_type', 'description', 'gender',\n 'urank', 'followers_count', 'follow_count', 'reposts_count',\n 'comments_count', 'attitudes_count', 'isLongText']\n\n\ndef get_info(uid):\n if info_dict[uid] == []:\n return False, {}\n tdict = {'text': '', 'textLength': 0, 'source': '', 'id': '',\n 'screen_name': '', 'statuses_count': 0, 'verified': False,\n 'verified_type': -1, 'description': '', 'gender': '', 'urank': 0,\n 'followers_count': 0, 'follow_count': 0, 'reposts_count': 0,\n 'comments_count': 0, 'attitudes_count': 0, 'isLongText': False}\n latest_po = info_dict[uid][0]['mblog']\n user_info = latest_po['user']\n for elem in info_keys[0:3]:\n if list(latest_po.keys()).__contains__(elem):\n tdict.update({elem: latest_po[elem]})\n for elem in info_keys[3:]:\n if list(user_info.keys()).__contains__(elem):\n tdict.update({elem: user_info[elem]})\n return True, tdict\n\n\ndef gen_data(dict1, dict2):\n result = []\n if dict1['verified'] and dict2['verified']:\n verified = -1\n elif dict1['verified'] or dict2['verified']:\n verified = 1\n else:\n verified = 0\n result.append(verified)\n bool_style = ['verified_type', 'gender', 'isLongText']\n for items in bool_style:\n result.append(1 if dict1[items] == dict2[items] else 0)\n result.append(abs(dict1['urank'] - dict2['urank']))\n result.append(abs(dict1['statuses_count'] - dict2['statuses_count']))\n result.append(abs(dict1['followers_count'] - dict2['followers_count']) /\n abs(dict1['followers_count'] + dict2['followers_count']) if abs(\n dict1['followers_count'] + dict2['followers_count']) != 0 else 1)\n result.append(abs(dict1['follow_count'] - dict2['follow_count']) / abs(\n dict1['follow_count'] + dict2['follow_count']) if abs(dict1[\n 'follow_count'] + dict2['follow_count']) != 0 else 1)\n result.append(abs(dict1['reposts_count'] - dict2['reposts_count']))\n result.append(abs(dict1['comments_count'] - dict2['comments_count']))\n result.append(abs(dict1['attitudes_count'] - dict2['attitudes_count']))\n result.append(Levenshtein.jaro_winkler(dict1['screen_name'], dict2[\n 'screen_name']))\n result.append(Levenshtein.jaro_winkler(dict1['description'], dict2[\n 'description']))\n result.append(Levenshtein.jaro_winkler(dict1['text'], dict2['text']))\n return result\n\n\ndef gen_flw(uid1, uid2):\n if not valid_flw.__contains__(uid1) and not valid_flw.__contains__(uid2):\n return 0, 0\n elif valid_flw.__contains__(uid1) and not valid_flw.__contains__(uid2):\n return flw_dict[uid1].__contains__(uid2), 0\n elif not valid_flw.__contains__(uid1) and valid_flw.__contains__(uid2):\n return flw_dict[uid2].__contains__(uid1), 0\n else:\n return 2, len(list(a for a in flw_dict[uid1] if a in flw_dict[uid2])\n ) / (len(flw_dict[uid1]) + len(flw_dict[uid2]) - len(list(a for\n a in flw_dict[uid1] if a in flw_dict[uid2])))\n\n\nlogging.info('Prepare Data!')\ntrain_num = 8000\ndata = []\nlabels = []\nuidpool = []\nfor i in range(0, train_num):\n order1 = random.randint(0, user_num - 1)\n order2 = random.randint(0, user_num - 1)\n uid1 = valid_users[order1]\n uid2 = same_line_dict[uid1][random.randint(0, len(same_line_dict[uid1]) -\n 1)]\n flag1, dict1 = get_info(uid1)\n flag2, dict2 = get_info(uid2)\n while uid1 == uid2 or uidpool.__contains__([uid1, uid2]\n ) or not flag1 or not flag2:\n order1 = random.randint(0, user_num - 1)\n order2 = random.randint(0, user_num - 1)\n uid1 = valid_users[order1]\n uid2 = valid_users[order2]\n flag1, dict1 = get_info(uid1)\n flag2, dict2 = get_info(uid2)\n uidpool.append([uid1, uid2])\n uidpool.append([uid2, uid1])\n tmp_data = gen_data(dict1, dict2)\n flw1, flw2 = gen_flw(uid1, uid2)\n tmp_data.append(flw1)\n tmp_data.append(flw2)\n data.append(tmp_data)\n labels.append(gen_label(uid1, uid2))\nprint(data)\nprint(labels)\nprint('total number:', train_num)\nprint('total positive samples:', labels.count('1'))\nlogging.info('Start Training!')\nrf = RandomForestClassifier(n_estimators=40, n_jobs=4, verbose=0)\naccur = []\nbegin_time = time.time()\nfor order in range(0, 10):\n ratio = 9 / 10\n train_data = []\n train_labels = []\n test_data = []\n test_labels = []\n for i in range(0, train_num):\n if random.random() > ratio:\n test_data.append(data[i])\n test_labels.append(labels[i])\n else:\n train_data.append(data[i])\n train_labels.append(labels[i])\n rf.fit(train_data, train_labels)\n logging.info('Train Done!')\n acc = rf.score(data, labels)\n accur.append(acc)\nend_time = time.time()\nprint('Feature Weight:')\nfeatures = ['verified', 'verified_type', 'gender', 'isLongText', 'urank',\n 'statuses_diff', 'followers_diff', 'follows_diff', 'reposts_diff',\n 'comment_diff', 'attitudes_diff', 'screen_name_similarity',\n 'description_similarity', 'text_similarity', 'co_follow', 'in_follows']\nfor i in range(0, 16):\n print(features[i], ':', rf.feature_importances_[i])\nprint('Total accuracy', rf.score(data, labels))\nscores = cross_val_score(rf, data, labels, cv=10)\nprint(sum(scores) / 10)\nprint('time:', end_time - begin_time)\n", "step-4": "import json\nimport codecs\nimport Levenshtein\nimport logging\nimport random\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import cross_val_score\nimport time\nfrom sklearn.model_selection import KFold\nimport numpy as np\nimport scipy.io as scio\nfrom matplotlib import pyplot as plt\nlogging.basicConfig(level=logging.INFO)\nuser_file = open('groundtruth.txt')\nuser_gp = user_file.readlines()\nuser_file.close()\nsame_line_dict = {}\nfor items in user_gp:\n users = items.strip().split()\n same_line_dict.update({x: users for x in users})\ninfo_file = codecs.open('new_posts.txt', 'r', 'utf-8')\ninfo_data = info_file.readlines()\ninfo_file.close()\ninfo_dict = {}\nfor line in info_data:\n tmp_str = line.strip()\n try:\n tmp_dict = json.loads(tmp_str)\n k = list(tmp_dict.keys())\n v = tmp_dict[k[0]]\n info_dict.update({k[0]: v})\n except:\n logging.warning('Invalid Data!')\n continue\nvalid_users = list(info_dict.keys())\nuser_num = len(valid_users)\nprint(user_num)\nflw_file = open('new_followings.txt')\nflw_data = flw_file.readlines()\nflw_file.close()\nflw_dict = {}\nfor lines in flw_data:\n items = lines.strip().split()\n flw_dict[items[0]] = items[2:]\nvalid_flw = list(flw_dict.keys())\nprint(len(flw_dict))\n\n\ndef gen_label(uid1, uid2):\n if same_line_dict[uid1].__contains__(uid2) and same_line_dict[uid2\n ].__contains__(uid1):\n return '1'\n else:\n return '-1'\n\n\ninfo_keys = ['text', 'textLength', 'source', 'id', 'screen_name',\n 'statuses_count', 'verified', 'verified_type', 'description', 'gender',\n 'urank', 'followers_count', 'follow_count', 'reposts_count',\n 'comments_count', 'attitudes_count', 'isLongText']\n\n\ndef get_info(uid):\n if info_dict[uid] == []:\n return False, {}\n tdict = {'text': '', 'textLength': 0, 'source': '', 'id': '',\n 'screen_name': '', 'statuses_count': 0, 'verified': False,\n 'verified_type': -1, 'description': '', 'gender': '', 'urank': 0,\n 'followers_count': 0, 'follow_count': 0, 'reposts_count': 0,\n 'comments_count': 0, 'attitudes_count': 0, 'isLongText': False}\n latest_po = info_dict[uid][0]['mblog']\n user_info = latest_po['user']\n for elem in info_keys[0:3]:\n if list(latest_po.keys()).__contains__(elem):\n tdict.update({elem: latest_po[elem]})\n for elem in info_keys[3:]:\n if list(user_info.keys()).__contains__(elem):\n tdict.update({elem: user_info[elem]})\n return True, tdict\n\n\ndef gen_data(dict1, dict2):\n result = []\n if dict1['verified'] and dict2['verified']:\n verified = -1\n elif dict1['verified'] or dict2['verified']:\n verified = 1\n else:\n verified = 0\n result.append(verified)\n bool_style = ['verified_type', 'gender', 'isLongText']\n for items in bool_style:\n result.append(1 if dict1[items] == dict2[items] else 0)\n result.append(abs(dict1['urank'] - dict2['urank']))\n result.append(abs(dict1['statuses_count'] - dict2['statuses_count']))\n result.append(abs(dict1['followers_count'] - dict2['followers_count']) /\n abs(dict1['followers_count'] + dict2['followers_count']) if abs(\n dict1['followers_count'] + dict2['followers_count']) != 0 else 1)\n result.append(abs(dict1['follow_count'] - dict2['follow_count']) / abs(\n dict1['follow_count'] + dict2['follow_count']) if abs(dict1[\n 'follow_count'] + dict2['follow_count']) != 0 else 1)\n result.append(abs(dict1['reposts_count'] - dict2['reposts_count']))\n result.append(abs(dict1['comments_count'] - dict2['comments_count']))\n result.append(abs(dict1['attitudes_count'] - dict2['attitudes_count']))\n result.append(Levenshtein.jaro_winkler(dict1['screen_name'], dict2[\n 'screen_name']))\n result.append(Levenshtein.jaro_winkler(dict1['description'], dict2[\n 'description']))\n result.append(Levenshtein.jaro_winkler(dict1['text'], dict2['text']))\n return result\n\n\ndef gen_flw(uid1, uid2):\n if not valid_flw.__contains__(uid1) and not valid_flw.__contains__(uid2):\n return 0, 0\n elif valid_flw.__contains__(uid1) and not valid_flw.__contains__(uid2):\n return flw_dict[uid1].__contains__(uid2), 0\n elif not valid_flw.__contains__(uid1) and valid_flw.__contains__(uid2):\n return flw_dict[uid2].__contains__(uid1), 0\n else:\n return 2, len(list(a for a in flw_dict[uid1] if a in flw_dict[uid2])\n ) / (len(flw_dict[uid1]) + len(flw_dict[uid2]) - len(list(a for\n a in flw_dict[uid1] if a in flw_dict[uid2])))\n\n\nlogging.info('Prepare Data!')\ntrain_num = 8000\ndata = []\nlabels = []\nuidpool = []\nfor i in range(0, train_num):\n order1 = random.randint(0, user_num - 1)\n order2 = random.randint(0, user_num - 1)\n uid1 = valid_users[order1]\n uid2 = same_line_dict[uid1][random.randint(0, len(same_line_dict[uid1]) -\n 1)]\n flag1, dict1 = get_info(uid1)\n flag2, dict2 = get_info(uid2)\n while uid1 == uid2 or uidpool.__contains__([uid1, uid2]\n ) or not flag1 or not flag2:\n order1 = random.randint(0, user_num - 1)\n order2 = random.randint(0, user_num - 1)\n uid1 = valid_users[order1]\n uid2 = valid_users[order2]\n flag1, dict1 = get_info(uid1)\n flag2, dict2 = get_info(uid2)\n uidpool.append([uid1, uid2])\n uidpool.append([uid2, uid1])\n tmp_data = gen_data(dict1, dict2)\n flw1, flw2 = gen_flw(uid1, uid2)\n tmp_data.append(flw1)\n tmp_data.append(flw2)\n data.append(tmp_data)\n labels.append(gen_label(uid1, uid2))\nprint(data)\nprint(labels)\nprint('total number:', train_num)\nprint('total positive samples:', labels.count('1'))\nlogging.info('Start Training!')\nrf = RandomForestClassifier(n_estimators=40, n_jobs=4, verbose=0)\naccur = []\nbegin_time = time.time()\nfor order in range(0, 10):\n ratio = 9 / 10\n train_data = []\n train_labels = []\n test_data = []\n test_labels = []\n for i in range(0, train_num):\n if random.random() > ratio:\n test_data.append(data[i])\n test_labels.append(labels[i])\n else:\n train_data.append(data[i])\n train_labels.append(labels[i])\n rf.fit(train_data, train_labels)\n logging.info('Train Done!')\n acc = rf.score(data, labels)\n accur.append(acc)\nend_time = time.time()\nprint('Feature Weight:')\nfeatures = ['verified', 'verified_type', 'gender', 'isLongText', 'urank',\n 'statuses_diff', 'followers_diff', 'follows_diff', 'reposts_diff',\n 'comment_diff', 'attitudes_diff', 'screen_name_similarity',\n 'description_similarity', 'text_similarity', 'co_follow', 'in_follows']\nfor i in range(0, 16):\n print(features[i], ':', rf.feature_importances_[i])\nprint('Total accuracy', rf.score(data, labels))\nscores = cross_val_score(rf, data, labels, cv=10)\nprint(sum(scores) / 10)\nprint('time:', end_time - begin_time)\n", "step-5": "#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\nimport json\r\nimport codecs\r\nimport Levenshtein\r\nimport logging\r\nimport random\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.model_selection import cross_val_score\r\nimport time\r\nfrom sklearn.model_selection import KFold\r\nimport numpy as np\r\nimport scipy.io as scio\r\nfrom matplotlib import pyplot as plt\r\n\r\nlogging.basicConfig(level=logging.INFO)\r\n\r\nuser_file = open('groundtruth.txt')\r\nuser_gp = user_file.readlines()\r\nuser_file.close()\r\nsame_line_dict = {}\r\nfor items in user_gp:\r\n users = items.strip().split()\r\n same_line_dict.update({x: users for x in users})\r\n# print(same_line_dict)\r\n\r\ninfo_file = codecs.open('new_posts.txt', 'r', 'utf-8')\r\ninfo_data = info_file.readlines()\r\ninfo_file.close()\r\ninfo_dict = {}\r\nfor line in info_data:\r\n tmp_str = line.strip()\r\n # print(tmp_str)\r\n try:\r\n tmp_dict = json.loads(tmp_str)\r\n k = list(tmp_dict.keys())\r\n # print(k)\r\n v = tmp_dict[k[0]]\r\n info_dict.update({k[0]: v})\r\n except:\r\n logging.warning('Invalid Data!')\r\n continue\r\n\r\nvalid_users = list(info_dict.keys())\r\nuser_num = len(valid_users)\r\nprint(user_num)\r\n\r\nflw_file = open('new_followings.txt')\r\nflw_data = flw_file.readlines()\r\nflw_file.close()\r\nflw_dict = {}\r\nfor lines in flw_data:\r\n items = lines.strip().split()\r\n flw_dict[items[0]] = items[2:]\r\nvalid_flw = list(flw_dict.keys())\r\nprint(len(flw_dict))\r\n\r\n\r\ndef gen_label(uid1, uid2):\r\n if same_line_dict[uid1].__contains__(uid2) and same_line_dict[uid2].__contains__(uid1):\r\n return '1'\r\n else:\r\n return '-1'\r\n\r\n\r\ninfo_keys = ['text', 'textLength', 'source', 'id', 'screen_name',\r\n 'statuses_count', 'verified', 'verified_type',\r\n 'description', 'gender', 'urank', 'followers_count',\r\n 'follow_count', 'reposts_count', 'comments_count',\r\n 'attitudes_count', 'isLongText']\r\n\r\n\r\ndef get_info(uid):\r\n if info_dict[uid] == []:\r\n return False, {}\r\n tdict = {\r\n 'text': '',\r\n 'textLength': 0,\r\n 'source': '',\r\n 'id': '',\r\n 'screen_name': '',\r\n 'statuses_count': 0,\r\n 'verified': False,\r\n 'verified_type': -1,\r\n 'description': '',\r\n 'gender': '',\r\n 'urank': 0,\r\n 'followers_count': 0,\r\n 'follow_count': 0,\r\n 'reposts_count': 0,\r\n 'comments_count': 0,\r\n 'attitudes_count': 0,\r\n 'isLongText': False\r\n }\r\n # print(info_dict[uid])\r\n latest_po = info_dict[uid][0]['mblog']\r\n user_info = latest_po['user']\r\n # print(latest_po)\r\n # print(user_info)\r\n for elem in info_keys[0:3]:\r\n if list(latest_po.keys()).__contains__(elem):\r\n tdict.update({elem: latest_po[elem]})\r\n for elem in info_keys[3:]:\r\n if list(user_info.keys()).__contains__(elem):\r\n tdict.update({elem: user_info[elem]})\r\n return True, tdict\r\n\r\n\r\ndef gen_data(dict1, dict2):\r\n result = []\r\n if dict1['verified'] and dict2['verified']:\r\n verified = -1\r\n elif dict1['verified'] or dict2['verified']:\r\n verified = 1\r\n else:\r\n verified = 0\r\n result.append(verified)\r\n bool_style = ['verified_type', 'gender', 'isLongText']\r\n for items in bool_style:\r\n result.append(1 if dict1[items] == dict2[items] else 0)\r\n result.append(abs(dict1['urank'] - dict2['urank']))\r\n result.append(abs(dict1['statuses_count'] - dict2['statuses_count']))\r\n result.append(abs(dict1['followers_count'] - dict2['followers_count'])\r\n / abs(dict1['followers_count'] + dict2['followers_count'])\r\n if abs(dict1['followers_count'] + dict2['followers_count']) != 0\r\n else 1)\r\n result.append(abs(dict1['follow_count'] - dict2['follow_count'])\r\n / abs(dict1['follow_count'] + dict2['follow_count'])\r\n if abs(dict1['follow_count'] + dict2['follow_count']) != 0\r\n else 1\r\n )\r\n result.append(abs(dict1['reposts_count'] - dict2['reposts_count']))\r\n result.append(abs(dict1['comments_count'] - dict2['comments_count']))\r\n result.append(abs(dict1['attitudes_count'] - dict2['attitudes_count']))\r\n result.append(Levenshtein.jaro_winkler(dict1['screen_name'], dict2['screen_name']))\r\n result.append(Levenshtein.jaro_winkler(dict1['description'], dict2['description']))\r\n result.append(Levenshtein.jaro_winkler(dict1['text'], dict2['text']))\r\n return result\r\n\r\n\r\ndef gen_flw(uid1, uid2):\r\n if not valid_flw.__contains__(uid1) and not valid_flw.__contains__(uid2):\r\n return 0, 0\r\n elif valid_flw.__contains__(uid1) and not valid_flw.__contains__(uid2):\r\n return flw_dict[uid1].__contains__(uid2), 0\r\n elif not valid_flw.__contains__(uid1) and valid_flw.__contains__(uid2):\r\n return flw_dict[uid2].__contains__(uid1), 0\r\n else:\r\n return 2, len(list(a for a in flw_dict[uid1] if a in flw_dict[uid2])) \\\r\n / (\r\n len(flw_dict[uid1]) + len(flw_dict[uid2]) - len(\r\n list(a for a in flw_dict[uid1] if a in flw_dict[uid2])))\r\n\r\n\r\nlogging.info('Prepare Data!')\r\ntrain_num = 8000\r\ndata = []\r\nlabels = []\r\nuidpool = []\r\nfor i in range(0, train_num):\r\n order1 = random.randint(0, user_num - 1)\r\n order2 = random.randint(0, user_num - 1)\r\n uid1 = valid_users[order1]\r\n uid2 = same_line_dict[uid1][random.randint(0, len(same_line_dict[uid1]) - 1)]\r\n # uid2 = valid_users[order2]\r\n # if random.random() >= 0:\r\n # # print('+-1')\r\n # uid2 = same_line_dict[uid1][random.randint(0, len(same_line_dict[uid1]) - 1)]\r\n flag1, dict1 = get_info(uid1)\r\n flag2, dict2 = get_info(uid2)\r\n while (uid1 == uid2 or uidpool.__contains__([uid1, uid2]) or not flag1 or not flag2):\r\n order1 = random.randint(0, user_num - 1)\r\n order2 = random.randint(0, user_num - 1)\r\n uid1 = valid_users[order1]\r\n uid2 = valid_users[order2]\r\n flag1, dict1 = get_info(uid1)\r\n flag2, dict2 = get_info(uid2)\r\n uidpool.append([uid1, uid2])\r\n uidpool.append([uid2, uid1])\r\n tmp_data = gen_data(dict1, dict2)\r\n flw1, flw2 = gen_flw(uid1, uid2)\r\n # data.append(gen_data(dict1, dict2))\r\n tmp_data.append(flw1)\r\n tmp_data.append(flw2)\r\n data.append(tmp_data)\r\n labels.append(gen_label(uid1, uid2))\r\n # print(uid1, uid2)\r\nprint(data)\r\nprint(labels)\r\nprint('total number:', train_num)\r\nprint('total positive samples:', labels.count('1'))\r\n\r\nlogging.info('Start Training!')\r\nrf = RandomForestClassifier(n_estimators=40, n_jobs=4, verbose=0)\r\naccur = []\r\nbegin_time=time.time()\r\nfor order in range(0, 10):\r\n ratio = 9 / 10\r\n train_data = []\r\n train_labels = []\r\n test_data = []\r\n test_labels = []\r\n for i in range(0, train_num):\r\n if random.random() > ratio:\r\n test_data.append(data[i])\r\n test_labels.append(labels[i])\r\n else:\r\n train_data.append(data[i])\r\n train_labels.append(labels[i])\r\n\r\n # print('train number:', len(train_labels))\r\n # print('train positive samples:', train_labels.count('1'))\r\n rf.fit(train_data, train_labels)\r\n\r\n logging.info('Train Done!')\r\n\r\n # print('Train accuracy:',\r\n # rf.score(train_data, train_labels))\r\n # print('Test accuracy:',\r\n # rf.score(test_data, test_labels))\r\n acc = rf.score(data, labels)\r\n # print('Total accuracy:', acc)\r\n accur.append(acc)\r\nend_time=time.time()\r\nprint('Feature Weight:')\r\n# print('Feature Weight:', rf.feature_importances_)\r\nfeatures = ['verified', 'verified_type', 'gender', 'isLongText', 'urank', 'statuses_diff',\r\n 'followers_diff', 'follows_diff', 'reposts_diff', 'comment_diff', 'attitudes_diff',\r\n 'screen_name_similarity', 'description_similarity', 'text_similarity', 'co_follow', 'in_follows']\r\nfor i in range(0, 16):\r\n print(features[i], ':', rf.feature_importances_[i])\r\n\r\nprint('Total accuracy', rf.score(data, labels))\r\n\r\nscores = cross_val_score(rf, data, labels, cv=10)\r\nprint(sum(scores) / 10)\r\n\r\nprint('time:',end_time-begin_time)\r\n", "step-ids": [ 2, 5, 6, 7, 8 ] }
[ 2, 5, 6, 7, 8 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> def create_logger(log_level: str='INFO', log_name: str='logfile', export_log: bool=True, save_dir: str=''): if log_name in loggers.keys(): logger = loggers.get(log_name) else: logger = logging.getLogger(log_name) logger.setLevel(logging.DEBUG) handler1 = logging.StreamHandler() handler1.setLevel(log_level) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler1.setFormatter(formatter) logger.addHandler(handler1) if export_log: pathname = log_name if len(save_dir) > 0: pathname = f'{save_dir}/{pathname}' handler2 = logging.FileHandler(filename=f'{pathname}.log', mode='w' ) handler2.setLevel('DEBUG') handler2.setFormatter(formatter) logger.addHandler(handler2) loggers[log_name] = logger return logger <|reserved_special_token_1|> <|reserved_special_token_0|> loggers = {} def create_logger(log_level: str='INFO', log_name: str='logfile', export_log: bool=True, save_dir: str=''): if log_name in loggers.keys(): logger = loggers.get(log_name) else: logger = logging.getLogger(log_name) logger.setLevel(logging.DEBUG) handler1 = logging.StreamHandler() handler1.setLevel(log_level) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler1.setFormatter(formatter) logger.addHandler(handler1) if export_log: pathname = log_name if len(save_dir) > 0: pathname = f'{save_dir}/{pathname}' handler2 = logging.FileHandler(filename=f'{pathname}.log', mode='w' ) handler2.setLevel('DEBUG') handler2.setFormatter(formatter) logger.addHandler(handler2) loggers[log_name] = logger return logger <|reserved_special_token_1|> import logging loggers = {} def create_logger(log_level: str='INFO', log_name: str='logfile', export_log: bool=True, save_dir: str=''): if log_name in loggers.keys(): logger = loggers.get(log_name) else: logger = logging.getLogger(log_name) logger.setLevel(logging.DEBUG) handler1 = logging.StreamHandler() handler1.setLevel(log_level) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler1.setFormatter(formatter) logger.addHandler(handler1) if export_log: pathname = log_name if len(save_dir) > 0: pathname = f'{save_dir}/{pathname}' handler2 = logging.FileHandler(filename=f'{pathname}.log', mode='w' ) handler2.setLevel('DEBUG') handler2.setFormatter(formatter) logger.addHandler(handler2) loggers[log_name] = logger return logger <|reserved_special_token_1|> import logging loggers = {} def create_logger( log_level:str ='INFO', log_name:str = 'logfile', export_log: bool = True, save_dir:str = ''): if log_name in loggers.keys(): logger = loggers.get(log_name) else: # create logger logger = logging.getLogger(log_name) logger.setLevel(logging.DEBUG) # create console handler and set level to debug handler1 = logging.StreamHandler() handler1.setLevel(log_level) # create formatter formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # add formatter to ch handler1.setFormatter(formatter) # add ch to logger logger.addHandler(handler1) if export_log: pathname = log_name if len(save_dir)>0: pathname = f'{save_dir}/{pathname}' handler2 = logging.FileHandler(filename=f'{pathname}.log', mode='w') handler2.setLevel('DEBUG') handler2.setFormatter(formatter) logger.addHandler(handler2) loggers[log_name] = logger return logger
flexible
{ "blob_id": "3146775c466368c25c92bd6074abb97408533500", "index": 2956, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef create_logger(log_level: str='INFO', log_name: str='logfile',\n export_log: bool=True, save_dir: str=''):\n if log_name in loggers.keys():\n logger = loggers.get(log_name)\n else:\n logger = logging.getLogger(log_name)\n logger.setLevel(logging.DEBUG)\n handler1 = logging.StreamHandler()\n handler1.setLevel(log_level)\n formatter = logging.Formatter(\n '%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n handler1.setFormatter(formatter)\n logger.addHandler(handler1)\n if export_log:\n pathname = log_name\n if len(save_dir) > 0:\n pathname = f'{save_dir}/{pathname}'\n handler2 = logging.FileHandler(filename=f'{pathname}.log', mode='w'\n )\n handler2.setLevel('DEBUG')\n handler2.setFormatter(formatter)\n logger.addHandler(handler2)\n loggers[log_name] = logger\n return logger\n", "step-3": "<mask token>\nloggers = {}\n\n\ndef create_logger(log_level: str='INFO', log_name: str='logfile',\n export_log: bool=True, save_dir: str=''):\n if log_name in loggers.keys():\n logger = loggers.get(log_name)\n else:\n logger = logging.getLogger(log_name)\n logger.setLevel(logging.DEBUG)\n handler1 = logging.StreamHandler()\n handler1.setLevel(log_level)\n formatter = logging.Formatter(\n '%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n handler1.setFormatter(formatter)\n logger.addHandler(handler1)\n if export_log:\n pathname = log_name\n if len(save_dir) > 0:\n pathname = f'{save_dir}/{pathname}'\n handler2 = logging.FileHandler(filename=f'{pathname}.log', mode='w'\n )\n handler2.setLevel('DEBUG')\n handler2.setFormatter(formatter)\n logger.addHandler(handler2)\n loggers[log_name] = logger\n return logger\n", "step-4": "import logging\nloggers = {}\n\n\ndef create_logger(log_level: str='INFO', log_name: str='logfile',\n export_log: bool=True, save_dir: str=''):\n if log_name in loggers.keys():\n logger = loggers.get(log_name)\n else:\n logger = logging.getLogger(log_name)\n logger.setLevel(logging.DEBUG)\n handler1 = logging.StreamHandler()\n handler1.setLevel(log_level)\n formatter = logging.Formatter(\n '%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n handler1.setFormatter(formatter)\n logger.addHandler(handler1)\n if export_log:\n pathname = log_name\n if len(save_dir) > 0:\n pathname = f'{save_dir}/{pathname}'\n handler2 = logging.FileHandler(filename=f'{pathname}.log', mode='w'\n )\n handler2.setLevel('DEBUG')\n handler2.setFormatter(formatter)\n logger.addHandler(handler2)\n loggers[log_name] = logger\n return logger\n", "step-5": "import logging\n\nloggers = {} \n\ndef create_logger(\n log_level:str ='INFO', \n log_name:str = 'logfile',\n export_log: bool = True,\n save_dir:str = ''):\n if log_name in loggers.keys():\n logger = loggers.get(log_name)\n else:\n # create logger\n logger = logging.getLogger(log_name)\n logger.setLevel(logging.DEBUG)\n\n # create console handler and set level to debug\n handler1 = logging.StreamHandler()\n handler1.setLevel(log_level)\n\n # create formatter\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n # add formatter to ch\n handler1.setFormatter(formatter)\n\n # add ch to logger\n logger.addHandler(handler1)\n\n if export_log:\n pathname = log_name\n if len(save_dir)>0:\n pathname = f'{save_dir}/{pathname}'\n\n handler2 = logging.FileHandler(filename=f'{pathname}.log', mode='w')\n handler2.setLevel('DEBUG')\n handler2.setFormatter(formatter)\n logger.addHandler(handler2)\n \n loggers[log_name] = logger\n \n return logger\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
# Umut Cakan Computer Science S006742 # Fibonacci list. First and second terms are static. fib_list = [0, 1] # Current index. CURRENT_INDEX = 2 # Function for the checking input is a Fibonacci number or not. def check_fibonacci_number(): global CURRENT_INDEX # Get the fibonacci numbers that are less or equal to input value. # Because we will not need to check fib numbers that are higher than our input. while fib_list[CURRENT_INDEX - 1] < NUMBER_TO_BE_CHECKED: fib_list.append(fib_list[CURRENT_INDEX - 1] + fib_list[CURRENT_INDEX - 2]) CURRENT_INDEX += 1 # Check if the input value is in that list or not. if NUMBER_TO_BE_CHECKED not in fib_list: print("Your number is not a Fibonacci number.") else: print("Your number is a Fibonacci number.") # Get number to be checked from user. while True: try: NUMBER_TO_BE_CHECKED = int(input("Please enter the number to check: ")) # If it is not an integer throw an error and wait for another input. except ValueError: print("Your input is not an integer!") continue # If it is an integer, proceed. else: check_fibonacci_number() break
normal
{ "blob_id": "50fa8852f74f4d2428fb238a86dd1feedb210877", "index": 3261, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\ndef check_fibonacci_number():\n global CURRENT_INDEX\n while fib_list[CURRENT_INDEX - 1] < NUMBER_TO_BE_CHECKED:\n fib_list.append(fib_list[CURRENT_INDEX - 1] + fib_list[\n CURRENT_INDEX - 2])\n CURRENT_INDEX += 1\n if NUMBER_TO_BE_CHECKED not in fib_list:\n print('Your number is not a Fibonacci number.')\n else:\n print('Your number is a Fibonacci number.')\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\ndef check_fibonacci_number():\n global CURRENT_INDEX\n while fib_list[CURRENT_INDEX - 1] < NUMBER_TO_BE_CHECKED:\n fib_list.append(fib_list[CURRENT_INDEX - 1] + fib_list[\n CURRENT_INDEX - 2])\n CURRENT_INDEX += 1\n if NUMBER_TO_BE_CHECKED not in fib_list:\n print('Your number is not a Fibonacci number.')\n else:\n print('Your number is a Fibonacci number.')\n\n\nwhile True:\n try:\n NUMBER_TO_BE_CHECKED = int(input('Please enter the number to check: '))\n except ValueError:\n print('Your input is not an integer!')\n continue\n else:\n check_fibonacci_number()\n break\n", "step-4": "fib_list = [0, 1]\nCURRENT_INDEX = 2\n\n\ndef check_fibonacci_number():\n global CURRENT_INDEX\n while fib_list[CURRENT_INDEX - 1] < NUMBER_TO_BE_CHECKED:\n fib_list.append(fib_list[CURRENT_INDEX - 1] + fib_list[\n CURRENT_INDEX - 2])\n CURRENT_INDEX += 1\n if NUMBER_TO_BE_CHECKED not in fib_list:\n print('Your number is not a Fibonacci number.')\n else:\n print('Your number is a Fibonacci number.')\n\n\nwhile True:\n try:\n NUMBER_TO_BE_CHECKED = int(input('Please enter the number to check: '))\n except ValueError:\n print('Your input is not an integer!')\n continue\n else:\n check_fibonacci_number()\n break\n", "step-5": "# Umut Cakan Computer Science S006742\n\n# Fibonacci list. First and second terms are static.\nfib_list = [0, 1]\n# Current index.\nCURRENT_INDEX = 2\n\n# Function for the checking input is a Fibonacci number or not.\ndef check_fibonacci_number():\n global CURRENT_INDEX\n # Get the fibonacci numbers that are less or equal to input value.\n # Because we will not need to check fib numbers that are higher than our input.\n while fib_list[CURRENT_INDEX - 1] < NUMBER_TO_BE_CHECKED:\n fib_list.append(fib_list[CURRENT_INDEX - 1] + fib_list[CURRENT_INDEX - 2])\n CURRENT_INDEX += 1\n # Check if the input value is in that list or not.\n if NUMBER_TO_BE_CHECKED not in fib_list:\n print(\"Your number is not a Fibonacci number.\")\n else:\n print(\"Your number is a Fibonacci number.\")\n\n\n# Get number to be checked from user.\nwhile True:\n try:\n NUMBER_TO_BE_CHECKED = int(input(\"Please enter the number to check: \"))\n # If it is not an integer throw an error and wait for another input.\n except ValueError:\n print(\"Your input is not an integer!\")\n continue\n # If it is an integer, proceed. \n else:\n check_fibonacci_number()\n break\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
#!/usr/bin/env python # -*- coding: utf-8 -*- class CacheDecorator: def __init__(self): self.cache = {} self.func = None def cachedFunc(self, *args): if args not in self.cache: print("Ergebnis berechnet") self.cache[args] = self.func(*args) else: print("Ergebnis geladen") return self.cache[args] def __call__(self, func): self.func = func return self.cachedFunc @CacheDecorator() def fak(n): ergebnis = 1 for i in range(2, n+1): ergebnis *= i return ergebnis print(fak(10)) print(fak(20)) print(fak(20)) print(fak(10))
normal
{ "blob_id": "b7f6207fe6c013a964258255445004c3f4e0adbb", "index": 7217, "step-1": "class CacheDecorator:\n <mask token>\n\n def cachedFunc(self, *args):\n if args not in self.cache:\n print('Ergebnis berechnet')\n self.cache[args] = self.func(*args)\n else:\n print('Ergebnis geladen')\n return self.cache[args]\n\n def __call__(self, func):\n self.func = func\n return self.cachedFunc\n\n\n<mask token>\n", "step-2": "class CacheDecorator:\n\n def __init__(self):\n self.cache = {}\n self.func = None\n\n def cachedFunc(self, *args):\n if args not in self.cache:\n print('Ergebnis berechnet')\n self.cache[args] = self.func(*args)\n else:\n print('Ergebnis geladen')\n return self.cache[args]\n\n def __call__(self, func):\n self.func = func\n return self.cachedFunc\n\n\n<mask token>\n", "step-3": "class CacheDecorator:\n\n def __init__(self):\n self.cache = {}\n self.func = None\n\n def cachedFunc(self, *args):\n if args not in self.cache:\n print('Ergebnis berechnet')\n self.cache[args] = self.func(*args)\n else:\n print('Ergebnis geladen')\n return self.cache[args]\n\n def __call__(self, func):\n self.func = func\n return self.cachedFunc\n\n\n@CacheDecorator()\ndef fak(n):\n ergebnis = 1\n for i in range(2, n + 1):\n ergebnis *= i\n return ergebnis\n\n\n<mask token>\n", "step-4": "class CacheDecorator:\n\n def __init__(self):\n self.cache = {}\n self.func = None\n\n def cachedFunc(self, *args):\n if args not in self.cache:\n print('Ergebnis berechnet')\n self.cache[args] = self.func(*args)\n else:\n print('Ergebnis geladen')\n return self.cache[args]\n\n def __call__(self, func):\n self.func = func\n return self.cachedFunc\n\n\n@CacheDecorator()\ndef fak(n):\n ergebnis = 1\n for i in range(2, n + 1):\n ergebnis *= i\n return ergebnis\n\n\nprint(fak(10))\nprint(fak(20))\nprint(fak(20))\nprint(fak(10))\n", "step-5": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nclass CacheDecorator:\n def __init__(self):\n self.cache = {}\n self.func = None\n \n def cachedFunc(self, *args):\n if args not in self.cache:\n print(\"Ergebnis berechnet\")\n self.cache[args] = self.func(*args)\n else:\n print(\"Ergebnis geladen\")\n return self.cache[args]\n \n def __call__(self, func):\n self.func = func\n return self.cachedFunc\n\n@CacheDecorator()\ndef fak(n):\n ergebnis = 1\n for i in range(2, n+1):\n ergebnis *= i\n return ergebnis\n\nprint(fak(10))\nprint(fak(20))\nprint(fak(20))\nprint(fak(10))\n", "step-ids": [ 3, 4, 5, 6, 7 ] }
[ 3, 4, 5, 6, 7 ]
#common method to delete data from a list fruits=['orange','apple','mango','grapes','banana','apple','litchi'] #l=[] #[l.append(i) for i in fruits if i not in l] #print(l) print(set(fruits)) print(fruits.count("orange")) #pop method in a list used to delete last mathod from a list #fruits.pop()#items from if we a passing arguments then its delete specified items #print(fruits) #fruits.pop(4) #print(fruits) #del fruits[4]# to delete operater items we use delete operater in a list #print(fruits) #print(enumerate(fruits)) #c=enumerate(fruits) #print(c) # remove method in list # when we dont know the position of the item inside the list #print(fruits.remove('banana')) #print(fruits) #fruits.remove('apple') #print(fruits) #print("the new {} is : ".format(l)) #print(l) #print(set(fruits))
normal
{ "blob_id": "158b39a64d725bdbfc78acc346ed8335613ae099", "index": 8367, "step-1": "<mask token>\n", "step-2": "<mask token>\nprint(set(fruits))\nprint(fruits.count('orange'))\n", "step-3": "fruits = ['orange', 'apple', 'mango', 'grapes', 'banana', 'apple', 'litchi']\nprint(set(fruits))\nprint(fruits.count('orange'))\n", "step-4": "#common method to delete data from a list\r\nfruits=['orange','apple','mango','grapes','banana','apple','litchi']\r\n#l=[]\r\n\r\n#[l.append(i) for i in fruits if i not in l]\r\n\r\n#print(l)\r\nprint(set(fruits))\r\n\r\nprint(fruits.count(\"orange\"))\r\n\r\n\r\n\r\n\r\n \r\n \r\n#pop method in a list used to delete last mathod from a list\r\n#fruits.pop()#items from if we a passing arguments then its delete specified items\r\n#print(fruits)\r\n#fruits.pop(4)\r\n#print(fruits)\r\n#del fruits[4]# to delete operater items we use delete operater in a list\r\n#print(fruits)\r\n#print(enumerate(fruits))\r\n#c=enumerate(fruits)\r\n#print(c)\r\n# remove method in list\r\n# when we dont know the position of the item inside the list\r\n#print(fruits.remove('banana'))\r\n#print(fruits)\r\n#fruits.remove('apple')\r\n#print(fruits)\r\n\r\n#print(\"the new {} is : \".format(l))\r\n#print(l)\r\n#print(set(fruits))\r\n\r\n\r\n\r\n\r\n", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Solution: <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class Solution: def longestConsecutive(self, nums: List[int]) ->int: numset = set(nums) ans = 0 maxnum = float('-inf') if not nums: return 0 for n in numset: if n + 1 not in numset: ans = 1 saven = n while saven - 1 in numset: ans += 1 saven = saven - 1 maxnum = max(ans, maxnum) return maxnum <|reserved_special_token_1|> """ 100 4 200 1 3 2 100 4 200 1 3 2 6:35 """ class Solution: def longestConsecutive(self, nums: List[int]) -> int: numset = set(nums) ans = 0 # visited = set(nums) maxnum = float('-inf') if not nums: return 0 for n in numset: # saven = n if n+1 not in numset: ans = 1 saven = n while saven-1 in numset: ans +=1 saven = saven-1 # visited.add(n) maxnum = max(ans, maxnum) return maxnum # cnt = Counter(nums) # print(cnt) # maxnum = float('-inf') # minnum = float('inf') # ans = [minnum, maxnum] # visited = set() # def checknumber(checknum, cnt, ans): # minnum = ans[0] # maxnum = ans[1] # print('checknum', checknum, minnum, maxnum, visited) # if checknum in cnt and n not in visited: # minnum = min(checknum, minnum) # maxnum = max(checknum, maxnum) # visited.add(n) # if checknum-1 in cnt: # checknumber(checknum-1, cnt,[minnum, maxnum]) # if checknum+1 in cnt: # checknumber(checknum+1, cnt, [minnum, maxnum]) # for n in nums: # checknumber(n, cnt, [minnum, maxnum]) # return (ans[1]-ans[0])+1
flexible
{ "blob_id": "50c7ce95f17cbd40a753d16d9f9fab349ad4f4ce", "index": 3801, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass Solution:\n <mask token>\n", "step-3": "<mask token>\n\n\nclass Solution:\n\n def longestConsecutive(self, nums: List[int]) ->int:\n numset = set(nums)\n ans = 0\n maxnum = float('-inf')\n if not nums:\n return 0\n for n in numset:\n if n + 1 not in numset:\n ans = 1\n saven = n\n while saven - 1 in numset:\n ans += 1\n saven = saven - 1\n maxnum = max(ans, maxnum)\n return maxnum\n", "step-4": "\"\"\"\n 100 4 200 1 3 2\n100 \n4\n200\n1\n3\n2\n\n6:35\n\"\"\"\n\nclass Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n numset = set(nums)\n ans = 0\n # visited = set(nums)\n maxnum = float('-inf')\n \n if not nums: \n return 0\n \n for n in numset:\n # saven = n\n \n if n+1 not in numset:\n ans = 1\n saven = n\n\n while saven-1 in numset:\n ans +=1\n saven = saven-1\n # visited.add(n)\n\n maxnum = max(ans, maxnum)\n \n return maxnum\n \n \n \n \n \n # cnt = Counter(nums)\n# print(cnt)\n# maxnum = float('-inf')\n# minnum = float('inf')\n# ans = [minnum, maxnum]\n# visited = set()\n \n# def checknumber(checknum, cnt, ans):\n# minnum = ans[0]\n# maxnum = ans[1]\n# print('checknum', checknum, minnum, maxnum, visited)\n# if checknum in cnt and n not in visited:\n# minnum = min(checknum, minnum) \n# maxnum = max(checknum, maxnum)\n# visited.add(n)\n\n# if checknum-1 in cnt:\n# checknumber(checknum-1, cnt,[minnum, maxnum])\n# if checknum+1 in cnt:\n# checknumber(checknum+1, cnt, [minnum, maxnum])\n \n# for n in nums:\n# checknumber(n, cnt, [minnum, maxnum])\n \n# return (ans[1]-ans[0])+1", "step-5": null, "step-ids": [ 0, 1, 2, 3 ] }
[ 0, 1, 2, 3 ]
from rest_framework import serializers from . import models class RaumSerializer(serializers.ModelSerializer): class Meta: model = models.Raum fields = [ "Raumnummer", "Anzahl_Sitzplaetze", "Beamer", "Whiteboard", ] class ZeitraumSerializer(serializers.ModelSerializer): class Meta: model = models.Zeitraum fields = [ "Vorlesungszeit", "EndTime", "Datum", "StartTime", ] class RaumbelegungSerializer(serializers.ModelSerializer): class Meta: model = models.Raumbelegung fields = [ "Belegt", "Belegungsgrund", ]
normal
{ "blob_id": "451c353a949458f5f71783c4aba1888c40018bfa", "index": 9400, "step-1": "<mask token>\n\n\nclass RaumbelegungSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = models.Raumbelegung\n fields = ['Belegt', 'Belegungsgrund']\n", "step-2": "<mask token>\n\n\nclass ZeitraumSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = models.Zeitraum\n fields = ['Vorlesungszeit', 'EndTime', 'Datum', 'StartTime']\n\n\nclass RaumbelegungSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = models.Raumbelegung\n fields = ['Belegt', 'Belegungsgrund']\n", "step-3": "<mask token>\n\n\nclass RaumSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = models.Raum\n fields = ['Raumnummer', 'Anzahl_Sitzplaetze', 'Beamer', 'Whiteboard']\n\n\nclass ZeitraumSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = models.Zeitraum\n fields = ['Vorlesungszeit', 'EndTime', 'Datum', 'StartTime']\n\n\nclass RaumbelegungSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = models.Raumbelegung\n fields = ['Belegt', 'Belegungsgrund']\n", "step-4": "from rest_framework import serializers\nfrom . import models\n\n\nclass RaumSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = models.Raum\n fields = ['Raumnummer', 'Anzahl_Sitzplaetze', 'Beamer', 'Whiteboard']\n\n\nclass ZeitraumSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = models.Zeitraum\n fields = ['Vorlesungszeit', 'EndTime', 'Datum', 'StartTime']\n\n\nclass RaumbelegungSerializer(serializers.ModelSerializer):\n\n\n class Meta:\n model = models.Raumbelegung\n fields = ['Belegt', 'Belegungsgrund']\n", "step-5": "from rest_framework import serializers\n\nfrom . import models\n\n\nclass RaumSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = models.Raum\n fields = [\n \"Raumnummer\",\n \"Anzahl_Sitzplaetze\",\n \"Beamer\",\n \"Whiteboard\",\n ]\n\nclass ZeitraumSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = models.Zeitraum\n fields = [\n \"Vorlesungszeit\",\n \"EndTime\",\n \"Datum\",\n \"StartTime\",\n ]\n\nclass RaumbelegungSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = models.Raumbelegung\n fields = [\n \"Belegt\",\n \"Belegungsgrund\",\n ]\n", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
<|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class ChildImport(object): <|reserved_special_token_0|> <|reserved_special_token_1|> <|reserved_special_token_0|> class ChildImport(object): def __init__(self, scriptName=None): x = Child.objects.create(first_name='Timmy', last_name='Thompson', school=School.objects.get(pk=1)) x.family.add(Person.objects.get(pk=1)) x.family.add(Person.objects.get(pk=2)) x.save() x = Child.objects.create(first_name='Jimmy', last_name='Johnson', school=School.objects.get(pk=2)) x.family.add(Person.objects.get(pk=2)) x.family.add(Person.objects.get(pk=1)) x.save() x = Child.objects.create(first_name='Bart', last_name='Simpson', school=School.objects.get(pk=3)) x.family.add(Person.objects.get(pk=3)) x.family.add(Person.objects.get(pk=4)) x.save() x = Child.objects.create(first_name='Lisa', last_name='Simpson', school=School.objects.get(pk=4)) x.family.add(Person.objects.get(pk=4)) x.family.add(Person.objects.get(pk=3)) x.save() x = Child.objects.create(first_name='Andrew', last_name='Becker', school=School.objects.get(pk=5)) x.family.add(Person.objects.get(pk=5)) x.family.add(Person.objects.get(pk=6)) x.save() x = Child.objects.create(first_name='Jasmine', last_name='Goulette', school=School.objects.get(pk=6)) x.family.add(Person.objects.get(pk=6)) x.family.add(Person.objects.get(pk=5)) x.save() x = Child.objects.create(first_name='Kristina', last_name='Murry', school=School.objects.get(pk=7)) x.family.add(Person.objects.get(pk=7)) x.family.add(Person.objects.get(pk=8)) x.save() x = Child.objects.create(first_name='Andrew', last_name= 'Scheonster', school=School.objects.get(pk=8)) x.family.add(Person.objects.get(pk=8)) x.family.add(Person.objects.get(pk=7)) x.save() <|reserved_special_token_1|> <|reserved_special_token_0|> from Data_Base.models import School, Person, Child <|reserved_special_token_0|> class ChildImport(object): def __init__(self, scriptName=None): x = Child.objects.create(first_name='Timmy', last_name='Thompson', school=School.objects.get(pk=1)) x.family.add(Person.objects.get(pk=1)) x.family.add(Person.objects.get(pk=2)) x.save() x = Child.objects.create(first_name='Jimmy', last_name='Johnson', school=School.objects.get(pk=2)) x.family.add(Person.objects.get(pk=2)) x.family.add(Person.objects.get(pk=1)) x.save() x = Child.objects.create(first_name='Bart', last_name='Simpson', school=School.objects.get(pk=3)) x.family.add(Person.objects.get(pk=3)) x.family.add(Person.objects.get(pk=4)) x.save() x = Child.objects.create(first_name='Lisa', last_name='Simpson', school=School.objects.get(pk=4)) x.family.add(Person.objects.get(pk=4)) x.family.add(Person.objects.get(pk=3)) x.save() x = Child.objects.create(first_name='Andrew', last_name='Becker', school=School.objects.get(pk=5)) x.family.add(Person.objects.get(pk=5)) x.family.add(Person.objects.get(pk=6)) x.save() x = Child.objects.create(first_name='Jasmine', last_name='Goulette', school=School.objects.get(pk=6)) x.family.add(Person.objects.get(pk=6)) x.family.add(Person.objects.get(pk=5)) x.save() x = Child.objects.create(first_name='Kristina', last_name='Murry', school=School.objects.get(pk=7)) x.family.add(Person.objects.get(pk=7)) x.family.add(Person.objects.get(pk=8)) x.save() x = Child.objects.create(first_name='Andrew', last_name= 'Scheonster', school=School.objects.get(pk=8)) x.family.add(Person.objects.get(pk=8)) x.family.add(Person.objects.get(pk=7)) x.save() <|reserved_special_token_1|> """ Python Package Support """ # Not applicable """ Django Package Support """ # Not applicable """ Internal Package Support """ from Data_Base.models import School, Person, Child """ Data_Base/Data/Imports/child_import.py Author: Matthew J Swann; Yong Kin; Bradon Atkins; and Adam Carter Version: 1.0 Last Update: 2013-04-07 Update By: Matthew J Swann Importing data to the person table. """ class ChildImport(object): def __init__(self, scriptName=None): # 1 x = Child.objects.create( first_name = 'Timmy', last_name = 'Thompson', school = School.objects.get(pk=1), ) x.family.add(Person.objects.get(pk=1)) x.family.add(Person.objects.get(pk=2)) x.save() # 2 x = Child.objects.create( first_name = 'Jimmy', last_name = 'Johnson', school = School.objects.get(pk=2), ) x.family.add(Person.objects.get(pk=2)) x.family.add(Person.objects.get(pk=1)) x.save() # 3 x = Child.objects.create( first_name = 'Bart', last_name = 'Simpson', school = School.objects.get(pk=3), ) x.family.add(Person.objects.get(pk=3)) x.family.add(Person.objects.get(pk=4)) x.save() # 4 x = Child.objects.create( first_name = 'Lisa', last_name = 'Simpson', school = School.objects.get(pk=4), ) x.family.add(Person.objects.get(pk=4)) x.family.add(Person.objects.get(pk=3)) x.save() # 5 x = Child.objects.create( first_name = 'Andrew', last_name = 'Becker', school = School.objects.get(pk=5), ) x.family.add(Person.objects.get(pk=5)) x.family.add(Person.objects.get(pk=6)) x.save() # 6 x = Child.objects.create( first_name = 'Jasmine', last_name = 'Goulette', school = School.objects.get(pk=6), ) x.family.add(Person.objects.get(pk=6)) x.family.add(Person.objects.get(pk=5)) x.save() # 7 x = Child.objects.create( first_name = 'Kristina', last_name = 'Murry', school = School.objects.get(pk=7), ) x.family.add(Person.objects.get(pk=7)) x.family.add(Person.objects.get(pk=8)) x.save() # 8 x = Child.objects.create( first_name = 'Andrew', last_name = 'Scheonster', school = School.objects.get(pk=8), ) x.family.add(Person.objects.get(pk=8)) x.family.add(Person.objects.get(pk=7)) x.save()
flexible
{ "blob_id": "d0287b057530883a50ad9c1e5e74dce10cd825b6", "index": 7961, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\nclass ChildImport(object):\n <mask token>\n", "step-3": "<mask token>\n\n\nclass ChildImport(object):\n\n def __init__(self, scriptName=None):\n x = Child.objects.create(first_name='Timmy', last_name='Thompson',\n school=School.objects.get(pk=1))\n x.family.add(Person.objects.get(pk=1))\n x.family.add(Person.objects.get(pk=2))\n x.save()\n x = Child.objects.create(first_name='Jimmy', last_name='Johnson',\n school=School.objects.get(pk=2))\n x.family.add(Person.objects.get(pk=2))\n x.family.add(Person.objects.get(pk=1))\n x.save()\n x = Child.objects.create(first_name='Bart', last_name='Simpson',\n school=School.objects.get(pk=3))\n x.family.add(Person.objects.get(pk=3))\n x.family.add(Person.objects.get(pk=4))\n x.save()\n x = Child.objects.create(first_name='Lisa', last_name='Simpson',\n school=School.objects.get(pk=4))\n x.family.add(Person.objects.get(pk=4))\n x.family.add(Person.objects.get(pk=3))\n x.save()\n x = Child.objects.create(first_name='Andrew', last_name='Becker',\n school=School.objects.get(pk=5))\n x.family.add(Person.objects.get(pk=5))\n x.family.add(Person.objects.get(pk=6))\n x.save()\n x = Child.objects.create(first_name='Jasmine', last_name='Goulette',\n school=School.objects.get(pk=6))\n x.family.add(Person.objects.get(pk=6))\n x.family.add(Person.objects.get(pk=5))\n x.save()\n x = Child.objects.create(first_name='Kristina', last_name='Murry',\n school=School.objects.get(pk=7))\n x.family.add(Person.objects.get(pk=7))\n x.family.add(Person.objects.get(pk=8))\n x.save()\n x = Child.objects.create(first_name='Andrew', last_name=\n 'Scheonster', school=School.objects.get(pk=8))\n x.family.add(Person.objects.get(pk=8))\n x.family.add(Person.objects.get(pk=7))\n x.save()\n", "step-4": "<mask token>\nfrom Data_Base.models import School, Person, Child\n<mask token>\n\n\nclass ChildImport(object):\n\n def __init__(self, scriptName=None):\n x = Child.objects.create(first_name='Timmy', last_name='Thompson',\n school=School.objects.get(pk=1))\n x.family.add(Person.objects.get(pk=1))\n x.family.add(Person.objects.get(pk=2))\n x.save()\n x = Child.objects.create(first_name='Jimmy', last_name='Johnson',\n school=School.objects.get(pk=2))\n x.family.add(Person.objects.get(pk=2))\n x.family.add(Person.objects.get(pk=1))\n x.save()\n x = Child.objects.create(first_name='Bart', last_name='Simpson',\n school=School.objects.get(pk=3))\n x.family.add(Person.objects.get(pk=3))\n x.family.add(Person.objects.get(pk=4))\n x.save()\n x = Child.objects.create(first_name='Lisa', last_name='Simpson',\n school=School.objects.get(pk=4))\n x.family.add(Person.objects.get(pk=4))\n x.family.add(Person.objects.get(pk=3))\n x.save()\n x = Child.objects.create(first_name='Andrew', last_name='Becker',\n school=School.objects.get(pk=5))\n x.family.add(Person.objects.get(pk=5))\n x.family.add(Person.objects.get(pk=6))\n x.save()\n x = Child.objects.create(first_name='Jasmine', last_name='Goulette',\n school=School.objects.get(pk=6))\n x.family.add(Person.objects.get(pk=6))\n x.family.add(Person.objects.get(pk=5))\n x.save()\n x = Child.objects.create(first_name='Kristina', last_name='Murry',\n school=School.objects.get(pk=7))\n x.family.add(Person.objects.get(pk=7))\n x.family.add(Person.objects.get(pk=8))\n x.save()\n x = Child.objects.create(first_name='Andrew', last_name=\n 'Scheonster', school=School.objects.get(pk=8))\n x.family.add(Person.objects.get(pk=8))\n x.family.add(Person.objects.get(pk=7))\n x.save()\n", "step-5": "\"\"\" Python Package Support \"\"\"\n# Not applicable\n\n\"\"\" Django Package Support \"\"\"\n# Not applicable\n\n\"\"\" Internal Package Support \"\"\"\nfrom Data_Base.models import School, Person, Child\n\n\"\"\"\n Data_Base/Data/Imports/child_import.py\n \n Author: Matthew J Swann; \n Yong Kin; \n Bradon Atkins; and \n Adam Carter\n \n Version: 1.0\n Last Update: 2013-04-07\n Update By: Matthew J Swann\n \n Importing data to the person table.\n\n \"\"\"\n \nclass ChildImport(object):\n \n def __init__(self, scriptName=None):\n \n # 1\n x = Child.objects.create(\n first_name = 'Timmy',\n last_name = 'Thompson',\n school = School.objects.get(pk=1), \n )\n x.family.add(Person.objects.get(pk=1))\n x.family.add(Person.objects.get(pk=2))\n x.save()\n\n # 2\n x = Child.objects.create(\n first_name = 'Jimmy',\n last_name = 'Johnson',\n school = School.objects.get(pk=2), \n )\n x.family.add(Person.objects.get(pk=2))\n x.family.add(Person.objects.get(pk=1))\n x.save()\n \n # 3\n x = Child.objects.create(\n first_name = 'Bart',\n last_name = 'Simpson',\n school = School.objects.get(pk=3), \n )\n x.family.add(Person.objects.get(pk=3))\n x.family.add(Person.objects.get(pk=4))\n x.save()\n \n # 4\n x = Child.objects.create(\n first_name = 'Lisa',\n last_name = 'Simpson',\n school = School.objects.get(pk=4), \n )\n x.family.add(Person.objects.get(pk=4))\n x.family.add(Person.objects.get(pk=3))\n x.save()\n \n # 5\n x = Child.objects.create(\n first_name = 'Andrew',\n last_name = 'Becker',\n school = School.objects.get(pk=5), \n )\n x.family.add(Person.objects.get(pk=5))\n x.family.add(Person.objects.get(pk=6))\n x.save()\n \n # 6\n x = Child.objects.create(\n first_name = 'Jasmine',\n last_name = 'Goulette',\n school = School.objects.get(pk=6), \n )\n x.family.add(Person.objects.get(pk=6))\n x.family.add(Person.objects.get(pk=5))\n x.save()\n \n # 7\n x = Child.objects.create(\n first_name = 'Kristina',\n last_name = 'Murry',\n school = School.objects.get(pk=7), \n )\n x.family.add(Person.objects.get(pk=7))\n x.family.add(Person.objects.get(pk=8))\n x.save()\n\n # 8\n x = Child.objects.create(\n first_name = 'Andrew',\n last_name = 'Scheonster',\n school = School.objects.get(pk=8), \n )\n x.family.add(Person.objects.get(pk=8))\n x.family.add(Person.objects.get(pk=7))\n x.save()\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
import json import sys import os # Change to Singularity working directory. os.chdir('/mnt/cwd') # Take subset index as argument subset_index = sys.argv[1] # Open up subset matching this. with open('/mnt/scripts/outputs/instcat_list_subset'+str(subset_index)+'.json', 'r') as f: instcat_list_subset = json.load(f) # Import instcat trimmer sys.path.append('/mnt/scripts') import instcat_trimmer as ict ict.determine_instcat_work(instcat_list_subset, '/mnt/scripts/outputs/worklist_subset'+str(subset_index)+'.json')
normal
{ "blob_id": "e2e5ca388d67f2a13eaef6067fc19e2dfe284a55", "index": 4469, "step-1": "<mask token>\n", "step-2": "<mask token>\nos.chdir('/mnt/cwd')\n<mask token>\nwith open('/mnt/scripts/outputs/instcat_list_subset' + str(subset_index) +\n '.json', 'r') as f:\n instcat_list_subset = json.load(f)\nsys.path.append('/mnt/scripts')\n<mask token>\nict.determine_instcat_work(instcat_list_subset, \n '/mnt/scripts/outputs/worklist_subset' + str(subset_index) + '.json')\n", "step-3": "<mask token>\nos.chdir('/mnt/cwd')\nsubset_index = sys.argv[1]\nwith open('/mnt/scripts/outputs/instcat_list_subset' + str(subset_index) +\n '.json', 'r') as f:\n instcat_list_subset = json.load(f)\nsys.path.append('/mnt/scripts')\n<mask token>\nict.determine_instcat_work(instcat_list_subset, \n '/mnt/scripts/outputs/worklist_subset' + str(subset_index) + '.json')\n", "step-4": "import json\nimport sys\nimport os\nos.chdir('/mnt/cwd')\nsubset_index = sys.argv[1]\nwith open('/mnt/scripts/outputs/instcat_list_subset' + str(subset_index) +\n '.json', 'r') as f:\n instcat_list_subset = json.load(f)\nsys.path.append('/mnt/scripts')\nimport instcat_trimmer as ict\nict.determine_instcat_work(instcat_list_subset, \n '/mnt/scripts/outputs/worklist_subset' + str(subset_index) + '.json')\n", "step-5": "import json\nimport sys\nimport os\n\n# Change to Singularity working directory.\nos.chdir('/mnt/cwd')\n\n# Take subset index as argument\nsubset_index = sys.argv[1]\n\n# Open up subset matching this.\nwith open('/mnt/scripts/outputs/instcat_list_subset'+str(subset_index)+'.json', 'r') as f:\n instcat_list_subset = json.load(f)\n\n# Import instcat trimmer\nsys.path.append('/mnt/scripts')\nimport instcat_trimmer as ict\n\nict.determine_instcat_work(instcat_list_subset, '/mnt/scripts/outputs/worklist_subset'+str(subset_index)+'.json')\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]
<|reserved_special_token_0|> def transform_data2(fn, *args): for arg in args: print(fn(arg)) <|reserved_special_token_0|> <|reserved_special_token_1|> def transform_data(fn): print(fn(10)) <|reserved_special_token_0|> def transform_data2(fn, *args): for arg in args: print(fn(arg)) <|reserved_special_token_0|> <|reserved_special_token_1|> def transform_data(fn): print(fn(10)) <|reserved_special_token_0|> def transform_data2(fn, *args): for arg in args: print(fn(arg)) <|reserved_special_token_0|> def transform_data2(fn, *args): for arg in args: print('Result: {:^20.2f}'.format(fn(arg))) <|reserved_special_token_0|> <|reserved_special_token_1|> def transform_data(fn): print(fn(10)) transform_data(lambda data: data / 5) def transform_data2(fn, *args): for arg in args: print(fn(arg)) transform_data2(lambda data: data / 5, 10, 15, 22, 30) def transform_data2(fn, *args): for arg in args: print('Result: {:^20.2f}'.format(fn(arg))) transform_data2(lambda data: data / 5, 10, 15, 22, 30) <|reserved_special_token_1|> # 1 def transform_data(fn): print(fn(10)) # 2 transform_data(lambda data: data / 5) # 3 def transform_data2(fn, *args): for arg in args: print(fn(arg)) transform_data2(lambda data: data / 5, 10, 15, 22, 30) # 4 def transform_data2(fn, *args): for arg in args: print('Result: {:^20.2f}'.format(fn(arg))) transform_data2(lambda data: data / 5, 10, 15, 22, 30)
flexible
{ "blob_id": "c87e6f8780bf8d9097f200c7f2f0faf55beb480c", "index": 52, "step-1": "<mask token>\n\n\ndef transform_data2(fn, *args):\n for arg in args:\n print(fn(arg))\n\n\n<mask token>\n", "step-2": "def transform_data(fn):\n print(fn(10))\n\n\n<mask token>\n\n\ndef transform_data2(fn, *args):\n for arg in args:\n print(fn(arg))\n\n\n<mask token>\n", "step-3": "def transform_data(fn):\n print(fn(10))\n\n\n<mask token>\n\n\ndef transform_data2(fn, *args):\n for arg in args:\n print(fn(arg))\n\n\n<mask token>\n\n\ndef transform_data2(fn, *args):\n for arg in args:\n print('Result: {:^20.2f}'.format(fn(arg)))\n\n\n<mask token>\n", "step-4": "def transform_data(fn):\n print(fn(10))\n\n\ntransform_data(lambda data: data / 5)\n\n\ndef transform_data2(fn, *args):\n for arg in args:\n print(fn(arg))\n\n\ntransform_data2(lambda data: data / 5, 10, 15, 22, 30)\n\n\ndef transform_data2(fn, *args):\n for arg in args:\n print('Result: {:^20.2f}'.format(fn(arg)))\n\n\ntransform_data2(lambda data: data / 5, 10, 15, 22, 30)\n", "step-5": "# 1\r\ndef transform_data(fn):\r\n print(fn(10))\r\n\r\n# 2\r\ntransform_data(lambda data: data / 5)\r\n\r\n# 3\r\ndef transform_data2(fn, *args):\r\n for arg in args:\r\n print(fn(arg))\r\n\r\ntransform_data2(lambda data: data / 5, 10, 15, 22, 30)\r\n\r\n# 4\r\ndef transform_data2(fn, *args):\r\n for arg in args:\r\n print('Result: {:^20.2f}'.format(fn(arg)))\r\n\r\ntransform_data2(lambda data: data / 5, 10, 15, 22, 30)", "step-ids": [ 1, 2, 3, 4, 5 ] }
[ 1, 2, 3, 4, 5 ]
from app import app from flask import render_template, request from app.models import model, formopener @app.route('/', methods=['GET', 'POST']) @app.route('/index') def index(): return render_template("index.html") @app.route('/personality', methods=['GET', 'POST']) def personfont(): user_input=dict(request.form) print(user_input) x=user_input["personality"] print(x) output=model.personfont(x) print(output) return render_template('index2.html', output=output)
normal
{ "blob_id": "bb3c4039ff224c0ca0305778b938ef969c196033", "index": 8759, "step-1": "<mask token>\n", "step-2": "<mask token>\n\n\n@app.route('/', methods=['GET', 'POST'])\n@app.route('/index')\ndef index():\n return render_template('index.html')\n\n\n<mask token>\n", "step-3": "<mask token>\n\n\n@app.route('/', methods=['GET', 'POST'])\n@app.route('/index')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/personality', methods=['GET', 'POST'])\ndef personfont():\n user_input = dict(request.form)\n print(user_input)\n x = user_input['personality']\n print(x)\n output = model.personfont(x)\n print(output)\n return render_template('index2.html', output=output)\n", "step-4": "from app import app\nfrom flask import render_template, request\nfrom app.models import model, formopener\n\n\n@app.route('/', methods=['GET', 'POST'])\n@app.route('/index')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/personality', methods=['GET', 'POST'])\ndef personfont():\n user_input = dict(request.form)\n print(user_input)\n x = user_input['personality']\n print(x)\n output = model.personfont(x)\n print(output)\n return render_template('index2.html', output=output)\n", "step-5": "from app import app\nfrom flask import render_template, request\nfrom app.models import model, formopener\n\n@app.route('/', methods=['GET', 'POST'])\n@app.route('/index')\ndef index():\n return render_template(\"index.html\")\n\n@app.route('/personality', methods=['GET', 'POST'])\ndef personfont():\n user_input=dict(request.form)\n print(user_input)\n x=user_input[\"personality\"]\n print(x)\n output=model.personfont(x)\n print(output)\n return render_template('index2.html', output=output)\n", "step-ids": [ 0, 1, 2, 3, 4 ] }
[ 0, 1, 2, 3, 4 ]